babylon.no-module.max.js 4.9 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180
  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. /**
  8500. * Will get a number picked randomly between factor1 and factor2.
  8501. * If factor2 is undefined then factor1 will be used
  8502. * @returns the picked number
  8503. */
  8504. FactorGradient.prototype.getFactor = function () {
  8505. if (this.factor2 === undefined) {
  8506. return this.factor1;
  8507. }
  8508. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8509. };
  8510. return FactorGradient;
  8511. }());
  8512. BABYLON.FactorGradient = FactorGradient;
  8513. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8514. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8515. var LoadFileError = /** @class */ (function (_super) {
  8516. __extends(LoadFileError, _super);
  8517. function LoadFileError(message, request) {
  8518. var _this = _super.call(this, message) || this;
  8519. _this.request = request;
  8520. _this.name = "LoadFileError";
  8521. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8522. return _this;
  8523. }
  8524. // Polyfill for Object.setPrototypeOf if necessary.
  8525. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8526. return LoadFileError;
  8527. }(Error));
  8528. BABYLON.LoadFileError = LoadFileError;
  8529. var RetryStrategy = /** @class */ (function () {
  8530. function RetryStrategy() {
  8531. }
  8532. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8533. if (maxRetries === void 0) { maxRetries = 3; }
  8534. if (baseInterval === void 0) { baseInterval = 500; }
  8535. return function (url, request, retryIndex) {
  8536. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8537. return -1;
  8538. }
  8539. return Math.pow(2, retryIndex) * baseInterval;
  8540. };
  8541. };
  8542. return RetryStrategy;
  8543. }());
  8544. BABYLON.RetryStrategy = RetryStrategy;
  8545. // Screenshots
  8546. var screenshotCanvas;
  8547. var cloneValue = function (source, destinationObject) {
  8548. if (!source)
  8549. return null;
  8550. if (source instanceof BABYLON.Mesh) {
  8551. return null;
  8552. }
  8553. if (source instanceof BABYLON.SubMesh) {
  8554. return source.clone(destinationObject);
  8555. }
  8556. else if (source.clone) {
  8557. return source.clone();
  8558. }
  8559. return null;
  8560. };
  8561. var Tools = /** @class */ (function () {
  8562. function Tools() {
  8563. }
  8564. /**
  8565. * Interpolates between a and b via alpha
  8566. * @param a The lower value (returned when alpha = 0)
  8567. * @param b The upper value (returned when alpha = 1)
  8568. * @param alpha The interpolation-factor
  8569. * @return The mixed value
  8570. */
  8571. Tools.Mix = function (a, b, alpha) {
  8572. return a * (1 - alpha) + b * alpha;
  8573. };
  8574. Tools.Instantiate = function (className) {
  8575. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8576. return Tools.RegisteredExternalClasses[className];
  8577. }
  8578. var arr = className.split(".");
  8579. var fn = (window || this);
  8580. for (var i = 0, len = arr.length; i < len; i++) {
  8581. fn = fn[arr[i]];
  8582. }
  8583. if (typeof fn !== "function") {
  8584. return null;
  8585. }
  8586. return fn;
  8587. };
  8588. /**
  8589. * Provides a slice function that will work even on IE
  8590. * @param data defines the array to slice
  8591. * @param start defines the start of the data (optional)
  8592. * @param end defines the end of the data (optional)
  8593. * @returns the new sliced array
  8594. */
  8595. Tools.Slice = function (data, start, end) {
  8596. if (data.slice) {
  8597. return data.slice(start, end);
  8598. }
  8599. return Array.prototype.slice.call(data, start, end);
  8600. };
  8601. Tools.SetImmediate = function (action) {
  8602. if (window.setImmediate) {
  8603. window.setImmediate(action);
  8604. }
  8605. else {
  8606. setTimeout(action, 1);
  8607. }
  8608. };
  8609. Tools.IsExponentOfTwo = function (value) {
  8610. var count = 1;
  8611. do {
  8612. count *= 2;
  8613. } while (count < value);
  8614. return count === value;
  8615. };
  8616. /**
  8617. * Returns the nearest 32-bit single precision float representation of a Number
  8618. * @param value A Number. If the parameter is of a different type, it will get converted
  8619. * to a number or to NaN if it cannot be converted
  8620. * @returns number
  8621. */
  8622. Tools.FloatRound = function (value) {
  8623. if (Math.fround) {
  8624. return Math.fround(value);
  8625. }
  8626. return (Tools._tmpFloatArray[0] = value);
  8627. };
  8628. /**
  8629. * Find the next highest power of two.
  8630. * @param x Number to start search from.
  8631. * @return Next highest power of two.
  8632. */
  8633. Tools.CeilingPOT = function (x) {
  8634. x--;
  8635. x |= x >> 1;
  8636. x |= x >> 2;
  8637. x |= x >> 4;
  8638. x |= x >> 8;
  8639. x |= x >> 16;
  8640. x++;
  8641. return x;
  8642. };
  8643. /**
  8644. * Find the next lowest power of two.
  8645. * @param x Number to start search from.
  8646. * @return Next lowest power of two.
  8647. */
  8648. Tools.FloorPOT = function (x) {
  8649. x = x | (x >> 1);
  8650. x = x | (x >> 2);
  8651. x = x | (x >> 4);
  8652. x = x | (x >> 8);
  8653. x = x | (x >> 16);
  8654. return x - (x >> 1);
  8655. };
  8656. /**
  8657. * Find the nearest power of two.
  8658. * @param x Number to start search from.
  8659. * @return Next nearest power of two.
  8660. */
  8661. Tools.NearestPOT = function (x) {
  8662. var c = Tools.CeilingPOT(x);
  8663. var f = Tools.FloorPOT(x);
  8664. return (c - x) > (x - f) ? f : c;
  8665. };
  8666. Tools.GetExponentOfTwo = function (value, max, mode) {
  8667. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8668. var pot;
  8669. switch (mode) {
  8670. case BABYLON.Engine.SCALEMODE_FLOOR:
  8671. pot = Tools.FloorPOT(value);
  8672. break;
  8673. case BABYLON.Engine.SCALEMODE_NEAREST:
  8674. pot = Tools.NearestPOT(value);
  8675. break;
  8676. case BABYLON.Engine.SCALEMODE_CEILING:
  8677. default:
  8678. pot = Tools.CeilingPOT(value);
  8679. break;
  8680. }
  8681. return Math.min(pot, max);
  8682. };
  8683. Tools.GetFilename = function (path) {
  8684. var index = path.lastIndexOf("/");
  8685. if (index < 0)
  8686. return path;
  8687. return path.substring(index + 1);
  8688. };
  8689. /**
  8690. * Extracts the "folder" part of a path (everything before the filename).
  8691. * @param uri The URI to extract the info from
  8692. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8693. * @returns The "folder" part of the path
  8694. */
  8695. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8696. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8697. var index = uri.lastIndexOf("/");
  8698. if (index < 0) {
  8699. if (returnUnchangedIfNoSlash) {
  8700. return uri;
  8701. }
  8702. return "";
  8703. }
  8704. return uri.substring(0, index + 1);
  8705. };
  8706. Tools.GetDOMTextContent = function (element) {
  8707. var result = "";
  8708. var child = element.firstChild;
  8709. while (child) {
  8710. if (child.nodeType === 3) {
  8711. result += child.textContent;
  8712. }
  8713. child = child.nextSibling;
  8714. }
  8715. return result;
  8716. };
  8717. Tools.ToDegrees = function (angle) {
  8718. return angle * 180 / Math.PI;
  8719. };
  8720. Tools.ToRadians = function (angle) {
  8721. return angle * Math.PI / 180;
  8722. };
  8723. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8724. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8725. var output = "";
  8726. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8727. var i = 0;
  8728. var bytes = new Uint8Array(buffer);
  8729. while (i < bytes.length) {
  8730. chr1 = bytes[i++];
  8731. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8732. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8733. enc1 = chr1 >> 2;
  8734. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8735. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8736. enc4 = chr3 & 63;
  8737. if (isNaN(chr2)) {
  8738. enc3 = enc4 = 64;
  8739. }
  8740. else if (isNaN(chr3)) {
  8741. enc4 = 64;
  8742. }
  8743. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8744. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8745. }
  8746. return "data:image/png;base64," + output;
  8747. };
  8748. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8749. if (bias === void 0) { bias = null; }
  8750. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8751. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8752. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8753. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8754. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8755. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8756. }
  8757. if (bias) {
  8758. minimum.x -= minimum.x * bias.x + bias.y;
  8759. minimum.y -= minimum.y * bias.x + bias.y;
  8760. minimum.z -= minimum.z * bias.x + bias.y;
  8761. maximum.x += maximum.x * bias.x + bias.y;
  8762. maximum.y += maximum.y * bias.x + bias.y;
  8763. maximum.z += maximum.z * bias.x + bias.y;
  8764. }
  8765. return {
  8766. minimum: minimum,
  8767. maximum: maximum
  8768. };
  8769. };
  8770. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8771. if (bias === void 0) { bias = null; }
  8772. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8773. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8774. if (!stride) {
  8775. stride = 3;
  8776. }
  8777. for (var index = start; index < start + count; index++) {
  8778. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8779. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8780. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8781. }
  8782. if (bias) {
  8783. minimum.x -= minimum.x * bias.x + bias.y;
  8784. minimum.y -= minimum.y * bias.x + bias.y;
  8785. minimum.z -= minimum.z * bias.x + bias.y;
  8786. maximum.x += maximum.x * bias.x + bias.y;
  8787. maximum.y += maximum.y * bias.x + bias.y;
  8788. maximum.z += maximum.z * bias.x + bias.y;
  8789. }
  8790. return {
  8791. minimum: minimum,
  8792. maximum: maximum
  8793. };
  8794. };
  8795. Tools.Vector2ArrayFeeder = function (array) {
  8796. return function (index) {
  8797. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8798. var length = isFloatArray ? array.length / 2 : array.length;
  8799. if (index >= length) {
  8800. return null;
  8801. }
  8802. if (isFloatArray) {
  8803. var fa = array;
  8804. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8805. }
  8806. var a = array;
  8807. return a[index];
  8808. };
  8809. };
  8810. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8811. if (bias === void 0) { bias = null; }
  8812. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8813. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8814. var i = 0;
  8815. var cur = feeder(i++);
  8816. while (cur) {
  8817. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8818. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8819. cur = feeder(i++);
  8820. }
  8821. if (bias) {
  8822. minimum.x -= minimum.x * bias.x + bias.y;
  8823. minimum.y -= minimum.y * bias.x + bias.y;
  8824. maximum.x += maximum.x * bias.x + bias.y;
  8825. maximum.y += maximum.y * bias.x + bias.y;
  8826. }
  8827. return {
  8828. minimum: minimum,
  8829. maximum: maximum
  8830. };
  8831. };
  8832. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8833. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8834. return null;
  8835. return Array.isArray(obj) ? obj : [obj];
  8836. };
  8837. // Misc.
  8838. Tools.GetPointerPrefix = function () {
  8839. var eventPrefix = "pointer";
  8840. // Check if pointer events are supported
  8841. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8842. eventPrefix = "mouse";
  8843. }
  8844. return eventPrefix;
  8845. };
  8846. /**
  8847. * @param func - the function to be called
  8848. * @param requester - the object that will request the next frame. Falls back to window.
  8849. */
  8850. Tools.QueueNewFrame = function (func, requester) {
  8851. if (!Tools.IsWindowObjectExist()) {
  8852. return setTimeout(func, 16);
  8853. }
  8854. if (!requester) {
  8855. requester = window;
  8856. }
  8857. if (requester.requestAnimationFrame) {
  8858. return requester.requestAnimationFrame(func);
  8859. }
  8860. else if (requester.msRequestAnimationFrame) {
  8861. return requester.msRequestAnimationFrame(func);
  8862. }
  8863. else if (requester.webkitRequestAnimationFrame) {
  8864. return requester.webkitRequestAnimationFrame(func);
  8865. }
  8866. else if (requester.mozRequestAnimationFrame) {
  8867. return requester.mozRequestAnimationFrame(func);
  8868. }
  8869. else if (requester.oRequestAnimationFrame) {
  8870. return requester.oRequestAnimationFrame(func);
  8871. }
  8872. else {
  8873. return window.setTimeout(func, 16);
  8874. }
  8875. };
  8876. Tools.RequestFullscreen = function (element) {
  8877. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8878. if (!requestFunction)
  8879. return;
  8880. requestFunction.call(element);
  8881. };
  8882. Tools.ExitFullscreen = function () {
  8883. if (document.exitFullscreen) {
  8884. document.exitFullscreen();
  8885. }
  8886. else if (document.mozCancelFullScreen) {
  8887. document.mozCancelFullScreen();
  8888. }
  8889. else if (document.webkitCancelFullScreen) {
  8890. document.webkitCancelFullScreen();
  8891. }
  8892. else if (document.msCancelFullScreen) {
  8893. document.msCancelFullScreen();
  8894. }
  8895. };
  8896. Tools.SetCorsBehavior = function (url, element) {
  8897. if (url && url.indexOf("data:") === 0) {
  8898. return;
  8899. }
  8900. if (Tools.CorsBehavior) {
  8901. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8902. element.crossOrigin = Tools.CorsBehavior;
  8903. }
  8904. else {
  8905. var result = Tools.CorsBehavior(url);
  8906. if (result) {
  8907. element.crossOrigin = result;
  8908. }
  8909. }
  8910. }
  8911. };
  8912. // External files
  8913. Tools.CleanUrl = function (url) {
  8914. url = url.replace(/#/mg, "%23");
  8915. return url;
  8916. };
  8917. /**
  8918. * Loads an image as an HTMLImageElement.
  8919. * @param input url string, ArrayBuffer, or Blob to load
  8920. * @param onLoad callback called when the image successfully loads
  8921. * @param onError callback called when the image fails to load
  8922. * @param database database for caching
  8923. * @returns the HTMLImageElement of the loaded image
  8924. */
  8925. Tools.LoadImage = function (input, onLoad, onError, database) {
  8926. var url;
  8927. var usingObjectURL = false;
  8928. if (input instanceof ArrayBuffer) {
  8929. url = URL.createObjectURL(new Blob([input]));
  8930. usingObjectURL = true;
  8931. }
  8932. else if (input instanceof Blob) {
  8933. url = URL.createObjectURL(input);
  8934. usingObjectURL = true;
  8935. }
  8936. else {
  8937. url = Tools.CleanUrl(input);
  8938. url = Tools.PreprocessUrl(input);
  8939. }
  8940. var img = new Image();
  8941. Tools.SetCorsBehavior(url, img);
  8942. var loadHandler = function () {
  8943. if (usingObjectURL && img.src) {
  8944. URL.revokeObjectURL(img.src);
  8945. }
  8946. img.removeEventListener("load", loadHandler);
  8947. img.removeEventListener("error", errorHandler);
  8948. onLoad(img);
  8949. };
  8950. var errorHandler = function (err) {
  8951. if (usingObjectURL && img.src) {
  8952. URL.revokeObjectURL(img.src);
  8953. }
  8954. img.removeEventListener("load", loadHandler);
  8955. img.removeEventListener("error", errorHandler);
  8956. Tools.Error("Error while trying to load image: " + input);
  8957. if (onError) {
  8958. onError("Error while trying to load image: " + input, err);
  8959. }
  8960. };
  8961. img.addEventListener("load", loadHandler);
  8962. img.addEventListener("error", errorHandler);
  8963. var noIndexedDB = function () {
  8964. img.src = url;
  8965. };
  8966. var loadFromIndexedDB = function () {
  8967. if (database) {
  8968. database.loadImageFromDB(url, img);
  8969. }
  8970. };
  8971. //ANY database to do!
  8972. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8973. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8974. }
  8975. else {
  8976. if (url.indexOf("file:") !== -1) {
  8977. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8978. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8979. try {
  8980. var blobURL;
  8981. try {
  8982. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8983. }
  8984. catch (ex) {
  8985. // Chrome doesn't support oneTimeOnly parameter
  8986. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8987. }
  8988. img.src = blobURL;
  8989. usingObjectURL = true;
  8990. }
  8991. catch (e) {
  8992. img.src = "";
  8993. }
  8994. return img;
  8995. }
  8996. }
  8997. noIndexedDB();
  8998. }
  8999. return img;
  9000. };
  9001. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9002. url = Tools.CleanUrl(url);
  9003. url = Tools.PreprocessUrl(url);
  9004. // If file and file input are set
  9005. if (url.indexOf("file:") !== -1) {
  9006. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9007. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9008. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9009. }
  9010. }
  9011. var loadUrl = Tools.BaseUrl + url;
  9012. var aborted = false;
  9013. var fileRequest = {
  9014. onCompleteObservable: new BABYLON.Observable(),
  9015. abort: function () { return aborted = true; },
  9016. };
  9017. var requestFile = function () {
  9018. var request = new XMLHttpRequest();
  9019. var retryHandle = null;
  9020. fileRequest.abort = function () {
  9021. aborted = true;
  9022. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9023. request.abort();
  9024. }
  9025. if (retryHandle !== null) {
  9026. clearTimeout(retryHandle);
  9027. retryHandle = null;
  9028. }
  9029. };
  9030. var retryLoop = function (retryIndex) {
  9031. request.open('GET', loadUrl, true);
  9032. if (useArrayBuffer) {
  9033. request.responseType = "arraybuffer";
  9034. }
  9035. if (onProgress) {
  9036. request.addEventListener("progress", onProgress);
  9037. }
  9038. var onLoadEnd = function () {
  9039. request.removeEventListener("loadend", onLoadEnd);
  9040. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9041. fileRequest.onCompleteObservable.clear();
  9042. };
  9043. request.addEventListener("loadend", onLoadEnd);
  9044. var onReadyStateChange = function () {
  9045. if (aborted) {
  9046. return;
  9047. }
  9048. // In case of undefined state in some browsers.
  9049. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9050. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9051. request.removeEventListener("readystatechange", onReadyStateChange);
  9052. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9053. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9054. return;
  9055. }
  9056. var retryStrategy = Tools.DefaultRetryStrategy;
  9057. if (retryStrategy) {
  9058. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9059. if (waitTime !== -1) {
  9060. // Prevent the request from completing for retry.
  9061. request.removeEventListener("loadend", onLoadEnd);
  9062. request = new XMLHttpRequest();
  9063. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9064. return;
  9065. }
  9066. }
  9067. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9068. if (onError) {
  9069. onError(request, e);
  9070. }
  9071. else {
  9072. throw e;
  9073. }
  9074. }
  9075. };
  9076. request.addEventListener("readystatechange", onReadyStateChange);
  9077. request.send();
  9078. };
  9079. retryLoop(0);
  9080. };
  9081. // Caching all files
  9082. if (database && database.enableSceneOffline) {
  9083. var noIndexedDB_1 = function () {
  9084. if (!aborted) {
  9085. requestFile();
  9086. }
  9087. };
  9088. var loadFromIndexedDB = function () {
  9089. // TODO: database needs to support aborting and should return a IFileRequest
  9090. if (aborted) {
  9091. return;
  9092. }
  9093. if (database) {
  9094. database.loadFileFromDB(url, function (data) {
  9095. if (!aborted) {
  9096. onSuccess(data);
  9097. }
  9098. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9099. }, onProgress ? function (event) {
  9100. if (!aborted) {
  9101. onProgress(event);
  9102. }
  9103. } : undefined, noIndexedDB_1, useArrayBuffer);
  9104. }
  9105. };
  9106. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9107. }
  9108. else {
  9109. requestFile();
  9110. }
  9111. return fileRequest;
  9112. };
  9113. /**
  9114. * Load a script (identified by an url). When the url returns, the
  9115. * content of this file is added into a new script element, attached to the DOM (body element)
  9116. */
  9117. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9118. var head = document.getElementsByTagName('head')[0];
  9119. var script = document.createElement('script');
  9120. script.type = 'text/javascript';
  9121. script.src = scriptUrl;
  9122. script.onload = function () {
  9123. if (onSuccess) {
  9124. onSuccess();
  9125. }
  9126. };
  9127. script.onerror = function (e) {
  9128. if (onError) {
  9129. onError("Unable to load script '" + scriptUrl + "'", e);
  9130. }
  9131. };
  9132. head.appendChild(script);
  9133. };
  9134. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9135. var reader = new FileReader();
  9136. var request = {
  9137. onCompleteObservable: new BABYLON.Observable(),
  9138. abort: function () { return reader.abort(); },
  9139. };
  9140. reader.onloadend = function (e) {
  9141. request.onCompleteObservable.notifyObservers(request);
  9142. };
  9143. reader.onload = function (e) {
  9144. //target doesn't have result from ts 1.3
  9145. callback(e.target['result']);
  9146. };
  9147. reader.onprogress = progressCallback;
  9148. reader.readAsDataURL(fileToLoad);
  9149. return request;
  9150. };
  9151. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9152. var reader = new FileReader();
  9153. var request = {
  9154. onCompleteObservable: new BABYLON.Observable(),
  9155. abort: function () { return reader.abort(); },
  9156. };
  9157. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9158. reader.onerror = function (e) {
  9159. Tools.Log("Error while reading file: " + fileToLoad.name);
  9160. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9161. };
  9162. reader.onload = function (e) {
  9163. //target doesn't have result from ts 1.3
  9164. callback(e.target['result']);
  9165. };
  9166. if (progressCallBack) {
  9167. reader.onprogress = progressCallBack;
  9168. }
  9169. if (!useArrayBuffer) {
  9170. // Asynchronous read
  9171. reader.readAsText(fileToLoad);
  9172. }
  9173. else {
  9174. reader.readAsArrayBuffer(fileToLoad);
  9175. }
  9176. return request;
  9177. };
  9178. //returns a downloadable url to a file content.
  9179. Tools.FileAsURL = function (content) {
  9180. var fileBlob = new Blob([content]);
  9181. var url = window.URL || window.webkitURL;
  9182. var link = url.createObjectURL(fileBlob);
  9183. return link;
  9184. };
  9185. // Misc.
  9186. Tools.Format = function (value, decimals) {
  9187. if (decimals === void 0) { decimals = 2; }
  9188. return value.toFixed(decimals);
  9189. };
  9190. Tools.CheckExtends = function (v, min, max) {
  9191. if (v.x < min.x)
  9192. min.x = v.x;
  9193. if (v.y < min.y)
  9194. min.y = v.y;
  9195. if (v.z < min.z)
  9196. min.z = v.z;
  9197. if (v.x > max.x)
  9198. max.x = v.x;
  9199. if (v.y > max.y)
  9200. max.y = v.y;
  9201. if (v.z > max.z)
  9202. max.z = v.z;
  9203. };
  9204. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9205. for (var prop in source) {
  9206. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9207. continue;
  9208. }
  9209. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9210. continue;
  9211. }
  9212. var sourceValue = source[prop];
  9213. var typeOfSourceValue = typeof sourceValue;
  9214. if (typeOfSourceValue === "function") {
  9215. continue;
  9216. }
  9217. try {
  9218. if (typeOfSourceValue === "object") {
  9219. if (sourceValue instanceof Array) {
  9220. destination[prop] = [];
  9221. if (sourceValue.length > 0) {
  9222. if (typeof sourceValue[0] == "object") {
  9223. for (var index = 0; index < sourceValue.length; index++) {
  9224. var clonedValue = cloneValue(sourceValue[index], destination);
  9225. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9226. destination[prop].push(clonedValue);
  9227. }
  9228. }
  9229. }
  9230. else {
  9231. destination[prop] = sourceValue.slice(0);
  9232. }
  9233. }
  9234. }
  9235. else {
  9236. destination[prop] = cloneValue(sourceValue, destination);
  9237. }
  9238. }
  9239. else {
  9240. destination[prop] = sourceValue;
  9241. }
  9242. }
  9243. catch (e) {
  9244. // Just ignore error (it could be because of a read-only property)
  9245. }
  9246. }
  9247. };
  9248. Tools.IsEmpty = function (obj) {
  9249. for (var i in obj) {
  9250. if (obj.hasOwnProperty(i)) {
  9251. return false;
  9252. }
  9253. }
  9254. return true;
  9255. };
  9256. Tools.RegisterTopRootEvents = function (events) {
  9257. for (var index = 0; index < events.length; index++) {
  9258. var event = events[index];
  9259. window.addEventListener(event.name, event.handler, false);
  9260. try {
  9261. if (window.parent) {
  9262. window.parent.addEventListener(event.name, event.handler, false);
  9263. }
  9264. }
  9265. catch (e) {
  9266. // Silently fails...
  9267. }
  9268. }
  9269. };
  9270. Tools.UnregisterTopRootEvents = function (events) {
  9271. for (var index = 0; index < events.length; index++) {
  9272. var event = events[index];
  9273. window.removeEventListener(event.name, event.handler);
  9274. try {
  9275. if (window.parent) {
  9276. window.parent.removeEventListener(event.name, event.handler);
  9277. }
  9278. }
  9279. catch (e) {
  9280. // Silently fails...
  9281. }
  9282. }
  9283. };
  9284. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9285. if (mimeType === void 0) { mimeType = "image/png"; }
  9286. // Read the contents of the framebuffer
  9287. var numberOfChannelsByLine = width * 4;
  9288. var halfHeight = height / 2;
  9289. //Reading datas from WebGL
  9290. var data = engine.readPixels(0, 0, width, height);
  9291. //To flip image on Y axis.
  9292. for (var i = 0; i < halfHeight; i++) {
  9293. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9294. var currentCell = j + i * numberOfChannelsByLine;
  9295. var targetLine = height - i - 1;
  9296. var targetCell = j + targetLine * numberOfChannelsByLine;
  9297. var temp = data[currentCell];
  9298. data[currentCell] = data[targetCell];
  9299. data[targetCell] = temp;
  9300. }
  9301. }
  9302. // Create a 2D canvas to store the result
  9303. if (!screenshotCanvas) {
  9304. screenshotCanvas = document.createElement('canvas');
  9305. }
  9306. screenshotCanvas.width = width;
  9307. screenshotCanvas.height = height;
  9308. var context = screenshotCanvas.getContext('2d');
  9309. if (context) {
  9310. // Copy the pixels to a 2D canvas
  9311. var imageData = context.createImageData(width, height);
  9312. var castData = (imageData.data);
  9313. castData.set(data);
  9314. context.putImageData(imageData, 0, 0);
  9315. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9316. }
  9317. };
  9318. /**
  9319. * Converts the canvas data to blob.
  9320. * This acts as a polyfill for browsers not supporting the to blob function.
  9321. * @param canvas Defines the canvas to extract the data from
  9322. * @param successCallback Defines the callback triggered once the data are available
  9323. * @param mimeType Defines the mime type of the result
  9324. */
  9325. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9326. if (mimeType === void 0) { mimeType = "image/png"; }
  9327. // We need HTMLCanvasElement.toBlob for HD screenshots
  9328. if (!screenshotCanvas.toBlob) {
  9329. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9330. screenshotCanvas.toBlob = function (callback, type, quality) {
  9331. var _this = this;
  9332. setTimeout(function () {
  9333. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9334. for (var i = 0; i < len; i++) {
  9335. arr[i] = binStr.charCodeAt(i);
  9336. }
  9337. callback(new Blob([arr]));
  9338. });
  9339. };
  9340. }
  9341. screenshotCanvas.toBlob(function (blob) {
  9342. successCallback(blob);
  9343. }, mimeType);
  9344. };
  9345. /**
  9346. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9347. * @param successCallback Defines the callback triggered once the data are available
  9348. * @param mimeType Defines the mime type of the result
  9349. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9350. */
  9351. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9352. if (mimeType === void 0) { mimeType = "image/png"; }
  9353. if (successCallback) {
  9354. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9355. successCallback(base64Image);
  9356. }
  9357. else {
  9358. this.ToBlob(screenshotCanvas, function (blob) {
  9359. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9360. if (("download" in document.createElement("a"))) {
  9361. if (!fileName) {
  9362. var date = new Date();
  9363. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9364. fileName = "screenshot_" + stringDate + ".png";
  9365. }
  9366. Tools.Download(blob, fileName);
  9367. }
  9368. else {
  9369. var url = URL.createObjectURL(blob);
  9370. var newWindow = window.open("");
  9371. if (!newWindow)
  9372. return;
  9373. var img = newWindow.document.createElement("img");
  9374. img.onload = function () {
  9375. // no longer need to read the blob so it's revoked
  9376. URL.revokeObjectURL(url);
  9377. };
  9378. img.src = url;
  9379. newWindow.document.body.appendChild(img);
  9380. }
  9381. }, mimeType);
  9382. }
  9383. };
  9384. /**
  9385. * Downloads a blob in the browser
  9386. * @param blob defines the blob to download
  9387. * @param fileName defines the name of the downloaded file
  9388. */
  9389. Tools.Download = function (blob, fileName) {
  9390. var url = window.URL.createObjectURL(blob);
  9391. var a = document.createElement("a");
  9392. document.body.appendChild(a);
  9393. a.style.display = "none";
  9394. a.href = url;
  9395. a.download = fileName;
  9396. a.addEventListener("click", function () {
  9397. if (a.parentElement) {
  9398. a.parentElement.removeChild(a);
  9399. }
  9400. });
  9401. a.click();
  9402. window.URL.revokeObjectURL(url);
  9403. };
  9404. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9405. if (mimeType === void 0) { mimeType = "image/png"; }
  9406. var width;
  9407. var height;
  9408. // If a precision value is specified
  9409. if (size.precision) {
  9410. width = Math.round(engine.getRenderWidth() * size.precision);
  9411. height = Math.round(width / engine.getAspectRatio(camera));
  9412. }
  9413. else if (size.width && size.height) {
  9414. width = size.width;
  9415. height = size.height;
  9416. }
  9417. //If passing only width, computing height to keep display canvas ratio.
  9418. else if (size.width && !size.height) {
  9419. width = size.width;
  9420. height = Math.round(width / engine.getAspectRatio(camera));
  9421. }
  9422. //If passing only height, computing width to keep display canvas ratio.
  9423. else if (size.height && !size.width) {
  9424. height = size.height;
  9425. width = Math.round(height * engine.getAspectRatio(camera));
  9426. }
  9427. //Assuming here that "size" parameter is a number
  9428. else if (!isNaN(size)) {
  9429. height = size;
  9430. width = size;
  9431. }
  9432. else {
  9433. Tools.Error("Invalid 'size' parameter !");
  9434. return;
  9435. }
  9436. if (!screenshotCanvas) {
  9437. screenshotCanvas = document.createElement('canvas');
  9438. }
  9439. screenshotCanvas.width = width;
  9440. screenshotCanvas.height = height;
  9441. var renderContext = screenshotCanvas.getContext("2d");
  9442. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9443. var newWidth = width;
  9444. var newHeight = newWidth / ratio;
  9445. if (newHeight > height) {
  9446. newHeight = height;
  9447. newWidth = newHeight * ratio;
  9448. }
  9449. var offsetX = Math.max(0, width - newWidth) / 2;
  9450. var offsetY = Math.max(0, height - newHeight) / 2;
  9451. var renderingCanvas = engine.getRenderingCanvas();
  9452. if (renderContext && renderingCanvas) {
  9453. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9454. }
  9455. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9456. };
  9457. /**
  9458. * Generates an image screenshot from the specified camera.
  9459. *
  9460. * @param engine The engine to use for rendering
  9461. * @param camera The camera to use for rendering
  9462. * @param size This parameter can be set to a single number or to an object with the
  9463. * following (optional) properties: precision, width, height. If a single number is passed,
  9464. * it will be used for both width and height. If an object is passed, the screenshot size
  9465. * will be derived from the parameters. The precision property is a multiplier allowing
  9466. * rendering at a higher or lower resolution.
  9467. * @param successCallback The callback receives a single parameter which contains the
  9468. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9469. * src parameter of an <img> to display it.
  9470. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9471. * Check your browser for supported MIME types.
  9472. * @param samples Texture samples (default: 1)
  9473. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9474. * @param fileName A name for for the downloaded file.
  9475. * @constructor
  9476. */
  9477. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9478. if (mimeType === void 0) { mimeType = "image/png"; }
  9479. if (samples === void 0) { samples = 1; }
  9480. if (antialiasing === void 0) { antialiasing = false; }
  9481. var width;
  9482. var height;
  9483. //If a precision value is specified
  9484. if (size.precision) {
  9485. width = Math.round(engine.getRenderWidth() * size.precision);
  9486. height = Math.round(width / engine.getAspectRatio(camera));
  9487. size = { width: width, height: height };
  9488. }
  9489. else if (size.width && size.height) {
  9490. width = size.width;
  9491. height = size.height;
  9492. }
  9493. //If passing only width, computing height to keep display canvas ratio.
  9494. else if (size.width && !size.height) {
  9495. width = size.width;
  9496. height = Math.round(width / engine.getAspectRatio(camera));
  9497. size = { width: width, height: height };
  9498. }
  9499. //If passing only height, computing width to keep display canvas ratio.
  9500. else if (size.height && !size.width) {
  9501. height = size.height;
  9502. width = Math.round(height * engine.getAspectRatio(camera));
  9503. size = { width: width, height: height };
  9504. }
  9505. //Assuming here that "size" parameter is a number
  9506. else if (!isNaN(size)) {
  9507. height = size;
  9508. width = size;
  9509. }
  9510. else {
  9511. Tools.Error("Invalid 'size' parameter !");
  9512. return;
  9513. }
  9514. var scene = camera.getScene();
  9515. var previousCamera = null;
  9516. if (scene.activeCamera !== camera) {
  9517. previousCamera = scene.activeCamera;
  9518. scene.activeCamera = camera;
  9519. }
  9520. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9521. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9522. texture.renderList = null;
  9523. texture.samples = samples;
  9524. if (antialiasing) {
  9525. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9526. }
  9527. texture.onAfterRenderObservable.add(function () {
  9528. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9529. });
  9530. scene.incrementRenderId();
  9531. scene.resetCachedMaterial();
  9532. texture.render(true);
  9533. texture.dispose();
  9534. if (previousCamera) {
  9535. scene.activeCamera = previousCamera;
  9536. }
  9537. camera.getProjectionMatrix(true); // Force cache refresh;
  9538. };
  9539. // XHR response validator for local file scenario
  9540. Tools.ValidateXHRData = function (xhr, dataType) {
  9541. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9542. if (dataType === void 0) { dataType = 7; }
  9543. try {
  9544. if (dataType & 1) {
  9545. if (xhr.responseText && xhr.responseText.length > 0) {
  9546. return true;
  9547. }
  9548. else if (dataType === 1) {
  9549. return false;
  9550. }
  9551. }
  9552. if (dataType & 2) {
  9553. // Check header width and height since there is no "TGA" magic number
  9554. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9555. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9556. return true;
  9557. }
  9558. else if (dataType === 2) {
  9559. return false;
  9560. }
  9561. }
  9562. if (dataType & 4) {
  9563. // Check for the "DDS" magic number
  9564. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9565. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9566. return true;
  9567. }
  9568. else {
  9569. return false;
  9570. }
  9571. }
  9572. }
  9573. catch (e) {
  9574. // Global protection
  9575. }
  9576. return false;
  9577. };
  9578. /**
  9579. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9580. * Be aware Math.random() could cause collisions, but:
  9581. * "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"
  9582. */
  9583. Tools.RandomId = function () {
  9584. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9585. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9586. return v.toString(16);
  9587. });
  9588. };
  9589. /**
  9590. * Test if the given uri is a base64 string.
  9591. * @param uri The uri to test
  9592. * @return True if the uri is a base64 string or false otherwise.
  9593. */
  9594. Tools.IsBase64 = function (uri) {
  9595. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9596. };
  9597. /**
  9598. * Decode the given base64 uri.
  9599. * @param uri The uri to decode
  9600. * @return The decoded base64 data.
  9601. */
  9602. Tools.DecodeBase64 = function (uri) {
  9603. var decodedString = atob(uri.split(",")[1]);
  9604. var bufferLength = decodedString.length;
  9605. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9606. for (var i = 0; i < bufferLength; i++) {
  9607. bufferView[i] = decodedString.charCodeAt(i);
  9608. }
  9609. return bufferView.buffer;
  9610. };
  9611. Object.defineProperty(Tools, "NoneLogLevel", {
  9612. get: function () {
  9613. return Tools._NoneLogLevel;
  9614. },
  9615. enumerable: true,
  9616. configurable: true
  9617. });
  9618. Object.defineProperty(Tools, "MessageLogLevel", {
  9619. get: function () {
  9620. return Tools._MessageLogLevel;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(Tools, "WarningLogLevel", {
  9626. get: function () {
  9627. return Tools._WarningLogLevel;
  9628. },
  9629. enumerable: true,
  9630. configurable: true
  9631. });
  9632. Object.defineProperty(Tools, "ErrorLogLevel", {
  9633. get: function () {
  9634. return Tools._ErrorLogLevel;
  9635. },
  9636. enumerable: true,
  9637. configurable: true
  9638. });
  9639. Object.defineProperty(Tools, "AllLogLevel", {
  9640. get: function () {
  9641. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9642. },
  9643. enumerable: true,
  9644. configurable: true
  9645. });
  9646. Tools._AddLogEntry = function (entry) {
  9647. Tools._LogCache = entry + Tools._LogCache;
  9648. if (Tools.OnNewCacheEntry) {
  9649. Tools.OnNewCacheEntry(entry);
  9650. }
  9651. };
  9652. Tools._FormatMessage = function (message) {
  9653. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9654. var date = new Date();
  9655. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9656. };
  9657. Tools._LogDisabled = function (message) {
  9658. // nothing to do
  9659. };
  9660. Tools._LogEnabled = function (message) {
  9661. var formattedMessage = Tools._FormatMessage(message);
  9662. console.log("BJS - " + formattedMessage);
  9663. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9664. Tools._AddLogEntry(entry);
  9665. };
  9666. Tools._WarnDisabled = function (message) {
  9667. // nothing to do
  9668. };
  9669. Tools._WarnEnabled = function (message) {
  9670. var formattedMessage = Tools._FormatMessage(message);
  9671. console.warn("BJS - " + formattedMessage);
  9672. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9673. Tools._AddLogEntry(entry);
  9674. };
  9675. Tools._ErrorDisabled = function (message) {
  9676. // nothing to do
  9677. };
  9678. Tools._ErrorEnabled = function (message) {
  9679. Tools.errorsCount++;
  9680. var formattedMessage = Tools._FormatMessage(message);
  9681. console.error("BJS - " + formattedMessage);
  9682. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9683. Tools._AddLogEntry(entry);
  9684. };
  9685. Object.defineProperty(Tools, "LogCache", {
  9686. get: function () {
  9687. return Tools._LogCache;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. Tools.ClearLogCache = function () {
  9693. Tools._LogCache = "";
  9694. Tools.errorsCount = 0;
  9695. };
  9696. Object.defineProperty(Tools, "LogLevels", {
  9697. set: function (level) {
  9698. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9699. Tools.Log = Tools._LogEnabled;
  9700. }
  9701. else {
  9702. Tools.Log = Tools._LogDisabled;
  9703. }
  9704. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9705. Tools.Warn = Tools._WarnEnabled;
  9706. }
  9707. else {
  9708. Tools.Warn = Tools._WarnDisabled;
  9709. }
  9710. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9711. Tools.Error = Tools._ErrorEnabled;
  9712. }
  9713. else {
  9714. Tools.Error = Tools._ErrorDisabled;
  9715. }
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Tools.IsWindowObjectExist = function () {
  9721. return (typeof window) !== "undefined";
  9722. };
  9723. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9724. get: function () {
  9725. return Tools._PerformanceNoneLogLevel;
  9726. },
  9727. enumerable: true,
  9728. configurable: true
  9729. });
  9730. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9731. get: function () {
  9732. return Tools._PerformanceUserMarkLogLevel;
  9733. },
  9734. enumerable: true,
  9735. configurable: true
  9736. });
  9737. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9738. get: function () {
  9739. return Tools._PerformanceConsoleLogLevel;
  9740. },
  9741. enumerable: true,
  9742. configurable: true
  9743. });
  9744. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9745. set: function (level) {
  9746. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9747. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9748. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9749. return;
  9750. }
  9751. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9752. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9753. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9754. return;
  9755. }
  9756. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9757. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9758. },
  9759. enumerable: true,
  9760. configurable: true
  9761. });
  9762. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9763. };
  9764. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9765. };
  9766. Tools._StartUserMark = function (counterName, condition) {
  9767. if (condition === void 0) { condition = true; }
  9768. if (!Tools._performance) {
  9769. if (!Tools.IsWindowObjectExist()) {
  9770. return;
  9771. }
  9772. Tools._performance = window.performance;
  9773. }
  9774. if (!condition || !Tools._performance.mark) {
  9775. return;
  9776. }
  9777. Tools._performance.mark(counterName + "-Begin");
  9778. };
  9779. Tools._EndUserMark = function (counterName, condition) {
  9780. if (condition === void 0) { condition = true; }
  9781. if (!condition || !Tools._performance.mark) {
  9782. return;
  9783. }
  9784. Tools._performance.mark(counterName + "-End");
  9785. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9786. };
  9787. Tools._StartPerformanceConsole = function (counterName, condition) {
  9788. if (condition === void 0) { condition = true; }
  9789. if (!condition) {
  9790. return;
  9791. }
  9792. Tools._StartUserMark(counterName, condition);
  9793. if (console.time) {
  9794. console.time(counterName);
  9795. }
  9796. };
  9797. Tools._EndPerformanceConsole = function (counterName, condition) {
  9798. if (condition === void 0) { condition = true; }
  9799. if (!condition) {
  9800. return;
  9801. }
  9802. Tools._EndUserMark(counterName, condition);
  9803. if (console.time) {
  9804. console.timeEnd(counterName);
  9805. }
  9806. };
  9807. Object.defineProperty(Tools, "Now", {
  9808. get: function () {
  9809. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9810. return window.performance.now();
  9811. }
  9812. return Date.now();
  9813. },
  9814. enumerable: true,
  9815. configurable: true
  9816. });
  9817. /**
  9818. * This method will return the name of the class used to create the instance of the given object.
  9819. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9820. * @param object the object to get the class name from
  9821. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9822. */
  9823. Tools.GetClassName = function (object, isType) {
  9824. if (isType === void 0) { isType = false; }
  9825. var name = null;
  9826. if (!isType && object.getClassName) {
  9827. name = object.getClassName();
  9828. }
  9829. else {
  9830. if (object instanceof Object) {
  9831. var classObj = isType ? object : Object.getPrototypeOf(object);
  9832. name = classObj.constructor["__bjsclassName__"];
  9833. }
  9834. if (!name) {
  9835. name = typeof object;
  9836. }
  9837. }
  9838. return name;
  9839. };
  9840. Tools.First = function (array, predicate) {
  9841. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9842. var el = array_1[_i];
  9843. if (predicate(el)) {
  9844. return el;
  9845. }
  9846. }
  9847. return null;
  9848. };
  9849. /**
  9850. * This method will return the name of the full name of the class, including its owning module (if any).
  9851. * 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).
  9852. * @param object the object to get the class name from
  9853. * @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.
  9854. */
  9855. Tools.getFullClassName = function (object, isType) {
  9856. if (isType === void 0) { isType = false; }
  9857. var className = null;
  9858. var moduleName = null;
  9859. if (!isType && object.getClassName) {
  9860. className = object.getClassName();
  9861. }
  9862. else {
  9863. if (object instanceof Object) {
  9864. var classObj = isType ? object : Object.getPrototypeOf(object);
  9865. className = classObj.constructor["__bjsclassName__"];
  9866. moduleName = classObj.constructor["__bjsmoduleName__"];
  9867. }
  9868. if (!className) {
  9869. className = typeof object;
  9870. }
  9871. }
  9872. if (!className) {
  9873. return null;
  9874. }
  9875. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9876. };
  9877. /**
  9878. * 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.
  9879. * @param array
  9880. */
  9881. Tools.arrayOrStringFeeder = function (array) {
  9882. return function (index) {
  9883. if (index >= array.length) {
  9884. return null;
  9885. }
  9886. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9887. if (val && val.getHashCode) {
  9888. val = val.getHashCode();
  9889. }
  9890. if (typeof val === "string") {
  9891. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9892. }
  9893. return val;
  9894. };
  9895. };
  9896. /**
  9897. * Compute the hashCode of a stream of number
  9898. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9899. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9900. * @return the hash code computed
  9901. */
  9902. Tools.hashCodeFromStream = function (feeder) {
  9903. // Based from here: http://stackoverflow.com/a/7616484/802124
  9904. var hash = 0;
  9905. var index = 0;
  9906. var chr = feeder(index++);
  9907. while (chr != null) {
  9908. hash = ((hash << 5) - hash) + chr;
  9909. hash |= 0; // Convert to 32bit integer
  9910. chr = feeder(index++);
  9911. }
  9912. return hash;
  9913. };
  9914. /**
  9915. * Returns a promise that resolves after the given amount of time.
  9916. * @param delay Number of milliseconds to delay
  9917. * @returns Promise that resolves after the given amount of time
  9918. */
  9919. Tools.DelayAsync = function (delay) {
  9920. return new Promise(function (resolve) {
  9921. setTimeout(function () {
  9922. resolve();
  9923. }, delay);
  9924. });
  9925. };
  9926. /**
  9927. * Gets the current gradient from an array of IValueGradient
  9928. * @param ratio defines the current ratio to get
  9929. * @param gradients defines the array of IValueGradient
  9930. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  9931. */
  9932. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  9933. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  9934. var currentGradient = gradients[gradientIndex];
  9935. var nextGradient = gradients[gradientIndex + 1];
  9936. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  9937. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  9938. updateFunc(currentGradient, nextGradient, scale);
  9939. }
  9940. }
  9941. };
  9942. Tools.BaseUrl = "";
  9943. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9944. /**
  9945. * Default behaviour for cors in the application.
  9946. * It can be a string if the expected behavior is identical in the entire app.
  9947. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9948. */
  9949. Tools.CorsBehavior = "anonymous";
  9950. Tools.UseFallbackTexture = true;
  9951. /**
  9952. * Use this object to register external classes like custom textures or material
  9953. * to allow the laoders to instantiate them
  9954. */
  9955. Tools.RegisteredExternalClasses = {};
  9956. // Used in case of a texture loading problem
  9957. 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";
  9958. Tools._tmpFloatArray = new Float32Array(1);
  9959. Tools.PreprocessUrl = function (url) {
  9960. return url;
  9961. };
  9962. // Logs
  9963. Tools._NoneLogLevel = 0;
  9964. Tools._MessageLogLevel = 1;
  9965. Tools._WarningLogLevel = 2;
  9966. Tools._ErrorLogLevel = 4;
  9967. Tools._LogCache = "";
  9968. Tools.errorsCount = 0;
  9969. Tools.Log = Tools._LogEnabled;
  9970. Tools.Warn = Tools._WarnEnabled;
  9971. Tools.Error = Tools._ErrorEnabled;
  9972. // Performances
  9973. Tools._PerformanceNoneLogLevel = 0;
  9974. Tools._PerformanceUserMarkLogLevel = 1;
  9975. Tools._PerformanceConsoleLogLevel = 2;
  9976. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9977. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9978. return Tools;
  9979. }());
  9980. BABYLON.Tools = Tools;
  9981. /**
  9982. * This class is used to track a performance counter which is number based.
  9983. * The user has access to many properties which give statistics of different nature
  9984. *
  9985. * The implementer can track two kinds of Performance Counter: time and count
  9986. * 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.
  9987. * 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.
  9988. */
  9989. var PerfCounter = /** @class */ (function () {
  9990. function PerfCounter() {
  9991. this._startMonitoringTime = 0;
  9992. this._min = 0;
  9993. this._max = 0;
  9994. this._average = 0;
  9995. this._lastSecAverage = 0;
  9996. this._current = 0;
  9997. this._totalValueCount = 0;
  9998. this._totalAccumulated = 0;
  9999. this._lastSecAccumulated = 0;
  10000. this._lastSecTime = 0;
  10001. this._lastSecValueCount = 0;
  10002. }
  10003. Object.defineProperty(PerfCounter.prototype, "min", {
  10004. /**
  10005. * Returns the smallest value ever
  10006. */
  10007. get: function () {
  10008. return this._min;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(PerfCounter.prototype, "max", {
  10014. /**
  10015. * Returns the biggest value ever
  10016. */
  10017. get: function () {
  10018. return this._max;
  10019. },
  10020. enumerable: true,
  10021. configurable: true
  10022. });
  10023. Object.defineProperty(PerfCounter.prototype, "average", {
  10024. /**
  10025. * Returns the average value since the performance counter is running
  10026. */
  10027. get: function () {
  10028. return this._average;
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10034. /**
  10035. * Returns the average value of the last second the counter was monitored
  10036. */
  10037. get: function () {
  10038. return this._lastSecAverage;
  10039. },
  10040. enumerable: true,
  10041. configurable: true
  10042. });
  10043. Object.defineProperty(PerfCounter.prototype, "current", {
  10044. /**
  10045. * Returns the current value
  10046. */
  10047. get: function () {
  10048. return this._current;
  10049. },
  10050. enumerable: true,
  10051. configurable: true
  10052. });
  10053. Object.defineProperty(PerfCounter.prototype, "total", {
  10054. get: function () {
  10055. return this._totalAccumulated;
  10056. },
  10057. enumerable: true,
  10058. configurable: true
  10059. });
  10060. Object.defineProperty(PerfCounter.prototype, "count", {
  10061. get: function () {
  10062. return this._totalValueCount;
  10063. },
  10064. enumerable: true,
  10065. configurable: true
  10066. });
  10067. /**
  10068. * Call this method to start monitoring a new frame.
  10069. * 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.
  10070. */
  10071. PerfCounter.prototype.fetchNewFrame = function () {
  10072. this._totalValueCount++;
  10073. this._current = 0;
  10074. this._lastSecValueCount++;
  10075. };
  10076. /**
  10077. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10078. * @param newCount the count value to add to the monitored count
  10079. * @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.
  10080. */
  10081. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10082. if (!PerfCounter.Enabled) {
  10083. return;
  10084. }
  10085. this._current += newCount;
  10086. if (fetchResult) {
  10087. this._fetchResult();
  10088. }
  10089. };
  10090. /**
  10091. * Start monitoring this performance counter
  10092. */
  10093. PerfCounter.prototype.beginMonitoring = function () {
  10094. if (!PerfCounter.Enabled) {
  10095. return;
  10096. }
  10097. this._startMonitoringTime = Tools.Now;
  10098. };
  10099. /**
  10100. * Compute the time lapsed since the previous beginMonitoring() call.
  10101. * @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
  10102. */
  10103. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10104. if (newFrame === void 0) { newFrame = true; }
  10105. if (!PerfCounter.Enabled) {
  10106. return;
  10107. }
  10108. if (newFrame) {
  10109. this.fetchNewFrame();
  10110. }
  10111. var currentTime = Tools.Now;
  10112. this._current = currentTime - this._startMonitoringTime;
  10113. if (newFrame) {
  10114. this._fetchResult();
  10115. }
  10116. };
  10117. PerfCounter.prototype._fetchResult = function () {
  10118. this._totalAccumulated += this._current;
  10119. this._lastSecAccumulated += this._current;
  10120. // Min/Max update
  10121. this._min = Math.min(this._min, this._current);
  10122. this._max = Math.max(this._max, this._current);
  10123. this._average = this._totalAccumulated / this._totalValueCount;
  10124. // Reset last sec?
  10125. var now = Tools.Now;
  10126. if ((now - this._lastSecTime) > 1000) {
  10127. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10128. this._lastSecTime = now;
  10129. this._lastSecAccumulated = 0;
  10130. this._lastSecValueCount = 0;
  10131. }
  10132. };
  10133. PerfCounter.Enabled = true;
  10134. return PerfCounter;
  10135. }());
  10136. BABYLON.PerfCounter = PerfCounter;
  10137. /**
  10138. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10139. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10140. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10141. * @param name The name of the class, case should be preserved
  10142. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10143. */
  10144. function className(name, module) {
  10145. return function (target) {
  10146. target["__bjsclassName__"] = name;
  10147. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10148. };
  10149. }
  10150. BABYLON.className = className;
  10151. /**
  10152. * An implementation of a loop for asynchronous functions.
  10153. */
  10154. var AsyncLoop = /** @class */ (function () {
  10155. /**
  10156. * Constroctor.
  10157. * @param iterations the number of iterations.
  10158. * @param _fn the function to run each iteration
  10159. * @param _successCallback the callback that will be called upon succesful execution
  10160. * @param offset starting offset.
  10161. */
  10162. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10163. if (offset === void 0) { offset = 0; }
  10164. this.iterations = iterations;
  10165. this._fn = _fn;
  10166. this._successCallback = _successCallback;
  10167. this.index = offset - 1;
  10168. this._done = false;
  10169. }
  10170. /**
  10171. * Execute the next iteration. Must be called after the last iteration was finished.
  10172. */
  10173. AsyncLoop.prototype.executeNext = function () {
  10174. if (!this._done) {
  10175. if (this.index + 1 < this.iterations) {
  10176. ++this.index;
  10177. this._fn(this);
  10178. }
  10179. else {
  10180. this.breakLoop();
  10181. }
  10182. }
  10183. };
  10184. /**
  10185. * Break the loop and run the success callback.
  10186. */
  10187. AsyncLoop.prototype.breakLoop = function () {
  10188. this._done = true;
  10189. this._successCallback();
  10190. };
  10191. /**
  10192. * Helper function
  10193. */
  10194. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10195. if (offset === void 0) { offset = 0; }
  10196. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10197. loop.executeNext();
  10198. return loop;
  10199. };
  10200. /**
  10201. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10202. * @param iterations total number of iterations
  10203. * @param syncedIterations number of synchronous iterations in each async iteration.
  10204. * @param fn the function to call each iteration.
  10205. * @param callback a success call back that will be called when iterating stops.
  10206. * @param breakFunction a break condition (optional)
  10207. * @param timeout timeout settings for the setTimeout function. default - 0.
  10208. * @constructor
  10209. */
  10210. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10211. if (timeout === void 0) { timeout = 0; }
  10212. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10213. if (breakFunction && breakFunction())
  10214. loop.breakLoop();
  10215. else {
  10216. setTimeout(function () {
  10217. for (var i = 0; i < syncedIterations; ++i) {
  10218. var iteration = (loop.index * syncedIterations) + i;
  10219. if (iteration >= iterations)
  10220. break;
  10221. fn(iteration);
  10222. if (breakFunction && breakFunction()) {
  10223. loop.breakLoop();
  10224. break;
  10225. }
  10226. }
  10227. loop.executeNext();
  10228. }, timeout);
  10229. }
  10230. }, callback);
  10231. };
  10232. return AsyncLoop;
  10233. }());
  10234. BABYLON.AsyncLoop = AsyncLoop;
  10235. })(BABYLON || (BABYLON = {}));
  10236. //# sourceMappingURL=babylon.tools.js.map
  10237. var BABYLON;
  10238. (function (BABYLON) {
  10239. var PromiseStates;
  10240. (function (PromiseStates) {
  10241. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10242. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10243. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10244. })(PromiseStates || (PromiseStates = {}));
  10245. var FulFillmentAgregator = /** @class */ (function () {
  10246. function FulFillmentAgregator() {
  10247. this.count = 0;
  10248. this.target = 0;
  10249. this.results = [];
  10250. }
  10251. return FulFillmentAgregator;
  10252. }());
  10253. var InternalPromise = /** @class */ (function () {
  10254. function InternalPromise(resolver) {
  10255. var _this = this;
  10256. this._state = PromiseStates.Pending;
  10257. this._children = new Array();
  10258. this._rejectWasConsumed = false;
  10259. if (!resolver) {
  10260. return;
  10261. }
  10262. try {
  10263. resolver(function (value) {
  10264. _this._resolve(value);
  10265. }, function (reason) {
  10266. _this._reject(reason);
  10267. });
  10268. }
  10269. catch (e) {
  10270. this._reject(e);
  10271. }
  10272. }
  10273. Object.defineProperty(InternalPromise.prototype, "_result", {
  10274. get: function () {
  10275. return this._resultValue;
  10276. },
  10277. set: function (value) {
  10278. this._resultValue = value;
  10279. if (this._parent && this._parent._result === undefined) {
  10280. this._parent._result = value;
  10281. }
  10282. },
  10283. enumerable: true,
  10284. configurable: true
  10285. });
  10286. InternalPromise.prototype.catch = function (onRejected) {
  10287. return this.then(undefined, onRejected);
  10288. };
  10289. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10290. var _this = this;
  10291. var newPromise = new InternalPromise();
  10292. newPromise._onFulfilled = onFulfilled;
  10293. newPromise._onRejected = onRejected;
  10294. // Composition
  10295. this._children.push(newPromise);
  10296. newPromise._parent = this;
  10297. if (this._state !== PromiseStates.Pending) {
  10298. BABYLON.Tools.SetImmediate(function () {
  10299. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10300. var returnedValue = newPromise._resolve(_this._result);
  10301. if (returnedValue !== undefined && returnedValue !== null) {
  10302. if (returnedValue._state !== undefined) {
  10303. var returnedPromise = returnedValue;
  10304. newPromise._children.push(returnedPromise);
  10305. returnedPromise._parent = newPromise;
  10306. newPromise = returnedPromise;
  10307. }
  10308. else {
  10309. newPromise._result = returnedValue;
  10310. }
  10311. }
  10312. }
  10313. else {
  10314. newPromise._reject(_this._reason);
  10315. }
  10316. });
  10317. }
  10318. return newPromise;
  10319. };
  10320. InternalPromise.prototype._moveChildren = function (children) {
  10321. var _this = this;
  10322. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10323. this._children.forEach(function (child) {
  10324. child._parent = _this;
  10325. });
  10326. if (this._state === PromiseStates.Fulfilled) {
  10327. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10328. var child = _b[_i];
  10329. child._resolve(this._result);
  10330. }
  10331. }
  10332. else if (this._state === PromiseStates.Rejected) {
  10333. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10334. var child = _d[_c];
  10335. child._reject(this._reason);
  10336. }
  10337. }
  10338. var _a;
  10339. };
  10340. InternalPromise.prototype._resolve = function (value) {
  10341. try {
  10342. this._state = PromiseStates.Fulfilled;
  10343. var returnedValue = null;
  10344. if (this._onFulfilled) {
  10345. returnedValue = this._onFulfilled(value);
  10346. }
  10347. if (returnedValue !== undefined && returnedValue !== null) {
  10348. if (returnedValue._state !== undefined) {
  10349. // Transmit children
  10350. var returnedPromise = returnedValue;
  10351. returnedPromise._parent = this;
  10352. returnedPromise._moveChildren(this._children);
  10353. value = returnedPromise._result;
  10354. }
  10355. else {
  10356. value = returnedValue;
  10357. }
  10358. }
  10359. this._result = value;
  10360. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10361. var child = _a[_i];
  10362. child._resolve(value);
  10363. }
  10364. this._children.length = 0;
  10365. delete this._onFulfilled;
  10366. delete this._onRejected;
  10367. }
  10368. catch (e) {
  10369. this._reject(e, true);
  10370. }
  10371. };
  10372. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10373. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10374. this._state = PromiseStates.Rejected;
  10375. this._reason = reason;
  10376. if (this._onRejected && !onLocalThrow) {
  10377. try {
  10378. this._onRejected(reason);
  10379. this._rejectWasConsumed = true;
  10380. }
  10381. catch (e) {
  10382. reason = e;
  10383. }
  10384. }
  10385. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10386. var child = _a[_i];
  10387. if (this._rejectWasConsumed) {
  10388. child._resolve(null);
  10389. }
  10390. else {
  10391. child._reject(reason);
  10392. }
  10393. }
  10394. this._children.length = 0;
  10395. delete this._onFulfilled;
  10396. delete this._onRejected;
  10397. };
  10398. InternalPromise.resolve = function (value) {
  10399. var newPromise = new InternalPromise();
  10400. newPromise._resolve(value);
  10401. return newPromise;
  10402. };
  10403. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10404. promise.then(function (value) {
  10405. agregator.results[index] = value;
  10406. agregator.count++;
  10407. if (agregator.count === agregator.target) {
  10408. agregator.rootPromise._resolve(agregator.results);
  10409. }
  10410. return null;
  10411. }, function (reason) {
  10412. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10413. agregator.rootPromise._reject(reason);
  10414. }
  10415. });
  10416. };
  10417. InternalPromise.all = function (promises) {
  10418. var newPromise = new InternalPromise();
  10419. var agregator = new FulFillmentAgregator();
  10420. agregator.target = promises.length;
  10421. agregator.rootPromise = newPromise;
  10422. if (promises.length) {
  10423. for (var index = 0; index < promises.length; index++) {
  10424. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10425. }
  10426. }
  10427. else {
  10428. newPromise._resolve([]);
  10429. }
  10430. return newPromise;
  10431. };
  10432. InternalPromise.race = function (promises) {
  10433. var newPromise = new InternalPromise();
  10434. if (promises.length) {
  10435. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10436. var promise = promises_1[_i];
  10437. promise.then(function (value) {
  10438. if (newPromise) {
  10439. newPromise._resolve(value);
  10440. newPromise = null;
  10441. }
  10442. return null;
  10443. }, function (reason) {
  10444. if (newPromise) {
  10445. newPromise._reject(reason);
  10446. newPromise = null;
  10447. }
  10448. });
  10449. }
  10450. }
  10451. return newPromise;
  10452. };
  10453. return InternalPromise;
  10454. }());
  10455. /**
  10456. * Helper class that provides a small promise polyfill
  10457. */
  10458. var PromisePolyfill = /** @class */ (function () {
  10459. function PromisePolyfill() {
  10460. }
  10461. /**
  10462. * Static function used to check if the polyfill is required
  10463. * If this is the case then the function will inject the polyfill to window.Promise
  10464. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10465. */
  10466. PromisePolyfill.Apply = function (force) {
  10467. if (force === void 0) { force = false; }
  10468. if (force || typeof Promise === 'undefined') {
  10469. var root = window;
  10470. root.Promise = InternalPromise;
  10471. }
  10472. };
  10473. return PromisePolyfill;
  10474. }());
  10475. BABYLON.PromisePolyfill = PromisePolyfill;
  10476. })(BABYLON || (BABYLON = {}));
  10477. //# sourceMappingURL=babylon.promise.js.map
  10478. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10479. var BABYLON;
  10480. (function (BABYLON) {
  10481. /**
  10482. * Helper class to push actions to a pool of workers.
  10483. */
  10484. var WorkerPool = /** @class */ (function () {
  10485. /**
  10486. * Constructor
  10487. * @param workers Array of workers to use for actions
  10488. */
  10489. function WorkerPool(workers) {
  10490. this._pendingActions = new Array();
  10491. this._workerInfos = workers.map(function (worker) { return ({
  10492. worker: worker,
  10493. active: false
  10494. }); });
  10495. }
  10496. /**
  10497. * Terminates all workers and clears any pending actions.
  10498. */
  10499. WorkerPool.prototype.dispose = function () {
  10500. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10501. var workerInfo = _a[_i];
  10502. workerInfo.worker.terminate();
  10503. }
  10504. delete this._workerInfos;
  10505. delete this._pendingActions;
  10506. };
  10507. /**
  10508. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10509. * pended until a worker has completed its action.
  10510. * @param action The action to perform. Call onComplete when the action is complete.
  10511. */
  10512. WorkerPool.prototype.push = function (action) {
  10513. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10514. var workerInfo = _a[_i];
  10515. if (!workerInfo.active) {
  10516. this._execute(workerInfo, action);
  10517. return;
  10518. }
  10519. }
  10520. this._pendingActions.push(action);
  10521. };
  10522. WorkerPool.prototype._execute = function (workerInfo, action) {
  10523. var _this = this;
  10524. workerInfo.active = true;
  10525. action(workerInfo.worker, function () {
  10526. workerInfo.active = false;
  10527. var nextAction = _this._pendingActions.shift();
  10528. if (nextAction) {
  10529. _this._execute(workerInfo, nextAction);
  10530. }
  10531. });
  10532. };
  10533. return WorkerPool;
  10534. }());
  10535. BABYLON.WorkerPool = WorkerPool;
  10536. })(BABYLON || (BABYLON = {}));
  10537. //# sourceMappingURL=babylon.workerPool.js.map
  10538. var BABYLON;
  10539. (function (BABYLON) {
  10540. /**
  10541. * @hidden
  10542. **/
  10543. var _AlphaState = /** @class */ (function () {
  10544. /**
  10545. * Initializes the state.
  10546. */
  10547. function _AlphaState() {
  10548. this._isAlphaBlendDirty = false;
  10549. this._isBlendFunctionParametersDirty = false;
  10550. this._isBlendEquationParametersDirty = false;
  10551. this._isBlendConstantsDirty = false;
  10552. this._alphaBlend = false;
  10553. this._blendFunctionParameters = new Array(4);
  10554. this._blendEquationParameters = new Array(2);
  10555. this._blendConstants = new Array(4);
  10556. this.reset();
  10557. }
  10558. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10559. get: function () {
  10560. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10561. },
  10562. enumerable: true,
  10563. configurable: true
  10564. });
  10565. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10566. get: function () {
  10567. return this._alphaBlend;
  10568. },
  10569. set: function (value) {
  10570. if (this._alphaBlend === value) {
  10571. return;
  10572. }
  10573. this._alphaBlend = value;
  10574. this._isAlphaBlendDirty = true;
  10575. },
  10576. enumerable: true,
  10577. configurable: true
  10578. });
  10579. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10580. if (this._blendConstants[0] === r &&
  10581. this._blendConstants[1] === g &&
  10582. this._blendConstants[2] === b &&
  10583. this._blendConstants[3] === a) {
  10584. return;
  10585. }
  10586. this._blendConstants[0] = r;
  10587. this._blendConstants[1] = g;
  10588. this._blendConstants[2] = b;
  10589. this._blendConstants[3] = a;
  10590. this._isBlendConstantsDirty = true;
  10591. };
  10592. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10593. if (this._blendFunctionParameters[0] === value0 &&
  10594. this._blendFunctionParameters[1] === value1 &&
  10595. this._blendFunctionParameters[2] === value2 &&
  10596. this._blendFunctionParameters[3] === value3) {
  10597. return;
  10598. }
  10599. this._blendFunctionParameters[0] = value0;
  10600. this._blendFunctionParameters[1] = value1;
  10601. this._blendFunctionParameters[2] = value2;
  10602. this._blendFunctionParameters[3] = value3;
  10603. this._isBlendFunctionParametersDirty = true;
  10604. };
  10605. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10606. if (this._blendEquationParameters[0] === rgb &&
  10607. this._blendEquationParameters[1] === alpha) {
  10608. return;
  10609. }
  10610. this._blendEquationParameters[0] = rgb;
  10611. this._blendEquationParameters[1] = alpha;
  10612. this._isBlendEquationParametersDirty = true;
  10613. };
  10614. _AlphaState.prototype.reset = function () {
  10615. this._alphaBlend = false;
  10616. this._blendFunctionParameters[0] = null;
  10617. this._blendFunctionParameters[1] = null;
  10618. this._blendFunctionParameters[2] = null;
  10619. this._blendFunctionParameters[3] = null;
  10620. this._blendEquationParameters[0] = null;
  10621. this._blendEquationParameters[1] = null;
  10622. this._blendConstants[0] = null;
  10623. this._blendConstants[1] = null;
  10624. this._blendConstants[2] = null;
  10625. this._blendConstants[3] = null;
  10626. this._isAlphaBlendDirty = true;
  10627. this._isBlendFunctionParametersDirty = false;
  10628. this._isBlendEquationParametersDirty = false;
  10629. this._isBlendConstantsDirty = false;
  10630. };
  10631. _AlphaState.prototype.apply = function (gl) {
  10632. if (!this.isDirty) {
  10633. return;
  10634. }
  10635. // Alpha blend
  10636. if (this._isAlphaBlendDirty) {
  10637. if (this._alphaBlend) {
  10638. gl.enable(gl.BLEND);
  10639. }
  10640. else {
  10641. gl.disable(gl.BLEND);
  10642. }
  10643. this._isAlphaBlendDirty = false;
  10644. }
  10645. // Alpha function
  10646. if (this._isBlendFunctionParametersDirty) {
  10647. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10648. this._isBlendFunctionParametersDirty = false;
  10649. }
  10650. // Alpha equation
  10651. if (this._isBlendEquationParametersDirty) {
  10652. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10653. this._isBlendEquationParametersDirty = false;
  10654. }
  10655. // Constants
  10656. if (this._isBlendConstantsDirty) {
  10657. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10658. this._isBlendConstantsDirty = false;
  10659. }
  10660. };
  10661. return _AlphaState;
  10662. }());
  10663. BABYLON._AlphaState = _AlphaState;
  10664. })(BABYLON || (BABYLON = {}));
  10665. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10666. var BABYLON;
  10667. (function (BABYLON) {
  10668. /**
  10669. * @hidden
  10670. **/
  10671. var _DepthCullingState = /** @class */ (function () {
  10672. /**
  10673. * Initializes the state.
  10674. */
  10675. function _DepthCullingState() {
  10676. this._isDepthTestDirty = false;
  10677. this._isDepthMaskDirty = false;
  10678. this._isDepthFuncDirty = false;
  10679. this._isCullFaceDirty = false;
  10680. this._isCullDirty = false;
  10681. this._isZOffsetDirty = false;
  10682. this._isFrontFaceDirty = false;
  10683. this.reset();
  10684. }
  10685. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10686. get: function () {
  10687. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10688. },
  10689. enumerable: true,
  10690. configurable: true
  10691. });
  10692. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10693. get: function () {
  10694. return this._zOffset;
  10695. },
  10696. set: function (value) {
  10697. if (this._zOffset === value) {
  10698. return;
  10699. }
  10700. this._zOffset = value;
  10701. this._isZOffsetDirty = true;
  10702. },
  10703. enumerable: true,
  10704. configurable: true
  10705. });
  10706. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10707. get: function () {
  10708. return this._cullFace;
  10709. },
  10710. set: function (value) {
  10711. if (this._cullFace === value) {
  10712. return;
  10713. }
  10714. this._cullFace = value;
  10715. this._isCullFaceDirty = true;
  10716. },
  10717. enumerable: true,
  10718. configurable: true
  10719. });
  10720. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10721. get: function () {
  10722. return this._cull;
  10723. },
  10724. set: function (value) {
  10725. if (this._cull === value) {
  10726. return;
  10727. }
  10728. this._cull = value;
  10729. this._isCullDirty = true;
  10730. },
  10731. enumerable: true,
  10732. configurable: true
  10733. });
  10734. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10735. get: function () {
  10736. return this._depthFunc;
  10737. },
  10738. set: function (value) {
  10739. if (this._depthFunc === value) {
  10740. return;
  10741. }
  10742. this._depthFunc = value;
  10743. this._isDepthFuncDirty = true;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10749. get: function () {
  10750. return this._depthMask;
  10751. },
  10752. set: function (value) {
  10753. if (this._depthMask === value) {
  10754. return;
  10755. }
  10756. this._depthMask = value;
  10757. this._isDepthMaskDirty = true;
  10758. },
  10759. enumerable: true,
  10760. configurable: true
  10761. });
  10762. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10763. get: function () {
  10764. return this._depthTest;
  10765. },
  10766. set: function (value) {
  10767. if (this._depthTest === value) {
  10768. return;
  10769. }
  10770. this._depthTest = value;
  10771. this._isDepthTestDirty = true;
  10772. },
  10773. enumerable: true,
  10774. configurable: true
  10775. });
  10776. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10777. get: function () {
  10778. return this._frontFace;
  10779. },
  10780. set: function (value) {
  10781. if (this._frontFace === value) {
  10782. return;
  10783. }
  10784. this._frontFace = value;
  10785. this._isFrontFaceDirty = true;
  10786. },
  10787. enumerable: true,
  10788. configurable: true
  10789. });
  10790. _DepthCullingState.prototype.reset = function () {
  10791. this._depthMask = true;
  10792. this._depthTest = true;
  10793. this._depthFunc = null;
  10794. this._cullFace = null;
  10795. this._cull = null;
  10796. this._zOffset = 0;
  10797. this._frontFace = null;
  10798. this._isDepthTestDirty = true;
  10799. this._isDepthMaskDirty = true;
  10800. this._isDepthFuncDirty = false;
  10801. this._isCullFaceDirty = false;
  10802. this._isCullDirty = false;
  10803. this._isZOffsetDirty = false;
  10804. this._isFrontFaceDirty = false;
  10805. };
  10806. _DepthCullingState.prototype.apply = function (gl) {
  10807. if (!this.isDirty) {
  10808. return;
  10809. }
  10810. // Cull
  10811. if (this._isCullDirty) {
  10812. if (this.cull) {
  10813. gl.enable(gl.CULL_FACE);
  10814. }
  10815. else {
  10816. gl.disable(gl.CULL_FACE);
  10817. }
  10818. this._isCullDirty = false;
  10819. }
  10820. // Cull face
  10821. if (this._isCullFaceDirty) {
  10822. gl.cullFace(this.cullFace);
  10823. this._isCullFaceDirty = false;
  10824. }
  10825. // Depth mask
  10826. if (this._isDepthMaskDirty) {
  10827. gl.depthMask(this.depthMask);
  10828. this._isDepthMaskDirty = false;
  10829. }
  10830. // Depth test
  10831. if (this._isDepthTestDirty) {
  10832. if (this.depthTest) {
  10833. gl.enable(gl.DEPTH_TEST);
  10834. }
  10835. else {
  10836. gl.disable(gl.DEPTH_TEST);
  10837. }
  10838. this._isDepthTestDirty = false;
  10839. }
  10840. // Depth func
  10841. if (this._isDepthFuncDirty) {
  10842. gl.depthFunc(this.depthFunc);
  10843. this._isDepthFuncDirty = false;
  10844. }
  10845. // zOffset
  10846. if (this._isZOffsetDirty) {
  10847. if (this.zOffset) {
  10848. gl.enable(gl.POLYGON_OFFSET_FILL);
  10849. gl.polygonOffset(this.zOffset, 0);
  10850. }
  10851. else {
  10852. gl.disable(gl.POLYGON_OFFSET_FILL);
  10853. }
  10854. this._isZOffsetDirty = false;
  10855. }
  10856. // Front face
  10857. if (this._isFrontFaceDirty) {
  10858. gl.frontFace(this.frontFace);
  10859. this._isFrontFaceDirty = false;
  10860. }
  10861. };
  10862. return _DepthCullingState;
  10863. }());
  10864. BABYLON._DepthCullingState = _DepthCullingState;
  10865. })(BABYLON || (BABYLON = {}));
  10866. //# sourceMappingURL=babylon.depthCullingState.js.map
  10867. var BABYLON;
  10868. (function (BABYLON) {
  10869. /**
  10870. * @hidden
  10871. **/
  10872. var _StencilState = /** @class */ (function () {
  10873. function _StencilState() {
  10874. this._isStencilTestDirty = false;
  10875. this._isStencilMaskDirty = false;
  10876. this._isStencilFuncDirty = false;
  10877. this._isStencilOpDirty = false;
  10878. this.reset();
  10879. }
  10880. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10881. get: function () {
  10882. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10883. },
  10884. enumerable: true,
  10885. configurable: true
  10886. });
  10887. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10888. get: function () {
  10889. return this._stencilFunc;
  10890. },
  10891. set: function (value) {
  10892. if (this._stencilFunc === value) {
  10893. return;
  10894. }
  10895. this._stencilFunc = value;
  10896. this._isStencilFuncDirty = true;
  10897. },
  10898. enumerable: true,
  10899. configurable: true
  10900. });
  10901. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10902. get: function () {
  10903. return this._stencilFuncRef;
  10904. },
  10905. set: function (value) {
  10906. if (this._stencilFuncRef === value) {
  10907. return;
  10908. }
  10909. this._stencilFuncRef = value;
  10910. this._isStencilFuncDirty = true;
  10911. },
  10912. enumerable: true,
  10913. configurable: true
  10914. });
  10915. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10916. get: function () {
  10917. return this._stencilFuncMask;
  10918. },
  10919. set: function (value) {
  10920. if (this._stencilFuncMask === value) {
  10921. return;
  10922. }
  10923. this._stencilFuncMask = value;
  10924. this._isStencilFuncDirty = true;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10930. get: function () {
  10931. return this._stencilOpStencilFail;
  10932. },
  10933. set: function (value) {
  10934. if (this._stencilOpStencilFail === value) {
  10935. return;
  10936. }
  10937. this._stencilOpStencilFail = value;
  10938. this._isStencilOpDirty = true;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10944. get: function () {
  10945. return this._stencilOpDepthFail;
  10946. },
  10947. set: function (value) {
  10948. if (this._stencilOpDepthFail === value) {
  10949. return;
  10950. }
  10951. this._stencilOpDepthFail = value;
  10952. this._isStencilOpDirty = true;
  10953. },
  10954. enumerable: true,
  10955. configurable: true
  10956. });
  10957. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10958. get: function () {
  10959. return this._stencilOpStencilDepthPass;
  10960. },
  10961. set: function (value) {
  10962. if (this._stencilOpStencilDepthPass === value) {
  10963. return;
  10964. }
  10965. this._stencilOpStencilDepthPass = value;
  10966. this._isStencilOpDirty = true;
  10967. },
  10968. enumerable: true,
  10969. configurable: true
  10970. });
  10971. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10972. get: function () {
  10973. return this._stencilMask;
  10974. },
  10975. set: function (value) {
  10976. if (this._stencilMask === value) {
  10977. return;
  10978. }
  10979. this._stencilMask = value;
  10980. this._isStencilMaskDirty = true;
  10981. },
  10982. enumerable: true,
  10983. configurable: true
  10984. });
  10985. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10986. get: function () {
  10987. return this._stencilTest;
  10988. },
  10989. set: function (value) {
  10990. if (this._stencilTest === value) {
  10991. return;
  10992. }
  10993. this._stencilTest = value;
  10994. this._isStencilTestDirty = true;
  10995. },
  10996. enumerable: true,
  10997. configurable: true
  10998. });
  10999. _StencilState.prototype.reset = function () {
  11000. this._stencilTest = false;
  11001. this._stencilMask = 0xFF;
  11002. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11003. this._stencilFuncRef = 1;
  11004. this._stencilFuncMask = 0xFF;
  11005. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11006. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11007. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11008. this._isStencilTestDirty = true;
  11009. this._isStencilMaskDirty = true;
  11010. this._isStencilFuncDirty = true;
  11011. this._isStencilOpDirty = true;
  11012. };
  11013. _StencilState.prototype.apply = function (gl) {
  11014. if (!this.isDirty) {
  11015. return;
  11016. }
  11017. // Stencil test
  11018. if (this._isStencilTestDirty) {
  11019. if (this.stencilTest) {
  11020. gl.enable(gl.STENCIL_TEST);
  11021. }
  11022. else {
  11023. gl.disable(gl.STENCIL_TEST);
  11024. }
  11025. this._isStencilTestDirty = false;
  11026. }
  11027. // Stencil mask
  11028. if (this._isStencilMaskDirty) {
  11029. gl.stencilMask(this.stencilMask);
  11030. this._isStencilMaskDirty = false;
  11031. }
  11032. // Stencil func
  11033. if (this._isStencilFuncDirty) {
  11034. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11035. this._isStencilFuncDirty = false;
  11036. }
  11037. // Stencil op
  11038. if (this._isStencilOpDirty) {
  11039. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11040. this._isStencilOpDirty = false;
  11041. }
  11042. };
  11043. return _StencilState;
  11044. }());
  11045. BABYLON._StencilState = _StencilState;
  11046. })(BABYLON || (BABYLON = {}));
  11047. //# sourceMappingURL=babylon.stencilState.js.map
  11048. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11049. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11050. s = arguments[i];
  11051. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11052. t[p] = s[p];
  11053. }
  11054. return t;
  11055. };
  11056. var BABYLON;
  11057. (function (BABYLON) {
  11058. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11059. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11060. };
  11061. var compileRawShader = function (gl, source, type) {
  11062. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11063. gl.shaderSource(shader, source);
  11064. gl.compileShader(shader);
  11065. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11066. var log = gl.getShaderInfoLog(shader);
  11067. if (log) {
  11068. throw new Error(log);
  11069. }
  11070. }
  11071. if (!shader) {
  11072. throw new Error("Something went wrong while compile the shader.");
  11073. }
  11074. return shader;
  11075. };
  11076. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11077. var magFilter = gl.NEAREST;
  11078. var minFilter = gl.NEAREST;
  11079. switch (samplingMode) {
  11080. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11081. magFilter = gl.LINEAR;
  11082. if (generateMipMaps) {
  11083. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11084. }
  11085. else {
  11086. minFilter = gl.LINEAR;
  11087. }
  11088. break;
  11089. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11090. magFilter = gl.LINEAR;
  11091. if (generateMipMaps) {
  11092. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11093. }
  11094. else {
  11095. minFilter = gl.LINEAR;
  11096. }
  11097. break;
  11098. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11099. magFilter = gl.NEAREST;
  11100. if (generateMipMaps) {
  11101. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11102. }
  11103. else {
  11104. minFilter = gl.NEAREST;
  11105. }
  11106. break;
  11107. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11108. magFilter = gl.NEAREST;
  11109. if (generateMipMaps) {
  11110. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11111. }
  11112. else {
  11113. minFilter = gl.NEAREST;
  11114. }
  11115. break;
  11116. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11117. magFilter = gl.NEAREST;
  11118. if (generateMipMaps) {
  11119. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11120. }
  11121. else {
  11122. minFilter = gl.LINEAR;
  11123. }
  11124. break;
  11125. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11126. magFilter = gl.NEAREST;
  11127. if (generateMipMaps) {
  11128. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11129. }
  11130. else {
  11131. minFilter = gl.LINEAR;
  11132. }
  11133. break;
  11134. case BABYLON.Texture.NEAREST_LINEAR:
  11135. magFilter = gl.NEAREST;
  11136. minFilter = gl.LINEAR;
  11137. break;
  11138. case BABYLON.Texture.NEAREST_NEAREST:
  11139. magFilter = gl.NEAREST;
  11140. minFilter = gl.NEAREST;
  11141. break;
  11142. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11143. magFilter = gl.LINEAR;
  11144. if (generateMipMaps) {
  11145. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11146. }
  11147. else {
  11148. minFilter = gl.NEAREST;
  11149. }
  11150. break;
  11151. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11152. magFilter = gl.LINEAR;
  11153. if (generateMipMaps) {
  11154. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11155. }
  11156. else {
  11157. minFilter = gl.NEAREST;
  11158. }
  11159. break;
  11160. case BABYLON.Texture.LINEAR_LINEAR:
  11161. magFilter = gl.LINEAR;
  11162. minFilter = gl.LINEAR;
  11163. break;
  11164. case BABYLON.Texture.LINEAR_NEAREST:
  11165. magFilter = gl.LINEAR;
  11166. minFilter = gl.NEAREST;
  11167. break;
  11168. }
  11169. return {
  11170. min: minFilter,
  11171. mag: magFilter
  11172. };
  11173. };
  11174. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11175. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11176. var img;
  11177. var onload = function () {
  11178. loadedImages[index] = img;
  11179. loadedImages._internalCount++;
  11180. if (scene) {
  11181. scene._removePendingData(img);
  11182. }
  11183. if (loadedImages._internalCount === 6) {
  11184. onfinish(loadedImages);
  11185. }
  11186. };
  11187. var onerror = function (message, exception) {
  11188. if (scene) {
  11189. scene._removePendingData(img);
  11190. }
  11191. if (onErrorCallBack) {
  11192. onErrorCallBack(message, exception);
  11193. }
  11194. };
  11195. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11196. if (scene) {
  11197. scene._addPendingData(img);
  11198. }
  11199. };
  11200. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11201. if (onError === void 0) { onError = null; }
  11202. var loadedImages = [];
  11203. loadedImages._internalCount = 0;
  11204. for (var index = 0; index < 6; index++) {
  11205. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11206. }
  11207. };
  11208. var BufferPointer = /** @class */ (function () {
  11209. function BufferPointer() {
  11210. }
  11211. return BufferPointer;
  11212. }());
  11213. /**
  11214. * Interface for attribute information associated with buffer instanciation
  11215. */
  11216. var InstancingAttributeInfo = /** @class */ (function () {
  11217. function InstancingAttributeInfo() {
  11218. }
  11219. return InstancingAttributeInfo;
  11220. }());
  11221. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11222. /**
  11223. * Define options used to create a render target texture
  11224. */
  11225. var RenderTargetCreationOptions = /** @class */ (function () {
  11226. function RenderTargetCreationOptions() {
  11227. }
  11228. return RenderTargetCreationOptions;
  11229. }());
  11230. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11231. /**
  11232. * Define options used to create a depth texture
  11233. */
  11234. var DepthTextureCreationOptions = /** @class */ (function () {
  11235. function DepthTextureCreationOptions() {
  11236. }
  11237. return DepthTextureCreationOptions;
  11238. }());
  11239. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11240. /**
  11241. * Class used to describe the capabilities of the engine relatively to the current browser
  11242. */
  11243. var EngineCapabilities = /** @class */ (function () {
  11244. function EngineCapabilities() {
  11245. }
  11246. return EngineCapabilities;
  11247. }());
  11248. BABYLON.EngineCapabilities = EngineCapabilities;
  11249. /**
  11250. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11251. */
  11252. var Engine = /** @class */ (function () {
  11253. /**
  11254. * Creates a new engine
  11255. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11256. * @param antialias defines enable antialiasing (default: false)
  11257. * @param options defines further options to be sent to the getContext() function
  11258. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11259. */
  11260. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11261. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11262. var _this = this;
  11263. // Public members
  11264. /**
  11265. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11266. */
  11267. this.forcePOTTextures = false;
  11268. /**
  11269. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11270. */
  11271. this.isFullscreen = false;
  11272. /**
  11273. * Gets a boolean indicating if the pointer is currently locked
  11274. */
  11275. this.isPointerLock = false;
  11276. /**
  11277. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11278. */
  11279. this.cullBackFaces = true;
  11280. /**
  11281. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11282. */
  11283. this.renderEvenInBackground = true;
  11284. /**
  11285. * Gets or sets a boolean indicating that cache can be kept between frames
  11286. */
  11287. this.preventCacheWipeBetweenFrames = false;
  11288. /**
  11289. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11290. **/
  11291. this.enableOfflineSupport = false;
  11292. /**
  11293. * 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)
  11294. **/
  11295. this.disableManifestCheck = false;
  11296. /**
  11297. * Gets the list of created scenes
  11298. */
  11299. this.scenes = new Array();
  11300. /**
  11301. * Gets the list of created postprocesses
  11302. */
  11303. this.postProcesses = new Array();
  11304. // Observables
  11305. /**
  11306. * Observable event triggered each time the rendering canvas is resized
  11307. */
  11308. this.onResizeObservable = new BABYLON.Observable();
  11309. /**
  11310. * Observable event triggered each time the canvas loses focus
  11311. */
  11312. this.onCanvasBlurObservable = new BABYLON.Observable();
  11313. /**
  11314. * Observable event triggered each time the canvas gains focus
  11315. */
  11316. this.onCanvasFocusObservable = new BABYLON.Observable();
  11317. /**
  11318. * Observable event triggered each time the canvas receives pointerout event
  11319. */
  11320. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11321. /**
  11322. * Observable event triggered before each texture is initialized
  11323. */
  11324. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11325. //WebVR
  11326. this._vrDisplay = undefined;
  11327. this._vrSupported = false;
  11328. this._vrExclusivePointerMode = false;
  11329. // Uniform buffers list
  11330. /**
  11331. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11332. */
  11333. this.disableUniformBuffers = false;
  11334. /** @hidden */
  11335. this._uniformBuffers = new Array();
  11336. // Observables
  11337. /**
  11338. * Observable raised when the engine begins a new frame
  11339. */
  11340. this.onBeginFrameObservable = new BABYLON.Observable();
  11341. /**
  11342. * Observable raised when the engine ends the current frame
  11343. */
  11344. this.onEndFrameObservable = new BABYLON.Observable();
  11345. /**
  11346. * Observable raised when the engine is about to compile a shader
  11347. */
  11348. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11349. /**
  11350. * Observable raised when the engine has jsut compiled a shader
  11351. */
  11352. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11353. this._windowIsBackground = false;
  11354. this._webGLVersion = 1.0;
  11355. /** @hidden */
  11356. this._badOS = false;
  11357. /** @hidden */
  11358. this._badDesktopOS = false;
  11359. /**
  11360. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11361. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11362. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11363. */
  11364. this.disableTextureBindingOptimization = false;
  11365. /**
  11366. * Observable signaled when VR display mode changes
  11367. */
  11368. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11369. /**
  11370. * Observable signaled when VR request present is complete
  11371. */
  11372. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11373. /**
  11374. * Observable signaled when VR request present starts
  11375. */
  11376. this.onVRRequestPresentStart = new BABYLON.Observable();
  11377. this._colorWrite = true;
  11378. /** @hidden */
  11379. this._drawCalls = new BABYLON.PerfCounter();
  11380. /** @hidden */
  11381. this._textureCollisions = new BABYLON.PerfCounter();
  11382. this._renderingQueueLaunched = false;
  11383. this._activeRenderLoops = new Array();
  11384. // Deterministic lockstepMaxSteps
  11385. this._deterministicLockstep = false;
  11386. this._lockstepMaxSteps = 4;
  11387. // Lost context
  11388. /**
  11389. * Observable signaled when a context lost event is raised
  11390. */
  11391. this.onContextLostObservable = new BABYLON.Observable();
  11392. /**
  11393. * Observable signaled when a context restored event is raised
  11394. */
  11395. this.onContextRestoredObservable = new BABYLON.Observable();
  11396. this._contextWasLost = false;
  11397. this._doNotHandleContextLost = false;
  11398. // FPS
  11399. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11400. this._fps = 60;
  11401. this._deltaTime = 0;
  11402. /**
  11403. * Turn this value on if you want to pause FPS computation when in background
  11404. */
  11405. this.disablePerformanceMonitorInBackground = false;
  11406. // States
  11407. /** @hidden */
  11408. this._depthCullingState = new BABYLON._DepthCullingState();
  11409. /** @hidden */
  11410. this._stencilState = new BABYLON._StencilState();
  11411. /** @hidden */
  11412. this._alphaState = new BABYLON._AlphaState();
  11413. /** @hidden */
  11414. this._alphaMode = Engine.ALPHA_DISABLE;
  11415. // Cache
  11416. this._internalTexturesCache = new Array();
  11417. /** @hidden */
  11418. this._activeChannel = 0;
  11419. this._currentTextureChannel = -1;
  11420. /** @hidden */
  11421. this._boundTexturesCache = {};
  11422. this._compiledEffects = {};
  11423. this._vertexAttribArraysEnabled = [];
  11424. this._uintIndicesCurrentlySet = false;
  11425. this._currentBoundBuffer = new Array();
  11426. this._currentBufferPointers = new Array();
  11427. this._currentInstanceLocations = new Array();
  11428. this._currentInstanceBuffers = new Array();
  11429. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11430. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11431. this._vaoRecordInProgress = false;
  11432. this._mustWipeVertexAttributes = false;
  11433. this._nextFreeTextureSlots = new Array();
  11434. this._maxSimultaneousTextures = 0;
  11435. this._activeRequests = new Array();
  11436. // Hardware supported Compressed Textures
  11437. this._texturesSupported = new Array();
  11438. /**
  11439. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11440. */
  11441. this.premultipliedAlpha = true;
  11442. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11443. this._onVRFullScreenTriggered = function () {
  11444. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11445. //get the old size before we change
  11446. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11447. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11448. //get the width and height, change the render size
  11449. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11450. _this.setHardwareScalingLevel(1);
  11451. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11452. }
  11453. else {
  11454. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11455. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11456. }
  11457. };
  11458. this._unpackFlipYCached = null;
  11459. this._boundUniforms = {};
  11460. // Register promises
  11461. BABYLON.PromisePolyfill.Apply();
  11462. var canvas = null;
  11463. Engine.Instances.push(this);
  11464. if (!canvasOrContext) {
  11465. return;
  11466. }
  11467. options = options || {};
  11468. if (canvasOrContext.getContext) {
  11469. canvas = canvasOrContext;
  11470. this._renderingCanvas = canvas;
  11471. if (antialias != null) {
  11472. options.antialias = antialias;
  11473. }
  11474. if (options.deterministicLockstep === undefined) {
  11475. options.deterministicLockstep = false;
  11476. }
  11477. if (options.lockstepMaxSteps === undefined) {
  11478. options.lockstepMaxSteps = 4;
  11479. }
  11480. if (options.preserveDrawingBuffer === undefined) {
  11481. options.preserveDrawingBuffer = false;
  11482. }
  11483. if (options.audioEngine === undefined) {
  11484. options.audioEngine = true;
  11485. }
  11486. if (options.stencil === undefined) {
  11487. options.stencil = true;
  11488. }
  11489. if (options.premultipliedAlpha === false) {
  11490. this.premultipliedAlpha = false;
  11491. }
  11492. this._deterministicLockstep = options.deterministicLockstep;
  11493. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11494. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11495. // Exceptions
  11496. if (navigator && navigator.userAgent) {
  11497. var ua = navigator.userAgent;
  11498. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11499. var exception = _a[_i];
  11500. var key = exception.key;
  11501. var targets = exception.targets;
  11502. if (ua.indexOf(key) > -1) {
  11503. if (exception.capture && exception.captureConstraint) {
  11504. var capture = exception.capture;
  11505. var constraint = exception.captureConstraint;
  11506. var regex = new RegExp(capture);
  11507. var matches = regex.exec(ua);
  11508. if (matches && matches.length > 0) {
  11509. var capturedValue = parseInt(matches[matches.length - 1]);
  11510. if (capturedValue >= constraint) {
  11511. continue;
  11512. }
  11513. }
  11514. }
  11515. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11516. var target = targets_1[_b];
  11517. switch (target) {
  11518. case "uniformBuffer":
  11519. this.disableUniformBuffers = true;
  11520. break;
  11521. case "textureBindingOptimization":
  11522. this.disableTextureBindingOptimization = true;
  11523. break;
  11524. }
  11525. }
  11526. }
  11527. }
  11528. }
  11529. // GL
  11530. if (!options.disableWebGL2Support) {
  11531. try {
  11532. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11533. if (this._gl) {
  11534. this._webGLVersion = 2.0;
  11535. }
  11536. }
  11537. catch (e) {
  11538. // Do nothing
  11539. }
  11540. }
  11541. if (!this._gl) {
  11542. if (!canvas) {
  11543. throw new Error("The provided canvas is null or undefined.");
  11544. }
  11545. try {
  11546. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11547. }
  11548. catch (e) {
  11549. throw new Error("WebGL not supported");
  11550. }
  11551. }
  11552. if (!this._gl) {
  11553. throw new Error("WebGL not supported");
  11554. }
  11555. this._onCanvasFocus = function () {
  11556. _this.onCanvasFocusObservable.notifyObservers(_this);
  11557. };
  11558. this._onCanvasBlur = function () {
  11559. _this.onCanvasBlurObservable.notifyObservers(_this);
  11560. };
  11561. canvas.addEventListener("focus", this._onCanvasFocus);
  11562. canvas.addEventListener("blur", this._onCanvasBlur);
  11563. this._onBlur = function () {
  11564. if (_this.disablePerformanceMonitorInBackground) {
  11565. _this._performanceMonitor.disable();
  11566. }
  11567. _this._windowIsBackground = true;
  11568. };
  11569. this._onFocus = function () {
  11570. if (_this.disablePerformanceMonitorInBackground) {
  11571. _this._performanceMonitor.enable();
  11572. }
  11573. _this._windowIsBackground = false;
  11574. };
  11575. this._onCanvasPointerOut = function (ev) {
  11576. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11577. };
  11578. window.addEventListener("blur", this._onBlur);
  11579. window.addEventListener("focus", this._onFocus);
  11580. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11581. // Context lost
  11582. if (!this._doNotHandleContextLost) {
  11583. this._onContextLost = function (evt) {
  11584. evt.preventDefault();
  11585. _this._contextWasLost = true;
  11586. BABYLON.Tools.Warn("WebGL context lost.");
  11587. _this.onContextLostObservable.notifyObservers(_this);
  11588. };
  11589. this._onContextRestored = function (evt) {
  11590. // Adding a timeout to avoid race condition at browser level
  11591. setTimeout(function () {
  11592. // Rebuild gl context
  11593. _this._initGLContext();
  11594. // Rebuild effects
  11595. _this._rebuildEffects();
  11596. // Rebuild textures
  11597. _this._rebuildInternalTextures();
  11598. // Rebuild buffers
  11599. _this._rebuildBuffers();
  11600. // Cache
  11601. _this.wipeCaches(true);
  11602. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11603. _this.onContextRestoredObservable.notifyObservers(_this);
  11604. _this._contextWasLost = false;
  11605. }, 0);
  11606. };
  11607. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11608. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11609. }
  11610. }
  11611. else {
  11612. this._gl = canvasOrContext;
  11613. this._renderingCanvas = this._gl.canvas;
  11614. if (this._gl.renderbufferStorageMultisample) {
  11615. this._webGLVersion = 2.0;
  11616. }
  11617. options.stencil = this._gl.getContextAttributes().stencil;
  11618. }
  11619. // Viewport
  11620. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11621. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11622. this.resize();
  11623. this._isStencilEnable = options.stencil ? true : false;
  11624. this._initGLContext();
  11625. if (canvas) {
  11626. // Fullscreen
  11627. this._onFullscreenChange = function () {
  11628. if (document.fullscreen !== undefined) {
  11629. _this.isFullscreen = document.fullscreen;
  11630. }
  11631. else if (document.mozFullScreen !== undefined) {
  11632. _this.isFullscreen = document.mozFullScreen;
  11633. }
  11634. else if (document.webkitIsFullScreen !== undefined) {
  11635. _this.isFullscreen = document.webkitIsFullScreen;
  11636. }
  11637. else if (document.msIsFullScreen !== undefined) {
  11638. _this.isFullscreen = document.msIsFullScreen;
  11639. }
  11640. // Pointer lock
  11641. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11642. canvas.requestPointerLock = canvas.requestPointerLock ||
  11643. canvas.msRequestPointerLock ||
  11644. canvas.mozRequestPointerLock ||
  11645. canvas.webkitRequestPointerLock;
  11646. if (canvas.requestPointerLock) {
  11647. canvas.requestPointerLock();
  11648. }
  11649. }
  11650. };
  11651. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11652. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11653. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11654. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11655. // Pointer lock
  11656. this._onPointerLockChange = function () {
  11657. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11658. document.webkitPointerLockElement === canvas ||
  11659. document.msPointerLockElement === canvas ||
  11660. document.pointerLockElement === canvas);
  11661. };
  11662. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11663. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11664. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11665. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11666. this._onVRDisplayPointerRestricted = function () {
  11667. if (canvas) {
  11668. canvas.requestPointerLock();
  11669. }
  11670. };
  11671. this._onVRDisplayPointerUnrestricted = function () {
  11672. document.exitPointerLock();
  11673. };
  11674. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11675. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11676. }
  11677. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11678. Engine.audioEngine = new BABYLON.AudioEngine();
  11679. }
  11680. // Prepare buffer pointers
  11681. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11682. this._currentBufferPointers[i] = new BufferPointer();
  11683. }
  11684. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11685. // Load WebVR Devices
  11686. if (options.autoEnableWebVR) {
  11687. this.initWebVR();
  11688. }
  11689. // Detect if we are running on a faulty buggy OS.
  11690. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11691. // Detect if we are running on a faulty buggy desktop OS.
  11692. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11693. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11694. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11695. }
  11696. Object.defineProperty(Engine, "LastCreatedEngine", {
  11697. /**
  11698. * Gets the latest created engine
  11699. */
  11700. get: function () {
  11701. if (Engine.Instances.length === 0) {
  11702. return null;
  11703. }
  11704. return Engine.Instances[Engine.Instances.length - 1];
  11705. },
  11706. enumerable: true,
  11707. configurable: true
  11708. });
  11709. Object.defineProperty(Engine, "LastCreatedScene", {
  11710. /**
  11711. * Gets the latest created scene
  11712. */
  11713. get: function () {
  11714. var lastCreatedEngine = Engine.LastCreatedEngine;
  11715. if (!lastCreatedEngine) {
  11716. return null;
  11717. }
  11718. if (lastCreatedEngine.scenes.length === 0) {
  11719. return null;
  11720. }
  11721. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11722. },
  11723. enumerable: true,
  11724. configurable: true
  11725. });
  11726. /**
  11727. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11728. * @param flag defines which part of the materials must be marked as dirty
  11729. * @param predicate defines a predicate used to filter which materials should be affected
  11730. */
  11731. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11732. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11733. var engine = Engine.Instances[engineIndex];
  11734. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11735. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11736. }
  11737. }
  11738. };
  11739. Object.defineProperty(Engine, "NEVER", {
  11740. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11741. get: function () {
  11742. return Engine._NEVER;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "ALWAYS", {
  11748. /** 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 */
  11749. get: function () {
  11750. return Engine._ALWAYS;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "LESS", {
  11756. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11757. get: function () {
  11758. return Engine._LESS;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "EQUAL", {
  11764. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11765. get: function () {
  11766. return Engine._EQUAL;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "LEQUAL", {
  11772. /** 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 */
  11773. get: function () {
  11774. return Engine._LEQUAL;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "GREATER", {
  11780. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11781. get: function () {
  11782. return Engine._GREATER;
  11783. },
  11784. enumerable: true,
  11785. configurable: true
  11786. });
  11787. Object.defineProperty(Engine, "GEQUAL", {
  11788. /** 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 */
  11789. get: function () {
  11790. return Engine._GEQUAL;
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. Object.defineProperty(Engine, "NOTEQUAL", {
  11796. /** 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 */
  11797. get: function () {
  11798. return Engine._NOTEQUAL;
  11799. },
  11800. enumerable: true,
  11801. configurable: true
  11802. });
  11803. Object.defineProperty(Engine, "KEEP", {
  11804. /** Passed to stencilOperation to specify that stencil value must be kept */
  11805. get: function () {
  11806. return Engine._KEEP;
  11807. },
  11808. enumerable: true,
  11809. configurable: true
  11810. });
  11811. Object.defineProperty(Engine, "REPLACE", {
  11812. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11813. get: function () {
  11814. return Engine._REPLACE;
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. Object.defineProperty(Engine, "INCR", {
  11820. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11821. get: function () {
  11822. return Engine._INCR;
  11823. },
  11824. enumerable: true,
  11825. configurable: true
  11826. });
  11827. Object.defineProperty(Engine, "DECR", {
  11828. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11829. get: function () {
  11830. return Engine._DECR;
  11831. },
  11832. enumerable: true,
  11833. configurable: true
  11834. });
  11835. Object.defineProperty(Engine, "INVERT", {
  11836. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11837. get: function () {
  11838. return Engine._INVERT;
  11839. },
  11840. enumerable: true,
  11841. configurable: true
  11842. });
  11843. Object.defineProperty(Engine, "INCR_WRAP", {
  11844. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11845. get: function () {
  11846. return Engine._INCR_WRAP;
  11847. },
  11848. enumerable: true,
  11849. configurable: true
  11850. });
  11851. Object.defineProperty(Engine, "DECR_WRAP", {
  11852. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11853. get: function () {
  11854. return Engine._DECR_WRAP;
  11855. },
  11856. enumerable: true,
  11857. configurable: true
  11858. });
  11859. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11860. // Alpha
  11861. /** Defines that alpha blending is disabled */
  11862. get: function () {
  11863. return Engine._ALPHA_DISABLE;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11869. /** Defines that alpha blending to SRC + DEST */
  11870. get: function () {
  11871. return Engine._ALPHA_ONEONE;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "ALPHA_ADD", {
  11877. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11878. get: function () {
  11879. return Engine._ALPHA_ADD;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11885. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11886. get: function () {
  11887. return Engine._ALPHA_COMBINE;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11893. /** Defines that alpha blending to DEST - SRC * DEST */
  11894. get: function () {
  11895. return Engine._ALPHA_SUBTRACT;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11901. /** Defines that alpha blending to SRC * DEST */
  11902. get: function () {
  11903. return Engine._ALPHA_MULTIPLY;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11909. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11910. get: function () {
  11911. return Engine._ALPHA_MAXIMIZED;
  11912. },
  11913. enumerable: true,
  11914. configurable: true
  11915. });
  11916. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11917. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11918. get: function () {
  11919. return Engine._ALPHA_PREMULTIPLIED;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11925. /**
  11926. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11927. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11928. */
  11929. get: function () {
  11930. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11936. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11937. get: function () {
  11938. return Engine._ALPHA_INTERPOLATE;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11944. /**
  11945. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11946. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11947. */
  11948. get: function () {
  11949. return Engine._ALPHA_SCREENMODE;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11955. // Delays
  11956. /** Defines that the ressource is not delayed*/
  11957. get: function () {
  11958. return Engine._DELAYLOADSTATE_NONE;
  11959. },
  11960. enumerable: true,
  11961. configurable: true
  11962. });
  11963. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11964. /** Defines that the ressource was successfully delay loaded */
  11965. get: function () {
  11966. return Engine._DELAYLOADSTATE_LOADED;
  11967. },
  11968. enumerable: true,
  11969. configurable: true
  11970. });
  11971. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11972. /** Defines that the ressource is currently delay loading */
  11973. get: function () {
  11974. return Engine._DELAYLOADSTATE_LOADING;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11980. /** Defines that the ressource is delayed and has not started loading */
  11981. get: function () {
  11982. return Engine._DELAYLOADSTATE_NOTLOADED;
  11983. },
  11984. enumerable: true,
  11985. configurable: true
  11986. });
  11987. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11988. /** ALPHA */
  11989. get: function () {
  11990. return Engine._TEXTUREFORMAT_ALPHA;
  11991. },
  11992. enumerable: true,
  11993. configurable: true
  11994. });
  11995. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11996. /** LUMINANCE */
  11997. get: function () {
  11998. return Engine._TEXTUREFORMAT_LUMINANCE;
  11999. },
  12000. enumerable: true,
  12001. configurable: true
  12002. });
  12003. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12004. /**
  12005. * R
  12006. */
  12007. get: function () {
  12008. return Engine._TEXTUREFORMAT_R;
  12009. },
  12010. enumerable: true,
  12011. configurable: true
  12012. });
  12013. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12014. /**
  12015. * RG
  12016. */
  12017. get: function () {
  12018. return Engine._TEXTUREFORMAT_RG;
  12019. },
  12020. enumerable: true,
  12021. configurable: true
  12022. });
  12023. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12024. /** LUMINANCE_ALPHA */
  12025. get: function () {
  12026. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12032. /** RGB */
  12033. get: function () {
  12034. return Engine._TEXTUREFORMAT_RGB;
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12040. /** RGBA */
  12041. get: function () {
  12042. return Engine._TEXTUREFORMAT_RGBA;
  12043. },
  12044. enumerable: true,
  12045. configurable: true
  12046. });
  12047. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12048. /** UNSIGNED_INT */
  12049. get: function () {
  12050. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12056. /** FLOAT */
  12057. get: function () {
  12058. return Engine._TEXTURETYPE_FLOAT;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12064. /** HALF_FLOAT */
  12065. get: function () {
  12066. return Engine._TEXTURETYPE_HALF_FLOAT;
  12067. },
  12068. enumerable: true,
  12069. configurable: true
  12070. });
  12071. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12072. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12073. get: function () {
  12074. return Engine._SCALEMODE_FLOOR;
  12075. },
  12076. enumerable: true,
  12077. configurable: true
  12078. });
  12079. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12080. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12081. get: function () {
  12082. return Engine._SCALEMODE_NEAREST;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12088. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12089. get: function () {
  12090. return Engine._SCALEMODE_CEILING;
  12091. },
  12092. enumerable: true,
  12093. configurable: true
  12094. });
  12095. Object.defineProperty(Engine, "Version", {
  12096. /**
  12097. * Returns the current version of the framework
  12098. */
  12099. get: function () {
  12100. return "3.3.0-alpha.9";
  12101. },
  12102. enumerable: true,
  12103. configurable: true
  12104. });
  12105. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12106. /**
  12107. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12108. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12109. */
  12110. get: function () {
  12111. return this._vrExclusivePointerMode;
  12112. },
  12113. enumerable: true,
  12114. configurable: true
  12115. });
  12116. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12117. /**
  12118. * Gets a boolean indicating that the engine supports uniform buffers
  12119. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12120. */
  12121. get: function () {
  12122. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12123. },
  12124. enumerable: true,
  12125. configurable: true
  12126. });
  12127. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12128. /**
  12129. * Gets a boolean indicating that only power of 2 textures are supported
  12130. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12131. */
  12132. get: function () {
  12133. return this._webGLVersion < 2 || this.forcePOTTextures;
  12134. },
  12135. enumerable: true,
  12136. configurable: true
  12137. });
  12138. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12139. /**
  12140. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12141. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12142. */
  12143. get: function () {
  12144. return this._doNotHandleContextLost;
  12145. },
  12146. set: function (value) {
  12147. this._doNotHandleContextLost = value;
  12148. },
  12149. enumerable: true,
  12150. configurable: true
  12151. });
  12152. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12153. /**
  12154. * Gets the performance monitor attached to this engine
  12155. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12156. */
  12157. get: function () {
  12158. return this._performanceMonitor;
  12159. },
  12160. enumerable: true,
  12161. configurable: true
  12162. });
  12163. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12164. /**
  12165. * Gets the list of texture formats supported
  12166. */
  12167. get: function () {
  12168. return this._texturesSupported;
  12169. },
  12170. enumerable: true,
  12171. configurable: true
  12172. });
  12173. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12174. /**
  12175. * Gets the list of texture formats in use
  12176. */
  12177. get: function () {
  12178. return this._textureFormatInUse;
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(Engine.prototype, "currentViewport", {
  12184. /**
  12185. * Gets the current viewport
  12186. */
  12187. get: function () {
  12188. return this._cachedViewport;
  12189. },
  12190. enumerable: true,
  12191. configurable: true
  12192. });
  12193. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12194. /**
  12195. * Gets the default empty texture
  12196. */
  12197. get: function () {
  12198. if (!this._emptyTexture) {
  12199. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12200. }
  12201. return this._emptyTexture;
  12202. },
  12203. enumerable: true,
  12204. configurable: true
  12205. });
  12206. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12207. /**
  12208. * Gets the default empty 3D texture
  12209. */
  12210. get: function () {
  12211. if (!this._emptyTexture3D) {
  12212. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12213. }
  12214. return this._emptyTexture3D;
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12220. /**
  12221. * Gets the default empty cube texture
  12222. */
  12223. get: function () {
  12224. if (!this._emptyCubeTexture) {
  12225. var faceData = new Uint8Array(4);
  12226. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12227. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12228. }
  12229. return this._emptyCubeTexture;
  12230. },
  12231. enumerable: true,
  12232. configurable: true
  12233. });
  12234. Engine.prototype._rebuildInternalTextures = function () {
  12235. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12236. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12237. var internalTexture = currentState_1[_i];
  12238. internalTexture._rebuild();
  12239. }
  12240. };
  12241. Engine.prototype._rebuildEffects = function () {
  12242. for (var key in this._compiledEffects) {
  12243. var effect = this._compiledEffects[key];
  12244. effect._prepareEffect();
  12245. }
  12246. BABYLON.Effect.ResetCache();
  12247. };
  12248. Engine.prototype._rebuildBuffers = function () {
  12249. // Index / Vertex
  12250. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12251. var scene = _a[_i];
  12252. scene.resetCachedMaterial();
  12253. scene._rebuildGeometries();
  12254. scene._rebuildTextures();
  12255. }
  12256. // Uniforms
  12257. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12258. var uniformBuffer = _c[_b];
  12259. uniformBuffer._rebuild();
  12260. }
  12261. };
  12262. Engine.prototype._initGLContext = function () {
  12263. // Caps
  12264. this._caps = new EngineCapabilities();
  12265. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12266. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12267. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12268. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12269. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12270. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12271. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12272. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12273. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12274. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12275. // Infos
  12276. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12277. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12278. if (rendererInfo != null) {
  12279. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12280. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12281. }
  12282. if (!this._glVendor) {
  12283. this._glVendor = "Unknown vendor";
  12284. }
  12285. if (!this._glRenderer) {
  12286. this._glRenderer = "Unknown renderer";
  12287. }
  12288. // Constants
  12289. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12290. if (this._gl.RGBA16F !== 0x881A) {
  12291. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12292. }
  12293. if (this._gl.RGBA32F !== 0x8814) {
  12294. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12295. }
  12296. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12297. this._gl.DEPTH24_STENCIL8 = 35056;
  12298. }
  12299. // Extensions
  12300. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12301. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12302. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12303. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12304. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12305. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12306. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12307. 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');
  12308. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12309. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12310. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12311. this._caps.highPrecisionShaderSupported = true;
  12312. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12313. if (this._caps.timerQuery) {
  12314. if (this._webGLVersion === 1) {
  12315. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12316. }
  12317. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12318. }
  12319. // Checks if some of the format renders first to allow the use of webgl inspector.
  12320. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12321. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12322. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12323. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12324. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12325. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12326. if (this._webGLVersion > 1) {
  12327. this._gl.HALF_FLOAT_OES = 0x140B;
  12328. }
  12329. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12330. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12331. // Draw buffers
  12332. if (this._webGLVersion > 1) {
  12333. this._caps.drawBuffersExtension = true;
  12334. }
  12335. else {
  12336. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12337. if (drawBuffersExtension !== null) {
  12338. this._caps.drawBuffersExtension = true;
  12339. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12340. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12341. for (var i = 0; i < 16; i++) {
  12342. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12343. }
  12344. }
  12345. else {
  12346. this._caps.drawBuffersExtension = false;
  12347. }
  12348. }
  12349. // Depth Texture
  12350. if (this._webGLVersion > 1) {
  12351. this._caps.depthTextureExtension = true;
  12352. }
  12353. else {
  12354. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12355. if (depthTextureExtension != null) {
  12356. this._caps.depthTextureExtension = true;
  12357. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12358. }
  12359. }
  12360. // Vertex array object
  12361. if (this._webGLVersion > 1) {
  12362. this._caps.vertexArrayObject = true;
  12363. }
  12364. else {
  12365. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12366. if (vertexArrayObjectExtension != null) {
  12367. this._caps.vertexArrayObject = true;
  12368. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12369. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12370. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12371. }
  12372. else {
  12373. this._caps.vertexArrayObject = false;
  12374. }
  12375. }
  12376. // Instances count
  12377. if (this._webGLVersion > 1) {
  12378. this._caps.instancedArrays = true;
  12379. }
  12380. else {
  12381. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12382. if (instanceExtension != null) {
  12383. this._caps.instancedArrays = true;
  12384. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12385. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12386. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12387. }
  12388. else {
  12389. this._caps.instancedArrays = false;
  12390. }
  12391. }
  12392. // Intelligently add supported compressed formats in order to check for.
  12393. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12394. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12395. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12396. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12397. if (this._caps.astc)
  12398. this.texturesSupported.push('-astc.ktx');
  12399. if (this._caps.s3tc)
  12400. this.texturesSupported.push('-dxt.ktx');
  12401. if (this._caps.pvrtc)
  12402. this.texturesSupported.push('-pvrtc.ktx');
  12403. if (this._caps.etc2)
  12404. this.texturesSupported.push('-etc2.ktx');
  12405. if (this._caps.etc1)
  12406. this.texturesSupported.push('-etc1.ktx');
  12407. if (this._gl.getShaderPrecisionFormat) {
  12408. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12409. if (highp) {
  12410. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12411. }
  12412. }
  12413. // Depth buffer
  12414. this.setDepthBuffer(true);
  12415. this.setDepthFunctionToLessOrEqual();
  12416. this.setDepthWrite(true);
  12417. // Texture maps
  12418. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12419. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12420. this._nextFreeTextureSlots.push(slot);
  12421. }
  12422. };
  12423. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12424. /**
  12425. * Gets version of the current webGL context
  12426. */
  12427. get: function () {
  12428. return this._webGLVersion;
  12429. },
  12430. enumerable: true,
  12431. configurable: true
  12432. });
  12433. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12434. /**
  12435. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12436. */
  12437. get: function () {
  12438. return this._isStencilEnable;
  12439. },
  12440. enumerable: true,
  12441. configurable: true
  12442. });
  12443. Engine.prototype._prepareWorkingCanvas = function () {
  12444. if (this._workingCanvas) {
  12445. return;
  12446. }
  12447. this._workingCanvas = document.createElement("canvas");
  12448. var context = this._workingCanvas.getContext("2d");
  12449. if (context) {
  12450. this._workingContext = context;
  12451. }
  12452. };
  12453. /**
  12454. * Reset the texture cache to empty state
  12455. */
  12456. Engine.prototype.resetTextureCache = function () {
  12457. for (var key in this._boundTexturesCache) {
  12458. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12459. continue;
  12460. }
  12461. var boundTexture = this._boundTexturesCache[key];
  12462. if (boundTexture) {
  12463. this._removeDesignatedSlot(boundTexture);
  12464. }
  12465. this._boundTexturesCache[key] = null;
  12466. }
  12467. if (!this.disableTextureBindingOptimization) {
  12468. this._nextFreeTextureSlots = [];
  12469. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12470. this._nextFreeTextureSlots.push(slot);
  12471. }
  12472. }
  12473. this._currentTextureChannel = -1;
  12474. };
  12475. /**
  12476. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12477. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12478. * @returns true if engine is in deterministic lock step mode
  12479. */
  12480. Engine.prototype.isDeterministicLockStep = function () {
  12481. return this._deterministicLockstep;
  12482. };
  12483. /**
  12484. * Gets the max steps when engine is running in deterministic lock step
  12485. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12486. * @returns the max steps
  12487. */
  12488. Engine.prototype.getLockstepMaxSteps = function () {
  12489. return this._lockstepMaxSteps;
  12490. };
  12491. /**
  12492. * Gets an object containing information about the current webGL context
  12493. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12494. */
  12495. Engine.prototype.getGlInfo = function () {
  12496. return {
  12497. vendor: this._glVendor,
  12498. renderer: this._glRenderer,
  12499. version: this._glVersion
  12500. };
  12501. };
  12502. /**
  12503. * Gets current aspect ratio
  12504. * @param camera defines the camera to use to get the aspect ratio
  12505. * @param useScreen defines if screen size must be used (or the current render target if any)
  12506. * @returns a number defining the aspect ratio
  12507. */
  12508. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12509. if (useScreen === void 0) { useScreen = false; }
  12510. var viewport = camera.viewport;
  12511. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12512. };
  12513. /**
  12514. * Gets current screen aspect ratio
  12515. * @returns a number defining the aspect ratio
  12516. */
  12517. Engine.prototype.getScreenAspectRatio = function () {
  12518. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12519. };
  12520. /**
  12521. * Gets the current render width
  12522. * @param useScreen defines if screen size must be used (or the current render target if any)
  12523. * @returns a number defining the current render width
  12524. */
  12525. Engine.prototype.getRenderWidth = function (useScreen) {
  12526. if (useScreen === void 0) { useScreen = false; }
  12527. if (!useScreen && this._currentRenderTarget) {
  12528. return this._currentRenderTarget.width;
  12529. }
  12530. return this._gl.drawingBufferWidth;
  12531. };
  12532. /**
  12533. * Gets the current render height
  12534. * @param useScreen defines if screen size must be used (or the current render target if any)
  12535. * @returns a number defining the current render height
  12536. */
  12537. Engine.prototype.getRenderHeight = function (useScreen) {
  12538. if (useScreen === void 0) { useScreen = false; }
  12539. if (!useScreen && this._currentRenderTarget) {
  12540. return this._currentRenderTarget.height;
  12541. }
  12542. return this._gl.drawingBufferHeight;
  12543. };
  12544. /**
  12545. * Gets the HTML canvas attached with the current webGL context
  12546. * @returns a HTML canvas
  12547. */
  12548. Engine.prototype.getRenderingCanvas = function () {
  12549. return this._renderingCanvas;
  12550. };
  12551. /**
  12552. * Gets the client rect of the HTML canvas attached with the current webGL context
  12553. * @returns a client rectanglee
  12554. */
  12555. Engine.prototype.getRenderingCanvasClientRect = function () {
  12556. if (!this._renderingCanvas) {
  12557. return null;
  12558. }
  12559. return this._renderingCanvas.getBoundingClientRect();
  12560. };
  12561. /**
  12562. * Defines the hardware scaling level.
  12563. * By default the hardware scaling level is computed from the window device ratio.
  12564. * 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.
  12565. * @param level defines the level to use
  12566. */
  12567. Engine.prototype.setHardwareScalingLevel = function (level) {
  12568. this._hardwareScalingLevel = level;
  12569. this.resize();
  12570. };
  12571. /**
  12572. * Gets the current hardware scaling level.
  12573. * By default the hardware scaling level is computed from the window device ratio.
  12574. * 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.
  12575. * @returns a number indicating the current hardware scaling level
  12576. */
  12577. Engine.prototype.getHardwareScalingLevel = function () {
  12578. return this._hardwareScalingLevel;
  12579. };
  12580. /**
  12581. * Gets the list of loaded textures
  12582. * @returns an array containing all loaded textures
  12583. */
  12584. Engine.prototype.getLoadedTexturesCache = function () {
  12585. return this._internalTexturesCache;
  12586. };
  12587. /**
  12588. * Gets the object containing all engine capabilities
  12589. * @returns the EngineCapabilities object
  12590. */
  12591. Engine.prototype.getCaps = function () {
  12592. return this._caps;
  12593. };
  12594. Object.defineProperty(Engine.prototype, "drawCalls", {
  12595. /** @hidden */
  12596. get: function () {
  12597. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12598. return 0;
  12599. },
  12600. enumerable: true,
  12601. configurable: true
  12602. });
  12603. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12604. /** @hidden */
  12605. get: function () {
  12606. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12607. return null;
  12608. },
  12609. enumerable: true,
  12610. configurable: true
  12611. });
  12612. /**
  12613. * Gets the current depth function
  12614. * @returns a number defining the depth function
  12615. */
  12616. Engine.prototype.getDepthFunction = function () {
  12617. return this._depthCullingState.depthFunc;
  12618. };
  12619. /**
  12620. * Sets the current depth function
  12621. * @param depthFunc defines the function to use
  12622. */
  12623. Engine.prototype.setDepthFunction = function (depthFunc) {
  12624. this._depthCullingState.depthFunc = depthFunc;
  12625. };
  12626. /**
  12627. * Sets the current depth function to GREATER
  12628. */
  12629. Engine.prototype.setDepthFunctionToGreater = function () {
  12630. this._depthCullingState.depthFunc = this._gl.GREATER;
  12631. };
  12632. /**
  12633. * Sets the current depth function to GEQUAL
  12634. */
  12635. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12636. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12637. };
  12638. /**
  12639. * Sets the current depth function to LESS
  12640. */
  12641. Engine.prototype.setDepthFunctionToLess = function () {
  12642. this._depthCullingState.depthFunc = this._gl.LESS;
  12643. };
  12644. /**
  12645. * Sets the current depth function to LEQUAL
  12646. */
  12647. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12648. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12649. };
  12650. /**
  12651. * Gets a boolean indicating if stencil buffer is enabled
  12652. * @returns the current stencil buffer state
  12653. */
  12654. Engine.prototype.getStencilBuffer = function () {
  12655. return this._stencilState.stencilTest;
  12656. };
  12657. /**
  12658. * Enable or disable the stencil buffer
  12659. * @param enable defines if the stencil buffer must be enabled or disabled
  12660. */
  12661. Engine.prototype.setStencilBuffer = function (enable) {
  12662. this._stencilState.stencilTest = enable;
  12663. };
  12664. /**
  12665. * Gets the current stencil mask
  12666. * @returns a number defining the new stencil mask to use
  12667. */
  12668. Engine.prototype.getStencilMask = function () {
  12669. return this._stencilState.stencilMask;
  12670. };
  12671. /**
  12672. * Sets the current stencil mask
  12673. * @param mask defines the new stencil mask to use
  12674. */
  12675. Engine.prototype.setStencilMask = function (mask) {
  12676. this._stencilState.stencilMask = mask;
  12677. };
  12678. /**
  12679. * Gets the current stencil function
  12680. * @returns a number defining the stencil function to use
  12681. */
  12682. Engine.prototype.getStencilFunction = function () {
  12683. return this._stencilState.stencilFunc;
  12684. };
  12685. /**
  12686. * Gets the current stencil reference value
  12687. * @returns a number defining the stencil reference value to use
  12688. */
  12689. Engine.prototype.getStencilFunctionReference = function () {
  12690. return this._stencilState.stencilFuncRef;
  12691. };
  12692. /**
  12693. * Gets the current stencil mask
  12694. * @returns a number defining the stencil mask to use
  12695. */
  12696. Engine.prototype.getStencilFunctionMask = function () {
  12697. return this._stencilState.stencilFuncMask;
  12698. };
  12699. /**
  12700. * Sets the current stencil function
  12701. * @param stencilFunc defines the new stencil function to use
  12702. */
  12703. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12704. this._stencilState.stencilFunc = stencilFunc;
  12705. };
  12706. /**
  12707. * Sets the current stencil reference
  12708. * @param reference defines the new stencil reference to use
  12709. */
  12710. Engine.prototype.setStencilFunctionReference = function (reference) {
  12711. this._stencilState.stencilFuncRef = reference;
  12712. };
  12713. /**
  12714. * Sets the current stencil mask
  12715. * @param mask defines the new stencil mask to use
  12716. */
  12717. Engine.prototype.setStencilFunctionMask = function (mask) {
  12718. this._stencilState.stencilFuncMask = mask;
  12719. };
  12720. /**
  12721. * Gets the current stencil operation when stencil fails
  12722. * @returns a number defining stencil operation to use when stencil fails
  12723. */
  12724. Engine.prototype.getStencilOperationFail = function () {
  12725. return this._stencilState.stencilOpStencilFail;
  12726. };
  12727. /**
  12728. * Gets the current stencil operation when depth fails
  12729. * @returns a number defining stencil operation to use when depth fails
  12730. */
  12731. Engine.prototype.getStencilOperationDepthFail = function () {
  12732. return this._stencilState.stencilOpDepthFail;
  12733. };
  12734. /**
  12735. * Gets the current stencil operation when stencil passes
  12736. * @returns a number defining stencil operation to use when stencil passes
  12737. */
  12738. Engine.prototype.getStencilOperationPass = function () {
  12739. return this._stencilState.stencilOpStencilDepthPass;
  12740. };
  12741. /**
  12742. * Sets the stencil operation to use when stencil fails
  12743. * @param operation defines the stencil operation to use when stencil fails
  12744. */
  12745. Engine.prototype.setStencilOperationFail = function (operation) {
  12746. this._stencilState.stencilOpStencilFail = operation;
  12747. };
  12748. /**
  12749. * Sets the stencil operation to use when depth fails
  12750. * @param operation defines the stencil operation to use when depth fails
  12751. */
  12752. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12753. this._stencilState.stencilOpDepthFail = operation;
  12754. };
  12755. /**
  12756. * Sets the stencil operation to use when stencil passes
  12757. * @param operation defines the stencil operation to use when stencil passes
  12758. */
  12759. Engine.prototype.setStencilOperationPass = function (operation) {
  12760. this._stencilState.stencilOpStencilDepthPass = operation;
  12761. };
  12762. /**
  12763. * Sets a boolean indicating if the dithering state is enabled or disabled
  12764. * @param value defines the dithering state
  12765. */
  12766. Engine.prototype.setDitheringState = function (value) {
  12767. if (value) {
  12768. this._gl.enable(this._gl.DITHER);
  12769. }
  12770. else {
  12771. this._gl.disable(this._gl.DITHER);
  12772. }
  12773. };
  12774. /**
  12775. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12776. * @param value defines the rasterizer state
  12777. */
  12778. Engine.prototype.setRasterizerState = function (value) {
  12779. if (value) {
  12780. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12781. }
  12782. else {
  12783. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12784. }
  12785. };
  12786. /**
  12787. * stop executing a render loop function and remove it from the execution array
  12788. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12789. */
  12790. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12791. if (!renderFunction) {
  12792. this._activeRenderLoops = [];
  12793. return;
  12794. }
  12795. var index = this._activeRenderLoops.indexOf(renderFunction);
  12796. if (index >= 0) {
  12797. this._activeRenderLoops.splice(index, 1);
  12798. }
  12799. };
  12800. /** @hidden */
  12801. Engine.prototype._renderLoop = function () {
  12802. if (!this._contextWasLost) {
  12803. var shouldRender = true;
  12804. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12805. shouldRender = false;
  12806. }
  12807. if (shouldRender) {
  12808. // Start new frame
  12809. this.beginFrame();
  12810. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12811. var renderFunction = this._activeRenderLoops[index];
  12812. renderFunction();
  12813. }
  12814. // Present
  12815. this.endFrame();
  12816. }
  12817. }
  12818. if (this._activeRenderLoops.length > 0) {
  12819. // Register new frame
  12820. var requester = null;
  12821. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12822. requester = this._vrDisplay;
  12823. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12824. }
  12825. else {
  12826. this._renderingQueueLaunched = false;
  12827. }
  12828. };
  12829. /**
  12830. * Register and execute a render loop. The engine can have more than one render function
  12831. * @param renderFunction defines the function to continuously execute
  12832. */
  12833. Engine.prototype.runRenderLoop = function (renderFunction) {
  12834. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12835. return;
  12836. }
  12837. this._activeRenderLoops.push(renderFunction);
  12838. if (!this._renderingQueueLaunched) {
  12839. this._renderingQueueLaunched = true;
  12840. this._bindedRenderFunction = this._renderLoop.bind(this);
  12841. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12842. }
  12843. };
  12844. /**
  12845. * Toggle full screen mode
  12846. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12847. * @param options defines an option object to be sent to the requestFullscreen function
  12848. */
  12849. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12850. if (this.isFullscreen) {
  12851. BABYLON.Tools.ExitFullscreen();
  12852. }
  12853. else {
  12854. this._pointerLockRequested = requestPointerLock;
  12855. if (this._renderingCanvas) {
  12856. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12857. }
  12858. }
  12859. };
  12860. /**
  12861. * Clear the current render buffer or the current render target (if any is set up)
  12862. * @param color defines the color to use
  12863. * @param backBuffer defines if the back buffer must be cleared
  12864. * @param depth defines if the depth buffer must be cleared
  12865. * @param stencil defines if the stencil buffer must be cleared
  12866. */
  12867. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12868. if (stencil === void 0) { stencil = false; }
  12869. this.applyStates();
  12870. var mode = 0;
  12871. if (backBuffer && color) {
  12872. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12873. mode |= this._gl.COLOR_BUFFER_BIT;
  12874. }
  12875. if (depth) {
  12876. this._gl.clearDepth(1.0);
  12877. mode |= this._gl.DEPTH_BUFFER_BIT;
  12878. }
  12879. if (stencil) {
  12880. this._gl.clearStencil(0);
  12881. mode |= this._gl.STENCIL_BUFFER_BIT;
  12882. }
  12883. this._gl.clear(mode);
  12884. };
  12885. /**
  12886. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12887. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12888. * @param y defines the y-coordinate of the corner of the clear rectangle
  12889. * @param width defines the width of the clear rectangle
  12890. * @param height defines the height of the clear rectangle
  12891. * @param clearColor defines the clear color
  12892. */
  12893. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12894. var gl = this._gl;
  12895. // Save state
  12896. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12897. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12898. // Change state
  12899. gl.enable(gl.SCISSOR_TEST);
  12900. gl.scissor(x, y, width, height);
  12901. // Clear
  12902. this.clear(clearColor, true, true, true);
  12903. // Restore state
  12904. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12905. if (curScissor === true) {
  12906. gl.enable(gl.SCISSOR_TEST);
  12907. }
  12908. else {
  12909. gl.disable(gl.SCISSOR_TEST);
  12910. }
  12911. };
  12912. /** @hidden */
  12913. Engine.prototype._viewport = function (x, y, width, height) {
  12914. if (x !== this._viewportCached.x ||
  12915. y !== this._viewportCached.y ||
  12916. width !== this._viewportCached.z ||
  12917. height !== this._viewportCached.w) {
  12918. this._viewportCached.x = x;
  12919. this._viewportCached.y = y;
  12920. this._viewportCached.z = width;
  12921. this._viewportCached.w = height;
  12922. this._gl.viewport(x, y, width, height);
  12923. }
  12924. };
  12925. /**
  12926. * Set the WebGL's viewport
  12927. * @param viewport defines the viewport element to be used
  12928. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12929. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12930. */
  12931. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12932. var width = requiredWidth || this.getRenderWidth();
  12933. var height = requiredHeight || this.getRenderHeight();
  12934. var x = viewport.x || 0;
  12935. var y = viewport.y || 0;
  12936. this._cachedViewport = viewport;
  12937. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12938. };
  12939. /**
  12940. * Directly set the WebGL Viewport
  12941. * @param x defines the x coordinate of the viewport (in screen space)
  12942. * @param y defines the y coordinate of the viewport (in screen space)
  12943. * @param width defines the width of the viewport (in screen space)
  12944. * @param height defines the height of the viewport (in screen space)
  12945. * @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
  12946. */
  12947. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12948. var currentViewport = this._cachedViewport;
  12949. this._cachedViewport = null;
  12950. this._viewport(x, y, width, height);
  12951. return currentViewport;
  12952. };
  12953. /**
  12954. * Begin a new frame
  12955. */
  12956. Engine.prototype.beginFrame = function () {
  12957. this.onBeginFrameObservable.notifyObservers(this);
  12958. this._measureFps();
  12959. };
  12960. /**
  12961. * Enf the current frame
  12962. */
  12963. Engine.prototype.endFrame = function () {
  12964. // Force a flush in case we are using a bad OS.
  12965. if (this._badOS) {
  12966. this.flushFramebuffer();
  12967. }
  12968. // Submit frame to the vr device, if enabled
  12969. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12970. // TODO: We should only submit the frame if we read frameData successfully.
  12971. this._vrDisplay.submitFrame();
  12972. }
  12973. this.onEndFrameObservable.notifyObservers(this);
  12974. };
  12975. /**
  12976. * Resize the view according to the canvas' size
  12977. */
  12978. Engine.prototype.resize = function () {
  12979. // We're not resizing the size of the canvas while in VR mode & presenting
  12980. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12981. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12982. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12983. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12984. }
  12985. };
  12986. /**
  12987. * Force a specific size of the canvas
  12988. * @param width defines the new canvas' width
  12989. * @param height defines the new canvas' height
  12990. */
  12991. Engine.prototype.setSize = function (width, height) {
  12992. if (!this._renderingCanvas) {
  12993. return;
  12994. }
  12995. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12996. return;
  12997. }
  12998. this._renderingCanvas.width = width;
  12999. this._renderingCanvas.height = height;
  13000. for (var index = 0; index < this.scenes.length; index++) {
  13001. var scene = this.scenes[index];
  13002. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13003. var cam = scene.cameras[camIndex];
  13004. cam._currentRenderId = 0;
  13005. }
  13006. }
  13007. if (this.onResizeObservable.hasObservers) {
  13008. this.onResizeObservable.notifyObservers(this);
  13009. }
  13010. };
  13011. // WebVR functions
  13012. /**
  13013. * Gets a boolean indicating if a webVR device was detected
  13014. * @returns true if a webVR device was detected
  13015. */
  13016. Engine.prototype.isVRDevicePresent = function () {
  13017. return !!this._vrDisplay;
  13018. };
  13019. /**
  13020. * Gets the current webVR device
  13021. * @returns the current webVR device (or null)
  13022. */
  13023. Engine.prototype.getVRDevice = function () {
  13024. return this._vrDisplay;
  13025. };
  13026. /**
  13027. * Initializes a webVR display and starts listening to display change events
  13028. * The onVRDisplayChangedObservable will be notified upon these changes
  13029. * @returns The onVRDisplayChangedObservable
  13030. */
  13031. Engine.prototype.initWebVR = function () {
  13032. this.initWebVRAsync();
  13033. return this.onVRDisplayChangedObservable;
  13034. };
  13035. /**
  13036. * Initializes a webVR display and starts listening to display change events
  13037. * The onVRDisplayChangedObservable will be notified upon these changes
  13038. * @returns A promise containing a VRDisplay and if vr is supported
  13039. */
  13040. Engine.prototype.initWebVRAsync = function () {
  13041. var _this = this;
  13042. var notifyObservers = function () {
  13043. var eventArgs = {
  13044. vrDisplay: _this._vrDisplay,
  13045. vrSupported: _this._vrSupported
  13046. };
  13047. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13048. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13049. };
  13050. if (!this._onVrDisplayConnect) {
  13051. this._onVrDisplayConnect = function (event) {
  13052. _this._vrDisplay = event.display;
  13053. notifyObservers();
  13054. };
  13055. this._onVrDisplayDisconnect = function () {
  13056. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13057. _this._vrDisplay = undefined;
  13058. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13059. notifyObservers();
  13060. };
  13061. this._onVrDisplayPresentChange = function () {
  13062. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13063. };
  13064. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13065. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13066. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13067. }
  13068. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13069. this._webVRInitPromise.then(notifyObservers);
  13070. return this._webVRInitPromise;
  13071. };
  13072. /**
  13073. * Call this function to switch to webVR mode
  13074. * Will do nothing if webVR is not supported or if there is no webVR device
  13075. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13076. */
  13077. Engine.prototype.enableVR = function () {
  13078. var _this = this;
  13079. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13080. var onResolved = function () {
  13081. _this.onVRRequestPresentComplete.notifyObservers(true);
  13082. _this._onVRFullScreenTriggered();
  13083. };
  13084. var onRejected = function () {
  13085. _this.onVRRequestPresentComplete.notifyObservers(false);
  13086. };
  13087. this.onVRRequestPresentStart.notifyObservers(this);
  13088. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13089. }
  13090. };
  13091. /**
  13092. * Call this function to leave webVR mode
  13093. * Will do nothing if webVR is not supported or if there is no webVR device
  13094. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13095. */
  13096. Engine.prototype.disableVR = function () {
  13097. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13098. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13099. }
  13100. };
  13101. Engine.prototype._getVRDisplaysAsync = function () {
  13102. var _this = this;
  13103. return new Promise(function (res, rej) {
  13104. if (navigator.getVRDisplays) {
  13105. navigator.getVRDisplays().then(function (devices) {
  13106. _this._vrSupported = true;
  13107. // note that devices may actually be an empty array. This is fine;
  13108. // we expect this._vrDisplay to be undefined in this case.
  13109. _this._vrDisplay = devices[0];
  13110. res({
  13111. vrDisplay: _this._vrDisplay,
  13112. vrSupported: _this._vrSupported
  13113. });
  13114. });
  13115. }
  13116. else {
  13117. _this._vrDisplay = undefined;
  13118. _this._vrSupported = false;
  13119. res({
  13120. vrDisplay: _this._vrDisplay,
  13121. vrSupported: _this._vrSupported
  13122. });
  13123. }
  13124. });
  13125. };
  13126. /**
  13127. * Binds the frame buffer to the specified texture.
  13128. * @param texture The texture to render to or null for the default canvas
  13129. * @param faceIndex The face of the texture to render to in case of cube texture
  13130. * @param requiredWidth The width of the target to render to
  13131. * @param requiredHeight The height of the target to render to
  13132. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13133. * @param depthStencilTexture The depth stencil texture to use to render
  13134. * @param lodLevel defines le lod level to bind to the frame buffer
  13135. */
  13136. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13137. if (lodLevel === void 0) { lodLevel = 0; }
  13138. if (this._currentRenderTarget) {
  13139. this.unBindFramebuffer(this._currentRenderTarget);
  13140. }
  13141. this._currentRenderTarget = texture;
  13142. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13143. var gl = this._gl;
  13144. if (texture.isCube) {
  13145. if (faceIndex === undefined) {
  13146. faceIndex = 0;
  13147. }
  13148. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13149. if (depthStencilTexture) {
  13150. if (depthStencilTexture._generateStencilBuffer) {
  13151. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13152. }
  13153. else {
  13154. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13155. }
  13156. }
  13157. }
  13158. if (this._cachedViewport && !forceFullscreenViewport) {
  13159. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13160. }
  13161. else {
  13162. if (!requiredWidth) {
  13163. requiredWidth = texture.width;
  13164. if (lodLevel) {
  13165. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13166. }
  13167. }
  13168. if (!requiredHeight) {
  13169. requiredHeight = texture.height;
  13170. if (lodLevel) {
  13171. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13172. }
  13173. }
  13174. this._viewport(0, 0, requiredWidth, requiredHeight);
  13175. }
  13176. this.wipeCaches();
  13177. };
  13178. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13179. if (this._currentFramebuffer !== framebuffer) {
  13180. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13181. this._currentFramebuffer = framebuffer;
  13182. }
  13183. };
  13184. /**
  13185. * Unbind the current render target texture from the webGL context
  13186. * @param texture defines the render target texture to unbind
  13187. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13188. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13189. */
  13190. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13191. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13192. this._currentRenderTarget = null;
  13193. // If MSAA, we need to bitblt back to main texture
  13194. var gl = this._gl;
  13195. if (texture._MSAAFramebuffer) {
  13196. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13197. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13198. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13199. }
  13200. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13201. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13202. gl.generateMipmap(gl.TEXTURE_2D);
  13203. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13204. }
  13205. if (onBeforeUnbind) {
  13206. if (texture._MSAAFramebuffer) {
  13207. // Bind the correct framebuffer
  13208. this.bindUnboundFramebuffer(texture._framebuffer);
  13209. }
  13210. onBeforeUnbind();
  13211. }
  13212. this.bindUnboundFramebuffer(null);
  13213. };
  13214. /**
  13215. * Unbind a list of render target textures from the webGL context
  13216. * This is used only when drawBuffer extension or webGL2 are active
  13217. * @param textures defines the render target textures to unbind
  13218. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13219. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13220. */
  13221. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13222. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13223. this._currentRenderTarget = null;
  13224. // If MSAA, we need to bitblt back to main texture
  13225. var gl = this._gl;
  13226. if (textures[0]._MSAAFramebuffer) {
  13227. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13228. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13229. var attachments = textures[0]._attachments;
  13230. if (!attachments) {
  13231. attachments = new Array(textures.length);
  13232. textures[0]._attachments = attachments;
  13233. }
  13234. for (var i = 0; i < textures.length; i++) {
  13235. var texture = textures[i];
  13236. for (var j = 0; j < attachments.length; j++) {
  13237. attachments[j] = gl.NONE;
  13238. }
  13239. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13240. gl.readBuffer(attachments[i]);
  13241. gl.drawBuffers(attachments);
  13242. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13243. }
  13244. for (var i = 0; i < attachments.length; i++) {
  13245. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13246. }
  13247. gl.drawBuffers(attachments);
  13248. }
  13249. for (var i = 0; i < textures.length; i++) {
  13250. var texture = textures[i];
  13251. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13252. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13253. gl.generateMipmap(gl.TEXTURE_2D);
  13254. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13255. }
  13256. }
  13257. if (onBeforeUnbind) {
  13258. if (textures[0]._MSAAFramebuffer) {
  13259. // Bind the correct framebuffer
  13260. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13261. }
  13262. onBeforeUnbind();
  13263. }
  13264. this.bindUnboundFramebuffer(null);
  13265. };
  13266. /**
  13267. * Force the mipmap generation for the given render target texture
  13268. * @param texture defines the render target texture to use
  13269. */
  13270. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13271. if (texture.generateMipMaps) {
  13272. var gl = this._gl;
  13273. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13274. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13275. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13276. }
  13277. };
  13278. /**
  13279. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13280. */
  13281. Engine.prototype.flushFramebuffer = function () {
  13282. this._gl.flush();
  13283. };
  13284. /**
  13285. * Unbind the current render target and bind the default framebuffer
  13286. */
  13287. Engine.prototype.restoreDefaultFramebuffer = function () {
  13288. if (this._currentRenderTarget) {
  13289. this.unBindFramebuffer(this._currentRenderTarget);
  13290. }
  13291. else {
  13292. this.bindUnboundFramebuffer(null);
  13293. }
  13294. if (this._cachedViewport) {
  13295. this.setViewport(this._cachedViewport);
  13296. }
  13297. this.wipeCaches();
  13298. };
  13299. // UBOs
  13300. /**
  13301. * Create an uniform buffer
  13302. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13303. * @param elements defines the content of the uniform buffer
  13304. * @returns the webGL uniform buffer
  13305. */
  13306. Engine.prototype.createUniformBuffer = function (elements) {
  13307. var ubo = this._gl.createBuffer();
  13308. if (!ubo) {
  13309. throw new Error("Unable to create uniform buffer");
  13310. }
  13311. this.bindUniformBuffer(ubo);
  13312. if (elements instanceof Float32Array) {
  13313. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13314. }
  13315. else {
  13316. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13317. }
  13318. this.bindUniformBuffer(null);
  13319. ubo.references = 1;
  13320. return ubo;
  13321. };
  13322. /**
  13323. * Create a dynamic uniform buffer
  13324. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13325. * @param elements defines the content of the uniform buffer
  13326. * @returns the webGL uniform buffer
  13327. */
  13328. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13329. var ubo = this._gl.createBuffer();
  13330. if (!ubo) {
  13331. throw new Error("Unable to create dynamic uniform buffer");
  13332. }
  13333. this.bindUniformBuffer(ubo);
  13334. if (elements instanceof Float32Array) {
  13335. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13336. }
  13337. else {
  13338. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13339. }
  13340. this.bindUniformBuffer(null);
  13341. ubo.references = 1;
  13342. return ubo;
  13343. };
  13344. /**
  13345. * Update an existing uniform buffer
  13346. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13347. * @param uniformBuffer defines the target uniform buffer
  13348. * @param elements defines the content to update
  13349. * @param offset defines the offset in the uniform buffer where update should start
  13350. * @param count defines the size of the data to update
  13351. */
  13352. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13353. this.bindUniformBuffer(uniformBuffer);
  13354. if (offset === undefined) {
  13355. offset = 0;
  13356. }
  13357. if (count === undefined) {
  13358. if (elements instanceof Float32Array) {
  13359. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13360. }
  13361. else {
  13362. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13363. }
  13364. }
  13365. else {
  13366. if (elements instanceof Float32Array) {
  13367. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13368. }
  13369. else {
  13370. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13371. }
  13372. }
  13373. this.bindUniformBuffer(null);
  13374. };
  13375. // VBOs
  13376. Engine.prototype._resetVertexBufferBinding = function () {
  13377. this.bindArrayBuffer(null);
  13378. this._cachedVertexBuffers = null;
  13379. };
  13380. /**
  13381. * Creates a vertex buffer
  13382. * @param data the data for the vertex buffer
  13383. * @returns the new WebGL static buffer
  13384. */
  13385. Engine.prototype.createVertexBuffer = function (data) {
  13386. var vbo = this._gl.createBuffer();
  13387. if (!vbo) {
  13388. throw new Error("Unable to create vertex buffer");
  13389. }
  13390. this.bindArrayBuffer(vbo);
  13391. if (data instanceof Array) {
  13392. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13393. }
  13394. else {
  13395. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13396. }
  13397. this._resetVertexBufferBinding();
  13398. vbo.references = 1;
  13399. return vbo;
  13400. };
  13401. /**
  13402. * Creates a dynamic vertex buffer
  13403. * @param data the data for the dynamic vertex buffer
  13404. * @returns the new WebGL dynamic buffer
  13405. */
  13406. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13407. var vbo = this._gl.createBuffer();
  13408. if (!vbo) {
  13409. throw new Error("Unable to create dynamic vertex buffer");
  13410. }
  13411. this.bindArrayBuffer(vbo);
  13412. if (data instanceof Array) {
  13413. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13414. }
  13415. else {
  13416. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13417. }
  13418. this._resetVertexBufferBinding();
  13419. vbo.references = 1;
  13420. return vbo;
  13421. };
  13422. /**
  13423. * Update a dynamic index buffer
  13424. * @param indexBuffer defines the target index buffer
  13425. * @param indices defines the data to update
  13426. * @param offset defines the offset in the target index buffer where update should start
  13427. */
  13428. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13429. if (offset === void 0) { offset = 0; }
  13430. // Force cache update
  13431. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13432. this.bindIndexBuffer(indexBuffer);
  13433. var arrayBuffer;
  13434. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13435. arrayBuffer = indices;
  13436. }
  13437. else {
  13438. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13439. }
  13440. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13441. this._resetIndexBufferBinding();
  13442. };
  13443. /**
  13444. * Updates a dynamic vertex buffer.
  13445. * @param vertexBuffer the vertex buffer to update
  13446. * @param data the data used to update the vertex buffer
  13447. * @param byteOffset the byte offset of the data
  13448. * @param byteLength the byte length of the data
  13449. */
  13450. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13451. this.bindArrayBuffer(vertexBuffer);
  13452. if (byteOffset === undefined) {
  13453. byteOffset = 0;
  13454. }
  13455. if (byteLength === undefined) {
  13456. if (data instanceof Array) {
  13457. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13458. }
  13459. else {
  13460. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13461. }
  13462. }
  13463. else {
  13464. if (data instanceof Array) {
  13465. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13466. }
  13467. else {
  13468. if (data instanceof ArrayBuffer) {
  13469. data = new Uint8Array(data, byteOffset, byteLength);
  13470. }
  13471. else {
  13472. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13473. }
  13474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13475. }
  13476. }
  13477. this._resetVertexBufferBinding();
  13478. };
  13479. Engine.prototype._resetIndexBufferBinding = function () {
  13480. this.bindIndexBuffer(null);
  13481. this._cachedIndexBuffer = null;
  13482. };
  13483. /**
  13484. * Creates a new index buffer
  13485. * @param indices defines the content of the index buffer
  13486. * @param updatable defines if the index buffer must be updatable
  13487. * @returns a new webGL buffer
  13488. */
  13489. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13490. var vbo = this._gl.createBuffer();
  13491. if (!vbo) {
  13492. throw new Error("Unable to create index buffer");
  13493. }
  13494. this.bindIndexBuffer(vbo);
  13495. // Check for 32 bits indices
  13496. var arrayBuffer;
  13497. var need32Bits = false;
  13498. if (indices instanceof Uint16Array) {
  13499. arrayBuffer = indices;
  13500. }
  13501. else {
  13502. //check 32 bit support
  13503. if (this._caps.uintIndices) {
  13504. if (indices instanceof Uint32Array) {
  13505. arrayBuffer = indices;
  13506. need32Bits = true;
  13507. }
  13508. else {
  13509. //number[] or Int32Array, check if 32 bit is necessary
  13510. for (var index = 0; index < indices.length; index++) {
  13511. if (indices[index] > 65535) {
  13512. need32Bits = true;
  13513. break;
  13514. }
  13515. }
  13516. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13517. }
  13518. }
  13519. else {
  13520. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13521. arrayBuffer = new Uint16Array(indices);
  13522. }
  13523. }
  13524. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13525. this._resetIndexBufferBinding();
  13526. vbo.references = 1;
  13527. vbo.is32Bits = need32Bits;
  13528. return vbo;
  13529. };
  13530. /**
  13531. * Bind a webGL buffer to the webGL context
  13532. * @param buffer defines the buffer to bind
  13533. */
  13534. Engine.prototype.bindArrayBuffer = function (buffer) {
  13535. if (!this._vaoRecordInProgress) {
  13536. this._unbindVertexArrayObject();
  13537. }
  13538. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13539. };
  13540. /**
  13541. * Bind an uniform buffer to the current webGL context
  13542. * @param buffer defines the buffer to bind
  13543. */
  13544. Engine.prototype.bindUniformBuffer = function (buffer) {
  13545. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13546. };
  13547. /**
  13548. * Bind a buffer to the current webGL context at a given location
  13549. * @param buffer defines the buffer to bind
  13550. * @param location defines the index where to bind the buffer
  13551. */
  13552. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13553. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13554. };
  13555. /**
  13556. * Bind a specific block at a given index in a specific shader program
  13557. * @param shaderProgram defines the shader program
  13558. * @param blockName defines the block name
  13559. * @param index defines the index where to bind the block
  13560. */
  13561. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13562. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13563. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13564. };
  13565. ;
  13566. Engine.prototype.bindIndexBuffer = function (buffer) {
  13567. if (!this._vaoRecordInProgress) {
  13568. this._unbindVertexArrayObject();
  13569. }
  13570. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13571. };
  13572. Engine.prototype.bindBuffer = function (buffer, target) {
  13573. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13574. this._gl.bindBuffer(target, buffer);
  13575. this._currentBoundBuffer[target] = buffer;
  13576. }
  13577. };
  13578. /**
  13579. * update the bound buffer with the given data
  13580. * @param data defines the data to update
  13581. */
  13582. Engine.prototype.updateArrayBuffer = function (data) {
  13583. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13584. };
  13585. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13586. var pointer = this._currentBufferPointers[indx];
  13587. var changed = false;
  13588. if (!pointer.active) {
  13589. changed = true;
  13590. pointer.active = true;
  13591. pointer.index = indx;
  13592. pointer.size = size;
  13593. pointer.type = type;
  13594. pointer.normalized = normalized;
  13595. pointer.stride = stride;
  13596. pointer.offset = offset;
  13597. pointer.buffer = buffer;
  13598. }
  13599. else {
  13600. if (pointer.buffer !== buffer) {
  13601. pointer.buffer = buffer;
  13602. changed = true;
  13603. }
  13604. if (pointer.size !== size) {
  13605. pointer.size = size;
  13606. changed = true;
  13607. }
  13608. if (pointer.type !== type) {
  13609. pointer.type = type;
  13610. changed = true;
  13611. }
  13612. if (pointer.normalized !== normalized) {
  13613. pointer.normalized = normalized;
  13614. changed = true;
  13615. }
  13616. if (pointer.stride !== stride) {
  13617. pointer.stride = stride;
  13618. changed = true;
  13619. }
  13620. if (pointer.offset !== offset) {
  13621. pointer.offset = offset;
  13622. changed = true;
  13623. }
  13624. }
  13625. if (changed || this._vaoRecordInProgress) {
  13626. this.bindArrayBuffer(buffer);
  13627. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13628. }
  13629. };
  13630. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13631. if (indexBuffer == null) {
  13632. return;
  13633. }
  13634. if (this._cachedIndexBuffer !== indexBuffer) {
  13635. this._cachedIndexBuffer = indexBuffer;
  13636. this.bindIndexBuffer(indexBuffer);
  13637. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13638. }
  13639. };
  13640. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13641. var attributes = effect.getAttributesNames();
  13642. if (!this._vaoRecordInProgress) {
  13643. this._unbindVertexArrayObject();
  13644. }
  13645. this.unbindAllAttributes();
  13646. for (var index = 0; index < attributes.length; index++) {
  13647. var order = effect.getAttributeLocation(index);
  13648. if (order >= 0) {
  13649. var vertexBuffer = vertexBuffers[attributes[index]];
  13650. if (!vertexBuffer) {
  13651. continue;
  13652. }
  13653. this._gl.enableVertexAttribArray(order);
  13654. if (!this._vaoRecordInProgress) {
  13655. this._vertexAttribArraysEnabled[order] = true;
  13656. }
  13657. var buffer = vertexBuffer.getBuffer();
  13658. if (buffer) {
  13659. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13660. if (vertexBuffer.getIsInstanced()) {
  13661. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13662. if (!this._vaoRecordInProgress) {
  13663. this._currentInstanceLocations.push(order);
  13664. this._currentInstanceBuffers.push(buffer);
  13665. }
  13666. }
  13667. }
  13668. }
  13669. }
  13670. };
  13671. /**
  13672. * Records a vertex array object
  13673. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13674. * @param vertexBuffers defines the list of vertex buffers to store
  13675. * @param indexBuffer defines the index buffer to store
  13676. * @param effect defines the effect to store
  13677. * @returns the new vertex array object
  13678. */
  13679. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13680. var vao = this._gl.createVertexArray();
  13681. this._vaoRecordInProgress = true;
  13682. this._gl.bindVertexArray(vao);
  13683. this._mustWipeVertexAttributes = true;
  13684. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13685. this.bindIndexBuffer(indexBuffer);
  13686. this._vaoRecordInProgress = false;
  13687. this._gl.bindVertexArray(null);
  13688. return vao;
  13689. };
  13690. /**
  13691. * Bind a specific vertex array object
  13692. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13693. * @param vertexArrayObject defines the vertex array object to bind
  13694. * @param indexBuffer defines the index buffer to bind
  13695. */
  13696. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13697. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13698. this._cachedVertexArrayObject = vertexArrayObject;
  13699. this._gl.bindVertexArray(vertexArrayObject);
  13700. this._cachedVertexBuffers = null;
  13701. this._cachedIndexBuffer = null;
  13702. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13703. this._mustWipeVertexAttributes = true;
  13704. }
  13705. };
  13706. /**
  13707. * Bind webGl buffers directly to the webGL context
  13708. * @param vertexBuffer defines the vertex buffer to bind
  13709. * @param indexBuffer defines the index buffer to bind
  13710. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13711. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13712. * @param effect defines the effect associated with the vertex buffer
  13713. */
  13714. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13715. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13716. this._cachedVertexBuffers = vertexBuffer;
  13717. this._cachedEffectForVertexBuffers = effect;
  13718. var attributesCount = effect.getAttributesCount();
  13719. this._unbindVertexArrayObject();
  13720. this.unbindAllAttributes();
  13721. var offset = 0;
  13722. for (var index = 0; index < attributesCount; index++) {
  13723. if (index < vertexDeclaration.length) {
  13724. var order = effect.getAttributeLocation(index);
  13725. if (order >= 0) {
  13726. this._gl.enableVertexAttribArray(order);
  13727. this._vertexAttribArraysEnabled[order] = true;
  13728. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13729. }
  13730. offset += vertexDeclaration[index] * 4;
  13731. }
  13732. }
  13733. }
  13734. this._bindIndexBufferWithCache(indexBuffer);
  13735. };
  13736. Engine.prototype._unbindVertexArrayObject = function () {
  13737. if (!this._cachedVertexArrayObject) {
  13738. return;
  13739. }
  13740. this._cachedVertexArrayObject = null;
  13741. this._gl.bindVertexArray(null);
  13742. };
  13743. /**
  13744. * Bind a list of vertex buffers to the webGL context
  13745. * @param vertexBuffers defines the list of vertex buffers to bind
  13746. * @param indexBuffer defines the index buffer to bind
  13747. * @param effect defines the effect associated with the vertex buffers
  13748. */
  13749. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13750. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13751. this._cachedVertexBuffers = vertexBuffers;
  13752. this._cachedEffectForVertexBuffers = effect;
  13753. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13754. }
  13755. this._bindIndexBufferWithCache(indexBuffer);
  13756. };
  13757. /**
  13758. * Unbind all instance attributes
  13759. */
  13760. Engine.prototype.unbindInstanceAttributes = function () {
  13761. var boundBuffer;
  13762. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13763. var instancesBuffer = this._currentInstanceBuffers[i];
  13764. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13765. boundBuffer = instancesBuffer;
  13766. this.bindArrayBuffer(instancesBuffer);
  13767. }
  13768. var offsetLocation = this._currentInstanceLocations[i];
  13769. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13770. }
  13771. this._currentInstanceBuffers.length = 0;
  13772. this._currentInstanceLocations.length = 0;
  13773. };
  13774. /**
  13775. * Release and free the memory of a vertex array object
  13776. * @param vao defines the vertex array object to delete
  13777. */
  13778. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13779. this._gl.deleteVertexArray(vao);
  13780. };
  13781. /** @hidden */
  13782. Engine.prototype._releaseBuffer = function (buffer) {
  13783. buffer.references--;
  13784. if (buffer.references === 0) {
  13785. this._gl.deleteBuffer(buffer);
  13786. return true;
  13787. }
  13788. return false;
  13789. };
  13790. /**
  13791. * Creates a webGL buffer to use with instanciation
  13792. * @param capacity defines the size of the buffer
  13793. * @returns the webGL buffer
  13794. */
  13795. Engine.prototype.createInstancesBuffer = function (capacity) {
  13796. var buffer = this._gl.createBuffer();
  13797. if (!buffer) {
  13798. throw new Error("Unable to create instance buffer");
  13799. }
  13800. buffer.capacity = capacity;
  13801. this.bindArrayBuffer(buffer);
  13802. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13803. return buffer;
  13804. };
  13805. /**
  13806. * Delete a webGL buffer used with instanciation
  13807. * @param buffer defines the webGL buffer to delete
  13808. */
  13809. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13810. this._gl.deleteBuffer(buffer);
  13811. };
  13812. /**
  13813. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13814. * @param instancesBuffer defines the webGL buffer to update and bind
  13815. * @param data defines the data to store in the buffer
  13816. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13817. */
  13818. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13819. this.bindArrayBuffer(instancesBuffer);
  13820. if (data) {
  13821. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13822. }
  13823. if (offsetLocations[0].index !== undefined) {
  13824. var stride = 0;
  13825. for (var i = 0; i < offsetLocations.length; i++) {
  13826. var ai = offsetLocations[i];
  13827. stride += ai.attributeSize * 4;
  13828. }
  13829. for (var i = 0; i < offsetLocations.length; i++) {
  13830. var ai = offsetLocations[i];
  13831. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13832. this._gl.enableVertexAttribArray(ai.index);
  13833. this._vertexAttribArraysEnabled[ai.index] = true;
  13834. }
  13835. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13836. this._gl.vertexAttribDivisor(ai.index, 1);
  13837. this._currentInstanceLocations.push(ai.index);
  13838. this._currentInstanceBuffers.push(instancesBuffer);
  13839. }
  13840. }
  13841. else {
  13842. for (var index = 0; index < 4; index++) {
  13843. var offsetLocation = offsetLocations[index];
  13844. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13845. this._gl.enableVertexAttribArray(offsetLocation);
  13846. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13847. }
  13848. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13849. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13850. this._currentInstanceLocations.push(offsetLocation);
  13851. this._currentInstanceBuffers.push(instancesBuffer);
  13852. }
  13853. }
  13854. };
  13855. /**
  13856. * Apply all cached states (depth, culling, stencil and alpha)
  13857. */
  13858. Engine.prototype.applyStates = function () {
  13859. this._depthCullingState.apply(this._gl);
  13860. this._stencilState.apply(this._gl);
  13861. this._alphaState.apply(this._gl);
  13862. };
  13863. /**
  13864. * Send a draw order
  13865. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13866. * @param indexStart defines the starting index
  13867. * @param indexCount defines the number of index to draw
  13868. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13869. */
  13870. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13871. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13872. };
  13873. /**
  13874. * Draw a list of points
  13875. * @param verticesStart defines the index of first vertex to draw
  13876. * @param verticesCount defines the count of vertices to draw
  13877. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13878. */
  13879. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13880. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13881. };
  13882. /**
  13883. * Draw a list of unindexed primitives
  13884. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13885. * @param verticesStart defines the index of first vertex to draw
  13886. * @param verticesCount defines the count of vertices to draw
  13887. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13888. */
  13889. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13890. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13891. };
  13892. /**
  13893. * Draw a list of indexed primitives
  13894. * @param fillMode defines the primitive to use
  13895. * @param indexStart defines the starting index
  13896. * @param indexCount defines the number of index to draw
  13897. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13898. */
  13899. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13900. // Apply states
  13901. this.applyStates();
  13902. this._drawCalls.addCount(1, false);
  13903. // Render
  13904. var drawMode = this._drawMode(fillMode);
  13905. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13906. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13907. if (instancesCount) {
  13908. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13909. }
  13910. else {
  13911. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13912. }
  13913. };
  13914. /**
  13915. * Draw a list of unindexed primitives
  13916. * @param fillMode defines the primitive to use
  13917. * @param verticesStart defines the index of first vertex to draw
  13918. * @param verticesCount defines the count of vertices to draw
  13919. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13920. */
  13921. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13922. // Apply states
  13923. this.applyStates();
  13924. this._drawCalls.addCount(1, false);
  13925. var drawMode = this._drawMode(fillMode);
  13926. if (instancesCount) {
  13927. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13928. }
  13929. else {
  13930. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13931. }
  13932. };
  13933. Engine.prototype._drawMode = function (fillMode) {
  13934. switch (fillMode) {
  13935. // Triangle views
  13936. case BABYLON.Material.TriangleFillMode:
  13937. return this._gl.TRIANGLES;
  13938. case BABYLON.Material.PointFillMode:
  13939. return this._gl.POINTS;
  13940. case BABYLON.Material.WireFrameFillMode:
  13941. return this._gl.LINES;
  13942. // Draw modes
  13943. case BABYLON.Material.PointListDrawMode:
  13944. return this._gl.POINTS;
  13945. case BABYLON.Material.LineListDrawMode:
  13946. return this._gl.LINES;
  13947. case BABYLON.Material.LineLoopDrawMode:
  13948. return this._gl.LINE_LOOP;
  13949. case BABYLON.Material.LineStripDrawMode:
  13950. return this._gl.LINE_STRIP;
  13951. case BABYLON.Material.TriangleStripDrawMode:
  13952. return this._gl.TRIANGLE_STRIP;
  13953. case BABYLON.Material.TriangleFanDrawMode:
  13954. return this._gl.TRIANGLE_FAN;
  13955. default:
  13956. return this._gl.TRIANGLES;
  13957. }
  13958. };
  13959. // Shaders
  13960. /** @hidden */
  13961. Engine.prototype._releaseEffect = function (effect) {
  13962. if (this._compiledEffects[effect._key]) {
  13963. delete this._compiledEffects[effect._key];
  13964. this._deleteProgram(effect.getProgram());
  13965. }
  13966. };
  13967. /** @hidden */
  13968. Engine.prototype._deleteProgram = function (program) {
  13969. if (program) {
  13970. program.__SPECTOR_rebuildProgram = null;
  13971. if (program.transformFeedback) {
  13972. this.deleteTransformFeedback(program.transformFeedback);
  13973. program.transformFeedback = null;
  13974. }
  13975. this._gl.deleteProgram(program);
  13976. }
  13977. };
  13978. /**
  13979. * Create a new effect (used to store vertex/fragment shaders)
  13980. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13981. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13982. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13983. * @param samplers defines an array of string used to represent textures
  13984. * @param defines defines the string containing the defines to use to compile the shaders
  13985. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13986. * @param onCompiled defines a function to call when the effect creation is successful
  13987. * @param onError defines a function to call when the effect creation has failed
  13988. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13989. * @returns the new Effect
  13990. */
  13991. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13992. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13993. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13994. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13995. if (this._compiledEffects[name]) {
  13996. var compiledEffect = this._compiledEffects[name];
  13997. if (onCompiled && compiledEffect.isReady()) {
  13998. onCompiled(compiledEffect);
  13999. }
  14000. return compiledEffect;
  14001. }
  14002. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14003. effect._key = name;
  14004. this._compiledEffects[name] = effect;
  14005. return effect;
  14006. };
  14007. /**
  14008. * Create an effect to use with particle systems.
  14009. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14010. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14011. * @param uniformsNames defines a list of attribute names
  14012. * @param samplers defines an array of string used to represent textures
  14013. * @param defines defines the string containing the defines to use to compile the shaders
  14014. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14015. * @param onCompiled defines a function to call when the effect creation is successful
  14016. * @param onError defines a function to call when the effect creation has failed
  14017. * @returns the new Effect
  14018. */
  14019. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14020. if (uniformsNames === void 0) { uniformsNames = []; }
  14021. if (samplers === void 0) { samplers = []; }
  14022. if (defines === void 0) { defines = ""; }
  14023. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14024. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14025. if (defines.indexOf(" BILLBOARD") === -1) {
  14026. defines += "\n#define BILLBOARD\n";
  14027. }
  14028. if (samplers.indexOf("diffuseSampler") === -1) {
  14029. samplers.push("diffuseSampler");
  14030. }
  14031. return this.createEffect({
  14032. vertex: "particles",
  14033. fragmentElement: fragmentName
  14034. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14035. };
  14036. /**
  14037. * Directly creates a webGL program
  14038. * @param vertexCode defines the vertex shader code to use
  14039. * @param fragmentCode defines the fragment shader code to use
  14040. * @param context defines the webGL context to use (if not set, the current one will be used)
  14041. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14042. * @returns the new webGL program
  14043. */
  14044. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14045. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14046. context = context || this._gl;
  14047. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14048. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14049. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14050. };
  14051. /**
  14052. * Creates a webGL program
  14053. * @param vertexCode defines the vertex shader code to use
  14054. * @param fragmentCode defines the fragment shader code to use
  14055. * @param defines defines the string containing the defines to use to compile the shaders
  14056. * @param context defines the webGL context to use (if not set, the current one will be used)
  14057. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14058. * @returns the new webGL program
  14059. */
  14060. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14061. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14062. context = context || this._gl;
  14063. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14064. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14065. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14066. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14067. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14068. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14069. return program;
  14070. };
  14071. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14072. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14073. var shaderProgram = context.createProgram();
  14074. if (!shaderProgram) {
  14075. throw new Error("Unable to create program");
  14076. }
  14077. context.attachShader(shaderProgram, vertexShader);
  14078. context.attachShader(shaderProgram, fragmentShader);
  14079. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14080. var transformFeedback = this.createTransformFeedback();
  14081. this.bindTransformFeedback(transformFeedback);
  14082. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14083. shaderProgram.transformFeedback = transformFeedback;
  14084. }
  14085. context.linkProgram(shaderProgram);
  14086. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14087. this.bindTransformFeedback(null);
  14088. }
  14089. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14090. if (!linked) {
  14091. context.validateProgram(shaderProgram);
  14092. var error = context.getProgramInfoLog(shaderProgram);
  14093. if (error) {
  14094. throw new Error(error);
  14095. }
  14096. }
  14097. context.deleteShader(vertexShader);
  14098. context.deleteShader(fragmentShader);
  14099. return shaderProgram;
  14100. };
  14101. /**
  14102. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14103. * @param shaderProgram defines the webGL program to use
  14104. * @param uniformsNames defines the list of uniform names
  14105. * @returns an array of webGL uniform locations
  14106. */
  14107. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14108. var results = new Array();
  14109. for (var index = 0; index < uniformsNames.length; index++) {
  14110. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14111. }
  14112. return results;
  14113. };
  14114. /**
  14115. * Gets the lsit of active attributes for a given webGL program
  14116. * @param shaderProgram defines the webGL program to use
  14117. * @param attributesNames defines the list of attribute names to get
  14118. * @returns an array of indices indicating the offset of each attribute
  14119. */
  14120. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14121. var results = [];
  14122. for (var index = 0; index < attributesNames.length; index++) {
  14123. try {
  14124. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14125. }
  14126. catch (e) {
  14127. results.push(-1);
  14128. }
  14129. }
  14130. return results;
  14131. };
  14132. /**
  14133. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14134. * @param effect defines the effect to activate
  14135. */
  14136. Engine.prototype.enableEffect = function (effect) {
  14137. if (!effect) {
  14138. return;
  14139. }
  14140. // Use program
  14141. this.bindSamplers(effect);
  14142. this._currentEffect = effect;
  14143. if (effect.onBind) {
  14144. effect.onBind(effect);
  14145. }
  14146. effect.onBindObservable.notifyObservers(effect);
  14147. };
  14148. /**
  14149. * Set the value of an uniform to an array of int32
  14150. * @param uniform defines the webGL uniform location where to store the value
  14151. * @param array defines the array of int32 to store
  14152. */
  14153. Engine.prototype.setIntArray = function (uniform, array) {
  14154. if (!uniform)
  14155. return;
  14156. this._gl.uniform1iv(uniform, array);
  14157. };
  14158. /**
  14159. * Set the value of an uniform to an array of int32 (stored as vec2)
  14160. * @param uniform defines the webGL uniform location where to store the value
  14161. * @param array defines the array of int32 to store
  14162. */
  14163. Engine.prototype.setIntArray2 = function (uniform, array) {
  14164. if (!uniform || array.length % 2 !== 0)
  14165. return;
  14166. this._gl.uniform2iv(uniform, array);
  14167. };
  14168. /**
  14169. * Set the value of an uniform to an array of int32 (stored as vec3)
  14170. * @param uniform defines the webGL uniform location where to store the value
  14171. * @param array defines the array of int32 to store
  14172. */
  14173. Engine.prototype.setIntArray3 = function (uniform, array) {
  14174. if (!uniform || array.length % 3 !== 0)
  14175. return;
  14176. this._gl.uniform3iv(uniform, array);
  14177. };
  14178. /**
  14179. * Set the value of an uniform to an array of int32 (stored as vec4)
  14180. * @param uniform defines the webGL uniform location where to store the value
  14181. * @param array defines the array of int32 to store
  14182. */
  14183. Engine.prototype.setIntArray4 = function (uniform, array) {
  14184. if (!uniform || array.length % 4 !== 0)
  14185. return;
  14186. this._gl.uniform4iv(uniform, array);
  14187. };
  14188. /**
  14189. * Set the value of an uniform to an array of float32
  14190. * @param uniform defines the webGL uniform location where to store the value
  14191. * @param array defines the array of float32 to store
  14192. */
  14193. Engine.prototype.setFloatArray = function (uniform, array) {
  14194. if (!uniform)
  14195. return;
  14196. this._gl.uniform1fv(uniform, array);
  14197. };
  14198. /**
  14199. * Set the value of an uniform to an array of float32 (stored as vec2)
  14200. * @param uniform defines the webGL uniform location where to store the value
  14201. * @param array defines the array of float32 to store
  14202. */
  14203. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14204. if (!uniform || array.length % 2 !== 0)
  14205. return;
  14206. this._gl.uniform2fv(uniform, array);
  14207. };
  14208. /**
  14209. * Set the value of an uniform to an array of float32 (stored as vec3)
  14210. * @param uniform defines the webGL uniform location where to store the value
  14211. * @param array defines the array of float32 to store
  14212. */
  14213. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14214. if (!uniform || array.length % 3 !== 0)
  14215. return;
  14216. this._gl.uniform3fv(uniform, array);
  14217. };
  14218. /**
  14219. * Set the value of an uniform to an array of float32 (stored as vec4)
  14220. * @param uniform defines the webGL uniform location where to store the value
  14221. * @param array defines the array of float32 to store
  14222. */
  14223. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14224. if (!uniform || array.length % 4 !== 0)
  14225. return;
  14226. this._gl.uniform4fv(uniform, array);
  14227. };
  14228. /**
  14229. * Set the value of an uniform to an array of number
  14230. * @param uniform defines the webGL uniform location where to store the value
  14231. * @param array defines the array of number to store
  14232. */
  14233. Engine.prototype.setArray = function (uniform, array) {
  14234. if (!uniform)
  14235. return;
  14236. this._gl.uniform1fv(uniform, array);
  14237. };
  14238. /**
  14239. * Set the value of an uniform to an array of number (stored as vec2)
  14240. * @param uniform defines the webGL uniform location where to store the value
  14241. * @param array defines the array of number to store
  14242. */
  14243. Engine.prototype.setArray2 = function (uniform, array) {
  14244. if (!uniform || array.length % 2 !== 0)
  14245. return;
  14246. this._gl.uniform2fv(uniform, array);
  14247. };
  14248. /**
  14249. * Set the value of an uniform to an array of number (stored as vec3)
  14250. * @param uniform defines the webGL uniform location where to store the value
  14251. * @param array defines the array of number to store
  14252. */
  14253. Engine.prototype.setArray3 = function (uniform, array) {
  14254. if (!uniform || array.length % 3 !== 0)
  14255. return;
  14256. this._gl.uniform3fv(uniform, array);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to an array of number (stored as vec4)
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param array defines the array of number to store
  14262. */
  14263. Engine.prototype.setArray4 = function (uniform, array) {
  14264. if (!uniform || array.length % 4 !== 0)
  14265. return;
  14266. this._gl.uniform4fv(uniform, array);
  14267. };
  14268. /**
  14269. * Set the value of an uniform to an array of float32 (stored as matrices)
  14270. * @param uniform defines the webGL uniform location where to store the value
  14271. * @param matrices defines the array of float32 to store
  14272. */
  14273. Engine.prototype.setMatrices = function (uniform, matrices) {
  14274. if (!uniform)
  14275. return;
  14276. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14277. };
  14278. /**
  14279. * Set the value of an uniform to a matrix
  14280. * @param uniform defines the webGL uniform location where to store the value
  14281. * @param matrix defines the matrix to store
  14282. */
  14283. Engine.prototype.setMatrix = function (uniform, matrix) {
  14284. if (!uniform)
  14285. return;
  14286. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14287. };
  14288. /**
  14289. * Set the value of an uniform to a matrix (3x3)
  14290. * @param uniform defines the webGL uniform location where to store the value
  14291. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14292. */
  14293. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14294. if (!uniform)
  14295. return;
  14296. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14297. };
  14298. /**
  14299. * Set the value of an uniform to a matrix (2x2)
  14300. * @param uniform defines the webGL uniform location where to store the value
  14301. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14302. */
  14303. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14304. if (!uniform)
  14305. return;
  14306. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14307. };
  14308. /**
  14309. * Set the value of an uniform to a number (int)
  14310. * @param uniform defines the webGL uniform location where to store the value
  14311. * @param value defines the int number to store
  14312. */
  14313. Engine.prototype.setInt = function (uniform, value) {
  14314. if (!uniform)
  14315. return;
  14316. this._gl.uniform1i(uniform, value);
  14317. };
  14318. /**
  14319. * Set the value of an uniform to a number (float)
  14320. * @param uniform defines the webGL uniform location where to store the value
  14321. * @param value defines the float number to store
  14322. */
  14323. Engine.prototype.setFloat = function (uniform, value) {
  14324. if (!uniform)
  14325. return;
  14326. this._gl.uniform1f(uniform, value);
  14327. };
  14328. /**
  14329. * Set the value of an uniform to a vec2
  14330. * @param uniform defines the webGL uniform location where to store the value
  14331. * @param x defines the 1st component of the value
  14332. * @param y defines the 2nd component of the value
  14333. */
  14334. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14335. if (!uniform)
  14336. return;
  14337. this._gl.uniform2f(uniform, x, y);
  14338. };
  14339. /**
  14340. * Set the value of an uniform to a vec3
  14341. * @param uniform defines the webGL uniform location where to store the value
  14342. * @param x defines the 1st component of the value
  14343. * @param y defines the 2nd component of the value
  14344. * @param z defines the 3rd component of the value
  14345. */
  14346. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14347. if (!uniform)
  14348. return;
  14349. this._gl.uniform3f(uniform, x, y, z);
  14350. };
  14351. /**
  14352. * Set the value of an uniform to a boolean
  14353. * @param uniform defines the webGL uniform location where to store the value
  14354. * @param bool defines the boolean to store
  14355. */
  14356. Engine.prototype.setBool = function (uniform, bool) {
  14357. if (!uniform)
  14358. return;
  14359. this._gl.uniform1i(uniform, bool);
  14360. };
  14361. /**
  14362. * Set the value of an uniform to a vec4
  14363. * @param uniform defines the webGL uniform location where to store the value
  14364. * @param x defines the 1st component of the value
  14365. * @param y defines the 2nd component of the value
  14366. * @param z defines the 3rd component of the value
  14367. * @param w defines the 4th component of the value
  14368. */
  14369. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14370. if (!uniform)
  14371. return;
  14372. this._gl.uniform4f(uniform, x, y, z, w);
  14373. };
  14374. /**
  14375. * Set the value of an uniform to a Color3
  14376. * @param uniform defines the webGL uniform location where to store the value
  14377. * @param color3 defines the color to store
  14378. */
  14379. Engine.prototype.setColor3 = function (uniform, color3) {
  14380. if (!uniform)
  14381. return;
  14382. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14383. };
  14384. /**
  14385. * Set the value of an uniform to a Color3 and an alpha value
  14386. * @param uniform defines the webGL uniform location where to store the value
  14387. * @param color3 defines the color to store
  14388. * @param alpha defines the alpha component to store
  14389. */
  14390. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14391. if (!uniform)
  14392. return;
  14393. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14394. };
  14395. /**
  14396. * Sets a Color4 on a uniform variable
  14397. * @param uniform defines the uniform location
  14398. * @param color4 defines the value to be set
  14399. */
  14400. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14401. if (!uniform)
  14402. return;
  14403. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14404. };
  14405. // States
  14406. /**
  14407. * Set various states to the webGL context
  14408. * @param culling defines backface culling state
  14409. * @param zOffset defines the value to apply to zOffset (0 by default)
  14410. * @param force defines if states must be applied even if cache is up to date
  14411. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14412. */
  14413. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14414. if (zOffset === void 0) { zOffset = 0; }
  14415. if (reverseSide === void 0) { reverseSide = false; }
  14416. // Culling
  14417. if (this._depthCullingState.cull !== culling || force) {
  14418. this._depthCullingState.cull = culling;
  14419. }
  14420. // Cull face
  14421. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14422. if (this._depthCullingState.cullFace !== cullFace || force) {
  14423. this._depthCullingState.cullFace = cullFace;
  14424. }
  14425. // Z offset
  14426. this.setZOffset(zOffset);
  14427. // Front face
  14428. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14429. if (this._depthCullingState.frontFace !== frontFace || force) {
  14430. this._depthCullingState.frontFace = frontFace;
  14431. }
  14432. };
  14433. /**
  14434. * Set the z offset to apply to current rendering
  14435. * @param value defines the offset to apply
  14436. */
  14437. Engine.prototype.setZOffset = function (value) {
  14438. this._depthCullingState.zOffset = value;
  14439. };
  14440. /**
  14441. * Gets the current value of the zOffset
  14442. * @returns the current zOffset state
  14443. */
  14444. Engine.prototype.getZOffset = function () {
  14445. return this._depthCullingState.zOffset;
  14446. };
  14447. /**
  14448. * Enable or disable depth buffering
  14449. * @param enable defines the state to set
  14450. */
  14451. Engine.prototype.setDepthBuffer = function (enable) {
  14452. this._depthCullingState.depthTest = enable;
  14453. };
  14454. /**
  14455. * Gets a boolean indicating if depth writing is enabled
  14456. * @returns the current depth writing state
  14457. */
  14458. Engine.prototype.getDepthWrite = function () {
  14459. return this._depthCullingState.depthMask;
  14460. };
  14461. /**
  14462. * Enable or disable depth writing
  14463. * @param enable defines the state to set
  14464. */
  14465. Engine.prototype.setDepthWrite = function (enable) {
  14466. this._depthCullingState.depthMask = enable;
  14467. };
  14468. /**
  14469. * Enable or disable color writing
  14470. * @param enable defines the state to set
  14471. */
  14472. Engine.prototype.setColorWrite = function (enable) {
  14473. this._gl.colorMask(enable, enable, enable, enable);
  14474. this._colorWrite = enable;
  14475. };
  14476. /**
  14477. * Gets a boolean indicating if color writing is enabled
  14478. * @returns the current color writing state
  14479. */
  14480. Engine.prototype.getColorWrite = function () {
  14481. return this._colorWrite;
  14482. };
  14483. /**
  14484. * Sets alpha constants used by some alpha blending modes
  14485. * @param r defines the red component
  14486. * @param g defines the green component
  14487. * @param b defines the blue component
  14488. * @param a defines the alpha component
  14489. */
  14490. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14491. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14492. };
  14493. /**
  14494. * Sets the current alpha mode
  14495. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14496. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14497. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14498. */
  14499. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14500. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14501. if (this._alphaMode === mode) {
  14502. return;
  14503. }
  14504. switch (mode) {
  14505. case Engine.ALPHA_DISABLE:
  14506. this._alphaState.alphaBlend = false;
  14507. break;
  14508. case Engine.ALPHA_PREMULTIPLIED:
  14509. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14510. this._alphaState.alphaBlend = true;
  14511. break;
  14512. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14513. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14514. this._alphaState.alphaBlend = true;
  14515. break;
  14516. case Engine.ALPHA_COMBINE:
  14517. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14518. this._alphaState.alphaBlend = true;
  14519. break;
  14520. case Engine.ALPHA_ONEONE:
  14521. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14522. this._alphaState.alphaBlend = true;
  14523. break;
  14524. case Engine.ALPHA_ADD:
  14525. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14526. this._alphaState.alphaBlend = true;
  14527. break;
  14528. case Engine.ALPHA_SUBTRACT:
  14529. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14530. this._alphaState.alphaBlend = true;
  14531. break;
  14532. case Engine.ALPHA_MULTIPLY:
  14533. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14534. this._alphaState.alphaBlend = true;
  14535. break;
  14536. case Engine.ALPHA_MAXIMIZED:
  14537. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14538. this._alphaState.alphaBlend = true;
  14539. break;
  14540. case Engine.ALPHA_INTERPOLATE:
  14541. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14542. this._alphaState.alphaBlend = true;
  14543. break;
  14544. case Engine.ALPHA_SCREENMODE:
  14545. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14546. this._alphaState.alphaBlend = true;
  14547. break;
  14548. }
  14549. if (!noDepthWriteChange) {
  14550. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14551. }
  14552. this._alphaMode = mode;
  14553. };
  14554. /**
  14555. * Gets the current alpha mode
  14556. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14557. * @returns the current alpha mode
  14558. */
  14559. Engine.prototype.getAlphaMode = function () {
  14560. return this._alphaMode;
  14561. };
  14562. // Textures
  14563. /**
  14564. * Clears the list of texture accessible through engine.
  14565. * This can help preventing texture load conflict due to name collision.
  14566. */
  14567. Engine.prototype.clearInternalTexturesCache = function () {
  14568. this._internalTexturesCache = [];
  14569. };
  14570. /**
  14571. * Force the entire cache to be cleared
  14572. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14573. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14574. */
  14575. Engine.prototype.wipeCaches = function (bruteForce) {
  14576. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14577. return;
  14578. }
  14579. this._currentEffect = null;
  14580. this._unpackFlipYCached = null;
  14581. this._viewportCached.x = 0;
  14582. this._viewportCached.y = 0;
  14583. this._viewportCached.z = 0;
  14584. this._viewportCached.w = 0;
  14585. if (bruteForce) {
  14586. this.resetTextureCache();
  14587. this._currentProgram = null;
  14588. this._stencilState.reset();
  14589. this._depthCullingState.reset();
  14590. this.setDepthFunctionToLessOrEqual();
  14591. this._alphaState.reset();
  14592. }
  14593. this._resetVertexBufferBinding();
  14594. this._cachedIndexBuffer = null;
  14595. this._cachedEffectForVertexBuffers = null;
  14596. this._unbindVertexArrayObject();
  14597. this.bindIndexBuffer(null);
  14598. };
  14599. /**
  14600. * Set the compressed texture format to use, based on the formats you have, and the formats
  14601. * supported by the hardware / browser.
  14602. *
  14603. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14604. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14605. * to API arguments needed to compressed textures. This puts the burden on the container
  14606. * generator to house the arcane code for determining these for current & future formats.
  14607. *
  14608. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14609. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14610. *
  14611. * Note: The result of this call is not taken into account when a texture is base64.
  14612. *
  14613. * @param formatsAvailable defines the list of those format families you have created
  14614. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14615. *
  14616. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14617. * @returns The extension selected.
  14618. */
  14619. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14620. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14621. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14622. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14623. return this._textureFormatInUse = this._texturesSupported[i];
  14624. }
  14625. }
  14626. }
  14627. // actively set format to nothing, to allow this to be called more than once
  14628. // and possibly fail the 2nd time
  14629. this._textureFormatInUse = null;
  14630. return null;
  14631. };
  14632. /** @hidden */
  14633. Engine.prototype._createTexture = function () {
  14634. var texture = this._gl.createTexture();
  14635. if (!texture) {
  14636. throw new Error("Unable to create texture");
  14637. }
  14638. return texture;
  14639. };
  14640. /**
  14641. * Usually called from BABYLON.Texture.ts.
  14642. * Passed information to create a WebGLTexture
  14643. * @param urlArg defines a value which contains one of the following:
  14644. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14645. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14646. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14647. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14648. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14649. * @param scene needed for loading to the correct scene
  14650. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14651. * @param onLoad optional callback to be called upon successful completion
  14652. * @param onError optional callback to be called upon failure
  14653. * @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
  14654. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14655. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14656. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14657. */
  14658. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14659. var _this = this;
  14660. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14661. if (onLoad === void 0) { onLoad = null; }
  14662. if (onError === void 0) { onError = null; }
  14663. if (buffer === void 0) { buffer = null; }
  14664. if (fallback === void 0) { fallback = null; }
  14665. if (format === void 0) { format = null; }
  14666. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14667. var fromData = url.substr(0, 5) === "data:";
  14668. var fromBlob = url.substr(0, 5) === "blob:";
  14669. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14670. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14671. // establish the file extension, if possible
  14672. var lastDot = url.lastIndexOf('.');
  14673. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14674. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14675. var isTGA = (extension.indexOf(".tga") === 0);
  14676. // determine if a ktx file should be substituted
  14677. var isKTX = false;
  14678. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14679. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14680. isKTX = true;
  14681. }
  14682. if (scene) {
  14683. scene._addPendingData(texture);
  14684. }
  14685. texture.url = url;
  14686. texture.generateMipMaps = !noMipmap;
  14687. texture.samplingMode = samplingMode;
  14688. texture.invertY = invertY;
  14689. if (!this._doNotHandleContextLost) {
  14690. // Keep a link to the buffer only if we plan to handle context lost
  14691. texture._buffer = buffer;
  14692. }
  14693. var onLoadObserver = null;
  14694. if (onLoad && !fallback) {
  14695. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14696. }
  14697. if (!fallback)
  14698. this._internalTexturesCache.push(texture);
  14699. var onerror = function (message, exception) {
  14700. if (scene) {
  14701. scene._removePendingData(texture);
  14702. }
  14703. if (onLoadObserver && !isKTX) {
  14704. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14705. texture.onLoadedObservable.remove(onLoadObserver);
  14706. }
  14707. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14708. if (isKTX) {
  14709. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14710. }
  14711. else if (BABYLON.Tools.UseFallbackTexture) {
  14712. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14713. }
  14714. if (onError) {
  14715. onError(message || "Unknown error", exception);
  14716. }
  14717. };
  14718. var callback = null;
  14719. // processing for non-image formats
  14720. if (isKTX || isTGA || isDDS) {
  14721. if (isKTX) {
  14722. callback = function (data) {
  14723. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14724. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14725. ktx.uploadLevels(_this._gl, !noMipmap);
  14726. return false;
  14727. }, samplingMode);
  14728. };
  14729. }
  14730. else if (isTGA) {
  14731. callback = function (arrayBuffer) {
  14732. var data = new Uint8Array(arrayBuffer);
  14733. var header = BABYLON.TGATools.GetTGAHeader(data);
  14734. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14735. BABYLON.TGATools.UploadContent(_this._gl, data);
  14736. return false;
  14737. }, samplingMode);
  14738. };
  14739. }
  14740. else if (isDDS) {
  14741. callback = function (data) {
  14742. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14743. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14744. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14745. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14746. return false;
  14747. }, samplingMode);
  14748. };
  14749. }
  14750. if (!buffer) {
  14751. this._loadFile(url, function (data) {
  14752. if (callback) {
  14753. callback(data);
  14754. }
  14755. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14756. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14757. });
  14758. }
  14759. else {
  14760. if (callback) {
  14761. callback(buffer);
  14762. }
  14763. }
  14764. // image format processing
  14765. }
  14766. else {
  14767. var onload = function (img) {
  14768. if (fromBlob && !_this._doNotHandleContextLost) {
  14769. // We need to store the image if we need to rebuild the texture
  14770. // in case of a webgl context lost
  14771. texture._buffer = img;
  14772. }
  14773. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14774. var gl = _this._gl;
  14775. var isPot = (img.width === potWidth && img.height === potHeight);
  14776. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14777. if (isPot) {
  14778. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14779. return false;
  14780. }
  14781. var maxTextureSize = _this._caps.maxTextureSize;
  14782. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14783. _this._prepareWorkingCanvas();
  14784. if (!_this._workingCanvas || !_this._workingContext) {
  14785. return false;
  14786. }
  14787. _this._workingCanvas.width = potWidth;
  14788. _this._workingCanvas.height = potHeight;
  14789. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14790. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14791. texture.width = potWidth;
  14792. texture.height = potHeight;
  14793. return false;
  14794. }
  14795. else {
  14796. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14797. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14798. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14799. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14801. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14802. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14803. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14804. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14805. _this._releaseTexture(source_1);
  14806. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14807. continuationCallback();
  14808. });
  14809. }
  14810. return true;
  14811. }, samplingMode);
  14812. };
  14813. if (!fromData || isBase64) {
  14814. if (buffer instanceof HTMLImageElement) {
  14815. onload(buffer);
  14816. }
  14817. else {
  14818. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14819. }
  14820. }
  14821. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14822. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14823. }
  14824. else {
  14825. onload(buffer);
  14826. }
  14827. }
  14828. return texture;
  14829. };
  14830. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14831. var _this = this;
  14832. var rtt = this.createRenderTargetTexture({
  14833. width: destination.width,
  14834. height: destination.height,
  14835. }, {
  14836. generateMipMaps: false,
  14837. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14838. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14839. generateDepthBuffer: false,
  14840. generateStencilBuffer: false
  14841. });
  14842. if (!this._rescalePostProcess) {
  14843. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14844. }
  14845. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14846. _this._rescalePostProcess.onApply = function (effect) {
  14847. effect._bindTexture("textureSampler", source);
  14848. };
  14849. var hostingScene = scene;
  14850. if (!hostingScene) {
  14851. hostingScene = _this.scenes[_this.scenes.length - 1];
  14852. }
  14853. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14854. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14855. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14856. _this.unBindFramebuffer(rtt);
  14857. _this._releaseTexture(rtt);
  14858. if (onComplete) {
  14859. onComplete();
  14860. }
  14861. });
  14862. };
  14863. /**
  14864. * Update a raw texture
  14865. * @param texture defines the texture to update
  14866. * @param data defines the data to store in the texture
  14867. * @param format defines the format of the data
  14868. * @param invertY defines if data must be stored with Y axis inverted
  14869. * @param compression defines the compression used (null by default)
  14870. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14871. */
  14872. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14873. if (compression === void 0) { compression = null; }
  14874. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14875. if (!texture) {
  14876. return;
  14877. }
  14878. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14879. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14880. // babylon's internalFormat but gl's texImage2D format
  14881. var internalFormat = this._getInternalFormat(format);
  14882. var textureType = this._getWebGLTextureType(type);
  14883. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14884. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  14885. if (!this._doNotHandleContextLost) {
  14886. texture._bufferView = data;
  14887. texture.format = format;
  14888. texture.type = type;
  14889. texture.invertY = invertY;
  14890. texture._compression = compression;
  14891. }
  14892. if (texture.width % 4 !== 0) {
  14893. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14894. }
  14895. if (compression && data) {
  14896. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14897. }
  14898. else {
  14899. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14900. }
  14901. if (texture.generateMipMaps) {
  14902. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14903. }
  14904. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14905. // this.resetTextureCache();
  14906. texture.isReady = true;
  14907. };
  14908. /**
  14909. * Creates a raw texture
  14910. * @param data defines the data to store in the texture
  14911. * @param width defines the width of the texture
  14912. * @param height defines the height of the texture
  14913. * @param format defines the format of the data
  14914. * @param generateMipMaps defines if the engine should generate the mip levels
  14915. * @param invertY defines if data must be stored with Y axis inverted
  14916. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14917. * @param compression defines the compression used (null by default)
  14918. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14919. * @returns the raw texture inside an InternalTexture
  14920. */
  14921. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14922. if (compression === void 0) { compression = null; }
  14923. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14924. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14925. texture.baseWidth = width;
  14926. texture.baseHeight = height;
  14927. texture.width = width;
  14928. texture.height = height;
  14929. texture.format = format;
  14930. texture.generateMipMaps = generateMipMaps;
  14931. texture.samplingMode = samplingMode;
  14932. texture.invertY = invertY;
  14933. texture._compression = compression;
  14934. texture.type = type;
  14935. if (!this._doNotHandleContextLost) {
  14936. texture._bufferView = data;
  14937. }
  14938. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14939. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14940. // Filters
  14941. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14942. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14943. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14944. if (generateMipMaps) {
  14945. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14946. }
  14947. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14948. this._internalTexturesCache.push(texture);
  14949. return texture;
  14950. };
  14951. /** @hidden */
  14952. Engine.prototype._unpackFlipY = function (value) {
  14953. if (this._unpackFlipYCached !== value) {
  14954. this._unpackFlipYCached = value;
  14955. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  14956. }
  14957. };
  14958. /**
  14959. * Creates a dynamic texture
  14960. * @param width defines the width of the texture
  14961. * @param height defines the height of the texture
  14962. * @param generateMipMaps defines if the engine should generate the mip levels
  14963. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14964. * @returns the dynamic texture inside an InternalTexture
  14965. */
  14966. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14967. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14968. texture.baseWidth = width;
  14969. texture.baseHeight = height;
  14970. if (generateMipMaps) {
  14971. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14972. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14973. }
  14974. // this.resetTextureCache();
  14975. texture.width = width;
  14976. texture.height = height;
  14977. texture.isReady = false;
  14978. texture.generateMipMaps = generateMipMaps;
  14979. texture.samplingMode = samplingMode;
  14980. this.updateTextureSamplingMode(samplingMode, texture);
  14981. this._internalTexturesCache.push(texture);
  14982. return texture;
  14983. };
  14984. /**
  14985. * Update the sampling mode of a given texture
  14986. * @param samplingMode defines the required sampling mode
  14987. * @param texture defines the texture to update
  14988. */
  14989. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14990. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14991. if (texture.isCube) {
  14992. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14993. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14994. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14995. }
  14996. else if (texture.is3D) {
  14997. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14998. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14999. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15000. }
  15001. else {
  15002. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15003. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15004. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15005. }
  15006. texture.samplingMode = samplingMode;
  15007. };
  15008. /**
  15009. * Update the content of a dynamic texture
  15010. * @param texture defines the texture to update
  15011. * @param canvas defines the canvas containing the source
  15012. * @param invertY defines if data must be stored with Y axis inverted
  15013. * @param premulAlpha defines if alpha is stored as premultiplied
  15014. * @param format defines the format of the data
  15015. */
  15016. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15017. if (premulAlpha === void 0) { premulAlpha = false; }
  15018. if (!texture) {
  15019. return;
  15020. }
  15021. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15022. this._unpackFlipY(invertY);
  15023. if (premulAlpha) {
  15024. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15025. }
  15026. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15027. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15028. if (texture.generateMipMaps) {
  15029. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15030. }
  15031. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15032. if (premulAlpha) {
  15033. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15034. }
  15035. texture.isReady = true;
  15036. };
  15037. /**
  15038. * Update a video texture
  15039. * @param texture defines the texture to update
  15040. * @param video defines the video element to use
  15041. * @param invertY defines if data must be stored with Y axis inverted
  15042. */
  15043. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15044. if (!texture || texture._isDisabled) {
  15045. return;
  15046. }
  15047. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15048. this._unpackFlipY(!invertY); // Video are upside down by default
  15049. try {
  15050. // Testing video texture support
  15051. if (this._videoTextureSupported === undefined) {
  15052. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15053. if (this._gl.getError() !== 0) {
  15054. this._videoTextureSupported = false;
  15055. }
  15056. else {
  15057. this._videoTextureSupported = true;
  15058. }
  15059. }
  15060. // Copy video through the current working canvas if video texture is not supported
  15061. if (!this._videoTextureSupported) {
  15062. if (!texture._workingCanvas) {
  15063. texture._workingCanvas = document.createElement("canvas");
  15064. var context = texture._workingCanvas.getContext("2d");
  15065. if (!context) {
  15066. throw new Error("Unable to get 2d context");
  15067. }
  15068. texture._workingContext = context;
  15069. texture._workingCanvas.width = texture.width;
  15070. texture._workingCanvas.height = texture.height;
  15071. }
  15072. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15073. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15074. }
  15075. else {
  15076. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15077. }
  15078. if (texture.generateMipMaps) {
  15079. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15080. }
  15081. if (!wasPreviouslyBound) {
  15082. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15083. }
  15084. // this.resetTextureCache();
  15085. texture.isReady = true;
  15086. }
  15087. catch (ex) {
  15088. // Something unexpected
  15089. // Let's disable the texture
  15090. texture._isDisabled = true;
  15091. }
  15092. };
  15093. /**
  15094. * Updates a depth texture Comparison Mode and Function.
  15095. * If the comparison Function is equal to 0, the mode will be set to none.
  15096. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15097. * @param texture The texture to set the comparison function for
  15098. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15099. */
  15100. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15101. if (this.webGLVersion === 1) {
  15102. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15103. return;
  15104. }
  15105. var gl = this._gl;
  15106. if (texture.isCube) {
  15107. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15108. if (comparisonFunction === 0) {
  15109. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15110. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15111. }
  15112. else {
  15113. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15114. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15115. }
  15116. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15117. }
  15118. else {
  15119. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15120. if (comparisonFunction === 0) {
  15121. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15123. }
  15124. else {
  15125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15127. }
  15128. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15129. }
  15130. texture._comparisonFunction = comparisonFunction;
  15131. };
  15132. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15133. var width = size.width || size;
  15134. var height = size.height || size;
  15135. internalTexture.baseWidth = width;
  15136. internalTexture.baseHeight = height;
  15137. internalTexture.width = width;
  15138. internalTexture.height = height;
  15139. internalTexture.isReady = true;
  15140. internalTexture.samples = 1;
  15141. internalTexture.generateMipMaps = false;
  15142. internalTexture._generateDepthBuffer = true;
  15143. internalTexture._generateStencilBuffer = generateStencil;
  15144. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15145. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15146. internalTexture._comparisonFunction = comparisonFunction;
  15147. var gl = this._gl;
  15148. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15149. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15150. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15151. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15152. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15153. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15154. if (comparisonFunction === 0) {
  15155. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15156. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15157. }
  15158. else {
  15159. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15160. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15161. }
  15162. };
  15163. /**
  15164. * Creates a depth stencil texture.
  15165. * This is only available in WebGL 2 or with the depth texture extension available.
  15166. * @param size The size of face edge in the texture.
  15167. * @param options The options defining the texture.
  15168. * @returns The texture
  15169. */
  15170. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15171. if (options.isCube) {
  15172. var width = size.width || size;
  15173. return this._createDepthStencilCubeTexture(width, options);
  15174. }
  15175. else {
  15176. return this._createDepthStencilTexture(size, options);
  15177. }
  15178. };
  15179. /**
  15180. * Creates a depth stencil texture.
  15181. * This is only available in WebGL 2 or with the depth texture extension available.
  15182. * @param size The size of face edge in the texture.
  15183. * @param options The options defining the texture.
  15184. * @returns The texture
  15185. */
  15186. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15187. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15188. if (!this._caps.depthTextureExtension) {
  15189. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15190. return internalTexture;
  15191. }
  15192. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15193. var gl = this._gl;
  15194. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15195. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15196. if (this.webGLVersion > 1) {
  15197. if (internalOptions.generateStencil) {
  15198. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15199. }
  15200. else {
  15201. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15202. }
  15203. }
  15204. else {
  15205. if (internalOptions.generateStencil) {
  15206. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15207. }
  15208. else {
  15209. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15210. }
  15211. }
  15212. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15213. return internalTexture;
  15214. };
  15215. /**
  15216. * Creates a depth stencil cube texture.
  15217. * This is only available in WebGL 2.
  15218. * @param size The size of face edge in the cube texture.
  15219. * @param options The options defining the cube texture.
  15220. * @returns The cube texture
  15221. */
  15222. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15223. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15224. internalTexture.isCube = true;
  15225. if (this.webGLVersion === 1) {
  15226. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15227. return internalTexture;
  15228. }
  15229. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15230. var gl = this._gl;
  15231. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15232. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15233. // Create the depth/stencil buffer
  15234. for (var face = 0; face < 6; face++) {
  15235. if (internalOptions.generateStencil) {
  15236. 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);
  15237. }
  15238. else {
  15239. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15240. }
  15241. }
  15242. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15243. return internalTexture;
  15244. };
  15245. /**
  15246. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15247. * @param renderTarget The render target to set the frame buffer for
  15248. */
  15249. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15250. // Create the framebuffer
  15251. var internalTexture = renderTarget.getInternalTexture();
  15252. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15253. return;
  15254. }
  15255. var gl = this._gl;
  15256. var depthStencilTexture = renderTarget.depthStencilTexture;
  15257. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15258. if (depthStencilTexture.isCube) {
  15259. if (depthStencilTexture._generateStencilBuffer) {
  15260. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15261. }
  15262. else {
  15263. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15264. }
  15265. }
  15266. else {
  15267. if (depthStencilTexture._generateStencilBuffer) {
  15268. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15269. }
  15270. else {
  15271. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15272. }
  15273. }
  15274. this.bindUnboundFramebuffer(null);
  15275. };
  15276. /**
  15277. * Creates a new render target texture
  15278. * @param size defines the size of the texture
  15279. * @param options defines the options used to create the texture
  15280. * @returns a new render target texture stored in an InternalTexture
  15281. */
  15282. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15283. var fullOptions = new RenderTargetCreationOptions();
  15284. if (options !== undefined && typeof options === "object") {
  15285. fullOptions.generateMipMaps = options.generateMipMaps;
  15286. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15287. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15288. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15289. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15290. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15291. }
  15292. else {
  15293. fullOptions.generateMipMaps = options;
  15294. fullOptions.generateDepthBuffer = true;
  15295. fullOptions.generateStencilBuffer = false;
  15296. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15297. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15298. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15299. }
  15300. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15301. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15302. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15303. }
  15304. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15305. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15306. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15307. }
  15308. var gl = this._gl;
  15309. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15310. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15311. var width = size.width || size;
  15312. var height = size.height || size;
  15313. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15314. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15315. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15316. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15317. }
  15318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15320. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15321. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15322. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15323. // Create the framebuffer
  15324. var currentFrameBuffer = this._currentFramebuffer;
  15325. var framebuffer = gl.createFramebuffer();
  15326. this.bindUnboundFramebuffer(framebuffer);
  15327. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15328. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15329. if (fullOptions.generateMipMaps) {
  15330. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15331. }
  15332. // Unbind
  15333. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15334. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15335. this.bindUnboundFramebuffer(currentFrameBuffer);
  15336. texture._framebuffer = framebuffer;
  15337. texture.baseWidth = width;
  15338. texture.baseHeight = height;
  15339. texture.width = width;
  15340. texture.height = height;
  15341. texture.isReady = true;
  15342. texture.samples = 1;
  15343. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15344. texture.samplingMode = fullOptions.samplingMode;
  15345. texture.type = fullOptions.type;
  15346. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15347. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15348. // this.resetTextureCache();
  15349. this._internalTexturesCache.push(texture);
  15350. return texture;
  15351. };
  15352. /**
  15353. * Create a multi render target texture
  15354. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15355. * @param size defines the size of the texture
  15356. * @param options defines the creation options
  15357. * @returns the cube texture as an InternalTexture
  15358. */
  15359. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15360. var generateMipMaps = false;
  15361. var generateDepthBuffer = true;
  15362. var generateStencilBuffer = false;
  15363. var generateDepthTexture = false;
  15364. var textureCount = 1;
  15365. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15366. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15367. var types = new Array();
  15368. var samplingModes = new Array();
  15369. if (options !== undefined) {
  15370. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15371. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15372. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15373. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15374. textureCount = options.textureCount || 1;
  15375. if (options.types) {
  15376. types = options.types;
  15377. }
  15378. if (options.samplingModes) {
  15379. samplingModes = options.samplingModes;
  15380. }
  15381. }
  15382. var gl = this._gl;
  15383. // Create the framebuffer
  15384. var framebuffer = gl.createFramebuffer();
  15385. this.bindUnboundFramebuffer(framebuffer);
  15386. var width = size.width || size;
  15387. var height = size.height || size;
  15388. var textures = [];
  15389. var attachments = [];
  15390. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15391. for (var i = 0; i < textureCount; i++) {
  15392. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15393. var type = types[i] || defaultType;
  15394. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15395. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15396. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15397. }
  15398. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15399. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15400. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15401. }
  15402. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15403. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15404. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15405. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15406. }
  15407. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15408. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15409. textures.push(texture);
  15410. attachments.push(attachment);
  15411. gl.activeTexture(gl["TEXTURE" + i]);
  15412. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15413. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15414. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15417. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15418. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15419. if (generateMipMaps) {
  15420. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15421. }
  15422. // Unbind
  15423. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15424. texture._framebuffer = framebuffer;
  15425. texture._depthStencilBuffer = depthStencilBuffer;
  15426. texture.baseWidth = width;
  15427. texture.baseHeight = height;
  15428. texture.width = width;
  15429. texture.height = height;
  15430. texture.isReady = true;
  15431. texture.samples = 1;
  15432. texture.generateMipMaps = generateMipMaps;
  15433. texture.samplingMode = samplingMode;
  15434. texture.type = type;
  15435. texture._generateDepthBuffer = generateDepthBuffer;
  15436. texture._generateStencilBuffer = generateStencilBuffer;
  15437. texture._attachments = attachments;
  15438. this._internalTexturesCache.push(texture);
  15439. }
  15440. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15441. // Depth texture
  15442. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15443. gl.activeTexture(gl.TEXTURE0);
  15444. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15445. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15446. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15447. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15448. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15449. 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);
  15450. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15451. depthTexture._framebuffer = framebuffer;
  15452. depthTexture.baseWidth = width;
  15453. depthTexture.baseHeight = height;
  15454. depthTexture.width = width;
  15455. depthTexture.height = height;
  15456. depthTexture.isReady = true;
  15457. depthTexture.samples = 1;
  15458. depthTexture.generateMipMaps = generateMipMaps;
  15459. depthTexture.samplingMode = gl.NEAREST;
  15460. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15461. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15462. textures.push(depthTexture);
  15463. this._internalTexturesCache.push(depthTexture);
  15464. }
  15465. gl.drawBuffers(attachments);
  15466. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15467. this.bindUnboundFramebuffer(null);
  15468. this.resetTextureCache();
  15469. return textures;
  15470. };
  15471. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15472. if (samples === void 0) { samples = 1; }
  15473. var depthStencilBuffer = null;
  15474. var gl = this._gl;
  15475. // Create the depth/stencil buffer
  15476. if (generateStencilBuffer) {
  15477. depthStencilBuffer = gl.createRenderbuffer();
  15478. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15479. if (samples > 1) {
  15480. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15481. }
  15482. else {
  15483. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15484. }
  15485. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15486. }
  15487. else if (generateDepthBuffer) {
  15488. depthStencilBuffer = gl.createRenderbuffer();
  15489. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15490. if (samples > 1) {
  15491. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15492. }
  15493. else {
  15494. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15495. }
  15496. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15497. }
  15498. return depthStencilBuffer;
  15499. };
  15500. /**
  15501. * Updates the sample count of a render target texture
  15502. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15503. * @param texture defines the texture to update
  15504. * @param samples defines the sample count to set
  15505. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15506. */
  15507. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15508. if (this.webGLVersion < 2 || !texture) {
  15509. return 1;
  15510. }
  15511. if (texture.samples === samples) {
  15512. return samples;
  15513. }
  15514. var gl = this._gl;
  15515. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15516. // Dispose previous render buffers
  15517. if (texture._depthStencilBuffer) {
  15518. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15519. texture._depthStencilBuffer = null;
  15520. }
  15521. if (texture._MSAAFramebuffer) {
  15522. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15523. texture._MSAAFramebuffer = null;
  15524. }
  15525. if (texture._MSAARenderBuffer) {
  15526. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15527. texture._MSAARenderBuffer = null;
  15528. }
  15529. if (samples > 1) {
  15530. var framebuffer = gl.createFramebuffer();
  15531. if (!framebuffer) {
  15532. throw new Error("Unable to create multi sampled framebuffer");
  15533. }
  15534. texture._MSAAFramebuffer = framebuffer;
  15535. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15536. var colorRenderbuffer = gl.createRenderbuffer();
  15537. if (!colorRenderbuffer) {
  15538. throw new Error("Unable to create multi sampled framebuffer");
  15539. }
  15540. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15541. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15542. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15543. texture._MSAARenderBuffer = colorRenderbuffer;
  15544. }
  15545. else {
  15546. this.bindUnboundFramebuffer(texture._framebuffer);
  15547. }
  15548. texture.samples = samples;
  15549. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15550. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15551. this.bindUnboundFramebuffer(null);
  15552. return samples;
  15553. };
  15554. /**
  15555. * Update the sample count for a given multiple render target texture
  15556. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15557. * @param textures defines the textures to update
  15558. * @param samples defines the sample count to set
  15559. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15560. */
  15561. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15562. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15563. return 1;
  15564. }
  15565. if (textures[0].samples === samples) {
  15566. return samples;
  15567. }
  15568. var gl = this._gl;
  15569. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15570. // Dispose previous render buffers
  15571. if (textures[0]._depthStencilBuffer) {
  15572. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15573. textures[0]._depthStencilBuffer = null;
  15574. }
  15575. if (textures[0]._MSAAFramebuffer) {
  15576. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15577. textures[0]._MSAAFramebuffer = null;
  15578. }
  15579. for (var i = 0; i < textures.length; i++) {
  15580. if (textures[i]._MSAARenderBuffer) {
  15581. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15582. textures[i]._MSAARenderBuffer = null;
  15583. }
  15584. }
  15585. if (samples > 1) {
  15586. var framebuffer = gl.createFramebuffer();
  15587. if (!framebuffer) {
  15588. throw new Error("Unable to create multi sampled framebuffer");
  15589. }
  15590. this.bindUnboundFramebuffer(framebuffer);
  15591. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15592. var attachments = [];
  15593. for (var i = 0; i < textures.length; i++) {
  15594. var texture = textures[i];
  15595. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15596. var colorRenderbuffer = gl.createRenderbuffer();
  15597. if (!colorRenderbuffer) {
  15598. throw new Error("Unable to create multi sampled framebuffer");
  15599. }
  15600. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15601. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15602. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15603. texture._MSAAFramebuffer = framebuffer;
  15604. texture._MSAARenderBuffer = colorRenderbuffer;
  15605. texture.samples = samples;
  15606. texture._depthStencilBuffer = depthStencilBuffer;
  15607. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15608. attachments.push(attachment);
  15609. }
  15610. gl.drawBuffers(attachments);
  15611. }
  15612. else {
  15613. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15614. }
  15615. this.bindUnboundFramebuffer(null);
  15616. return samples;
  15617. };
  15618. /** @hidden */
  15619. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15620. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15621. };
  15622. /** @hidden */
  15623. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15624. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15625. };
  15626. /** @hidden */
  15627. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15628. var gl = this._gl;
  15629. var textureType = this._getWebGLTextureType(texture.type);
  15630. var format = this._getInternalFormat(texture.format);
  15631. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15632. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15633. this._bindTextureDirectly(bindTarget, texture, true);
  15634. this._unpackFlipY(texture.invertY);
  15635. var target = gl.TEXTURE_2D;
  15636. if (texture.isCube) {
  15637. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15638. }
  15639. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15640. this._bindTextureDirectly(bindTarget, null, true);
  15641. };
  15642. /**
  15643. * Creates a new render target cube texture
  15644. * @param size defines the size of the texture
  15645. * @param options defines the options used to create the texture
  15646. * @returns a new render target cube texture stored in an InternalTexture
  15647. */
  15648. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15649. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15650. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15651. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15652. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15653. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15654. }
  15655. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15656. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15657. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15658. }
  15659. var gl = this._gl;
  15660. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15661. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15662. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15663. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15664. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15665. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15666. }
  15667. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15668. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15669. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15671. for (var face = 0; face < 6; face++) {
  15672. 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);
  15673. }
  15674. // Create the framebuffer
  15675. var framebuffer = gl.createFramebuffer();
  15676. this.bindUnboundFramebuffer(framebuffer);
  15677. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15678. // MipMaps
  15679. if (fullOptions.generateMipMaps) {
  15680. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15681. }
  15682. // Unbind
  15683. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15684. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15685. this.bindUnboundFramebuffer(null);
  15686. texture._framebuffer = framebuffer;
  15687. texture.width = size;
  15688. texture.height = size;
  15689. texture.isReady = true;
  15690. texture.isCube = true;
  15691. texture.samples = 1;
  15692. texture.generateMipMaps = fullOptions.generateMipMaps;
  15693. texture.samplingMode = fullOptions.samplingMode;
  15694. texture.type = fullOptions.type;
  15695. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15696. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15697. this._internalTexturesCache.push(texture);
  15698. return texture;
  15699. };
  15700. /**
  15701. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15702. * @param rootUrl defines the url where the file to load is located
  15703. * @param scene defines the current scene
  15704. * @param lodScale defines scale to apply to the mip map selection
  15705. * @param lodOffset defines offset to apply to the mip map selection
  15706. * @param onLoad defines an optional callback raised when the texture is loaded
  15707. * @param onError defines an optional callback raised if there is an issue to load the texture
  15708. * @param format defines the format of the data
  15709. * @param forcedExtension defines the extension to use to pick the right loader
  15710. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15711. * @returns the cube texture as an InternalTexture
  15712. */
  15713. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15714. var _this = this;
  15715. if (onLoad === void 0) { onLoad = null; }
  15716. if (onError === void 0) { onError = null; }
  15717. if (forcedExtension === void 0) { forcedExtension = null; }
  15718. if (createPolynomials === void 0) { createPolynomials = true; }
  15719. var callback = function (loadData) {
  15720. if (!loadData) {
  15721. if (onLoad) {
  15722. onLoad(null);
  15723. }
  15724. return;
  15725. }
  15726. var texture = loadData.texture;
  15727. if (!createPolynomials) {
  15728. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15729. }
  15730. else if (loadData.info.sphericalPolynomial) {
  15731. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15732. }
  15733. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15734. if (_this._caps.textureLOD) {
  15735. // Do not add extra process if texture lod is supported.
  15736. if (onLoad) {
  15737. onLoad(texture);
  15738. }
  15739. return;
  15740. }
  15741. var mipSlices = 3;
  15742. var gl = _this._gl;
  15743. var width = loadData.width;
  15744. if (!width) {
  15745. return;
  15746. }
  15747. var textures = [];
  15748. for (var i = 0; i < mipSlices; i++) {
  15749. //compute LOD from even spacing in smoothness (matching shader calculation)
  15750. var smoothness = i / (mipSlices - 1);
  15751. var roughness = 1 - smoothness;
  15752. var minLODIndex = lodOffset; // roughness = 0
  15753. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15754. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15755. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15756. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15757. glTextureFromLod.isCube = true;
  15758. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15759. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15762. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15763. if (loadData.isDDS) {
  15764. var info = loadData.info;
  15765. var data = loadData.data;
  15766. _this._unpackFlipY(info.isCompressed);
  15767. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15768. }
  15769. else {
  15770. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15771. }
  15772. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15773. // Wrap in a base texture for easy binding.
  15774. var lodTexture = new BABYLON.BaseTexture(scene);
  15775. lodTexture.isCube = true;
  15776. lodTexture._texture = glTextureFromLod;
  15777. glTextureFromLod.isReady = true;
  15778. textures.push(lodTexture);
  15779. }
  15780. texture._lodTextureHigh = textures[2];
  15781. texture._lodTextureMid = textures[1];
  15782. texture._lodTextureLow = textures[0];
  15783. if (onLoad) {
  15784. onLoad(texture);
  15785. }
  15786. };
  15787. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15788. };
  15789. /**
  15790. * Creates a cube texture
  15791. * @param rootUrl defines the url where the files to load is located
  15792. * @param scene defines the current scene
  15793. * @param files defines the list of files to load (1 per face)
  15794. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15795. * @param onLoad defines an optional callback raised when the texture is loaded
  15796. * @param onError defines an optional callback raised if there is an issue to load the texture
  15797. * @param format defines the format of the data
  15798. * @param forcedExtension defines the extension to use to pick the right loader
  15799. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15800. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15801. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15802. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15803. * @returns the cube texture as an InternalTexture
  15804. */
  15805. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15806. var _this = this;
  15807. if (onLoad === void 0) { onLoad = null; }
  15808. if (onError === void 0) { onError = null; }
  15809. if (forcedExtension === void 0) { forcedExtension = null; }
  15810. if (createPolynomials === void 0) { createPolynomials = false; }
  15811. if (lodScale === void 0) { lodScale = 0; }
  15812. if (lodOffset === void 0) { lodOffset = 0; }
  15813. if (fallback === void 0) { fallback = null; }
  15814. var gl = this._gl;
  15815. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15816. texture.isCube = true;
  15817. texture.url = rootUrl;
  15818. texture.generateMipMaps = !noMipmap;
  15819. texture._lodGenerationScale = lodScale;
  15820. texture._lodGenerationOffset = lodOffset;
  15821. if (!this._doNotHandleContextLost) {
  15822. texture._extension = forcedExtension;
  15823. texture._files = files;
  15824. }
  15825. var isKTX = false;
  15826. var isDDS = false;
  15827. var isEnv = false;
  15828. var lastDot = rootUrl.lastIndexOf('.');
  15829. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15830. if (this._textureFormatInUse && !fallback) {
  15831. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15832. isKTX = true;
  15833. }
  15834. else {
  15835. isDDS = (extension === ".dds");
  15836. isEnv = (extension === ".env");
  15837. }
  15838. var onerror = function (request, exception) {
  15839. if (isKTX) {
  15840. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15841. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15842. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15843. }
  15844. if (onError && request) {
  15845. onError(request.status + " " + request.statusText, exception);
  15846. }
  15847. };
  15848. if (isKTX) {
  15849. this._loadFile(rootUrl, function (data) {
  15850. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15851. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15852. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15853. _this._unpackFlipY(true);
  15854. ktx.uploadLevels(_this._gl, !noMipmap);
  15855. _this.setCubeMapTextureParams(gl, loadMipmap);
  15856. texture.width = ktx.pixelWidth;
  15857. texture.height = ktx.pixelHeight;
  15858. texture.isReady = true;
  15859. }, undefined, undefined, true, onerror);
  15860. }
  15861. else if (isEnv) {
  15862. this._loadFile(rootUrl, function (data) {
  15863. data = data;
  15864. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15865. if (info) {
  15866. texture.width = info.width;
  15867. texture.height = info.width;
  15868. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15869. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15870. texture.isReady = true;
  15871. if (onLoad) {
  15872. onLoad();
  15873. }
  15874. });
  15875. }
  15876. else if (onError) {
  15877. onError("Can not parse the environment file", null);
  15878. }
  15879. }, undefined, undefined, true, onerror);
  15880. }
  15881. else if (isDDS) {
  15882. if (files && files.length === 6) {
  15883. this._cascadeLoadFiles(scene, function (imgs) {
  15884. var info;
  15885. var loadMipmap = false;
  15886. var width = 0;
  15887. for (var index = 0; index < imgs.length; index++) {
  15888. var data = imgs[index];
  15889. info = BABYLON.DDSTools.GetDDSInfo(data);
  15890. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15891. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15892. _this._unpackFlipY(info.isCompressed);
  15893. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15894. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15895. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15896. }
  15897. texture.width = info.width;
  15898. texture.height = info.height;
  15899. texture.type = info.textureType;
  15900. width = info.width;
  15901. }
  15902. _this.setCubeMapTextureParams(gl, loadMipmap);
  15903. texture.isReady = true;
  15904. if (onLoad) {
  15905. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15906. }
  15907. }, files, onError);
  15908. }
  15909. else {
  15910. this._loadFile(rootUrl, function (data) {
  15911. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15912. if (createPolynomials) {
  15913. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15914. }
  15915. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15916. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15917. _this._unpackFlipY(info.isCompressed);
  15918. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15919. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15920. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15921. }
  15922. _this.setCubeMapTextureParams(gl, loadMipmap);
  15923. texture.width = info.width;
  15924. texture.height = info.height;
  15925. texture.isReady = true;
  15926. texture.type = info.textureType;
  15927. if (onLoad) {
  15928. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15929. }
  15930. }, undefined, undefined, true, onerror);
  15931. }
  15932. }
  15933. else {
  15934. if (!files) {
  15935. throw new Error("Cannot load cubemap because files were not defined");
  15936. }
  15937. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15938. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15939. var height = width;
  15940. _this._prepareWorkingCanvas();
  15941. if (!_this._workingCanvas || !_this._workingContext) {
  15942. return;
  15943. }
  15944. _this._workingCanvas.width = width;
  15945. _this._workingCanvas.height = height;
  15946. var faces = [
  15947. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15948. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15949. ];
  15950. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15951. _this._unpackFlipY(false);
  15952. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15953. for (var index = 0; index < faces.length; index++) {
  15954. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15955. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15956. }
  15957. if (!noMipmap) {
  15958. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15959. }
  15960. _this.setCubeMapTextureParams(gl, !noMipmap);
  15961. texture.width = width;
  15962. texture.height = height;
  15963. texture.isReady = true;
  15964. if (format) {
  15965. texture.format = format;
  15966. }
  15967. texture.onLoadedObservable.notifyObservers(texture);
  15968. texture.onLoadedObservable.clear();
  15969. if (onLoad) {
  15970. onLoad();
  15971. }
  15972. }, files, onError);
  15973. }
  15974. this._internalTexturesCache.push(texture);
  15975. return texture;
  15976. };
  15977. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15978. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15979. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15980. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15981. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15982. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15983. // this.resetTextureCache();
  15984. };
  15985. /**
  15986. * Update a raw cube texture
  15987. * @param texture defines the texture to udpdate
  15988. * @param data defines the data to store
  15989. * @param format defines the data format
  15990. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15991. * @param invertY defines if data must be stored with Y axis inverted
  15992. * @param compression defines the compression used (null by default)
  15993. * @param level defines which level of the texture to update
  15994. */
  15995. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15996. if (compression === void 0) { compression = null; }
  15997. if (level === void 0) { level = 0; }
  15998. texture._bufferViewArray = data;
  15999. texture.format = format;
  16000. texture.type = type;
  16001. texture.invertY = invertY;
  16002. texture._compression = compression;
  16003. var gl = this._gl;
  16004. var textureType = this._getWebGLTextureType(type);
  16005. var internalFormat = this._getInternalFormat(format);
  16006. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16007. var needConversion = false;
  16008. if (internalFormat === gl.RGB) {
  16009. internalFormat = gl.RGBA;
  16010. needConversion = true;
  16011. }
  16012. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16013. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16014. if (texture.width % 4 !== 0) {
  16015. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16016. }
  16017. // Data are known to be in +X +Y +Z -X -Y -Z
  16018. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16019. var faceData = data[faceIndex];
  16020. if (compression) {
  16021. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16022. }
  16023. else {
  16024. if (needConversion) {
  16025. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16026. }
  16027. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16028. }
  16029. }
  16030. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16031. if (isPot && texture.generateMipMaps && level === 0) {
  16032. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16033. }
  16034. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16035. // this.resetTextureCache();
  16036. texture.isReady = true;
  16037. };
  16038. /**
  16039. * Creates a new raw cube texture
  16040. * @param data defines the array of data to use to create each face
  16041. * @param size defines the size of the textures
  16042. * @param format defines the format of the data
  16043. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16044. * @param generateMipMaps defines if the engine should generate the mip levels
  16045. * @param invertY defines if data must be stored with Y axis inverted
  16046. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16047. * @param compression defines the compression used (null by default)
  16048. * @returns the cube texture as an InternalTexture
  16049. */
  16050. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16051. if (compression === void 0) { compression = null; }
  16052. var gl = this._gl;
  16053. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16054. texture.isCube = true;
  16055. texture.generateMipMaps = generateMipMaps;
  16056. texture.format = format;
  16057. texture.type = type;
  16058. if (!this._doNotHandleContextLost) {
  16059. texture._bufferViewArray = data;
  16060. }
  16061. var textureType = this._getWebGLTextureType(type);
  16062. var internalFormat = this._getInternalFormat(format);
  16063. if (internalFormat === gl.RGB) {
  16064. internalFormat = gl.RGBA;
  16065. }
  16066. var width = size;
  16067. var height = width;
  16068. texture.width = width;
  16069. texture.height = height;
  16070. // Double check on POT to generate Mips.
  16071. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16072. if (!isPot) {
  16073. generateMipMaps = false;
  16074. }
  16075. // Upload data if needed. The texture won't be ready until then.
  16076. if (data) {
  16077. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16078. }
  16079. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16080. // Filters
  16081. if (data && generateMipMaps) {
  16082. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16083. }
  16084. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16085. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16086. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16087. }
  16088. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16089. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16090. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16091. }
  16092. else {
  16093. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16096. }
  16097. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16098. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16099. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16100. return texture;
  16101. };
  16102. /**
  16103. * Creates a new raw cube texture from a specified url
  16104. * @param url defines the url where the data is located
  16105. * @param scene defines the current scene
  16106. * @param size defines the size of the textures
  16107. * @param format defines the format of the data
  16108. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16109. * @param noMipmap defines if the engine should avoid generating the mip levels
  16110. * @param callback defines a callback used to extract texture data from loaded data
  16111. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16112. * @param onLoad defines a callback called when texture is loaded
  16113. * @param onError defines a callback called if there is an error
  16114. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16115. * @param invertY defines if data must be stored with Y axis inverted
  16116. * @returns the cube texture as an InternalTexture
  16117. */
  16118. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16119. var _this = this;
  16120. if (onLoad === void 0) { onLoad = null; }
  16121. if (onError === void 0) { onError = null; }
  16122. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16123. if (invertY === void 0) { invertY = false; }
  16124. var gl = this._gl;
  16125. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16126. scene._addPendingData(texture);
  16127. texture.url = url;
  16128. this._internalTexturesCache.push(texture);
  16129. var onerror = function (request, exception) {
  16130. scene._removePendingData(texture);
  16131. if (onError && request) {
  16132. onError(request.status + " " + request.statusText, exception);
  16133. }
  16134. };
  16135. var internalCallback = function (data) {
  16136. var width = texture.width;
  16137. var faceDataArrays = callback(data);
  16138. if (!faceDataArrays) {
  16139. return;
  16140. }
  16141. if (mipmapGenerator) {
  16142. var textureType = _this._getWebGLTextureType(type);
  16143. var internalFormat = _this._getInternalFormat(format);
  16144. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16145. var needConversion = false;
  16146. if (internalFormat === gl.RGB) {
  16147. internalFormat = gl.RGBA;
  16148. needConversion = true;
  16149. }
  16150. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16151. _this._unpackFlipY(false);
  16152. var mipData = mipmapGenerator(faceDataArrays);
  16153. for (var level = 0; level < mipData.length; level++) {
  16154. var mipSize = width >> level;
  16155. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16156. var mipFaceData = mipData[level][faceIndex];
  16157. if (needConversion) {
  16158. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16159. }
  16160. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16161. }
  16162. }
  16163. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16164. }
  16165. else {
  16166. texture.generateMipMaps = !noMipmap;
  16167. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16168. }
  16169. texture.isReady = true;
  16170. // this.resetTextureCache();
  16171. scene._removePendingData(texture);
  16172. if (onLoad) {
  16173. onLoad();
  16174. }
  16175. };
  16176. this._loadFile(url, function (data) {
  16177. internalCallback(data);
  16178. }, undefined, scene.database, true, onerror);
  16179. return texture;
  16180. };
  16181. ;
  16182. /**
  16183. * Update a raw 3D texture
  16184. * @param texture defines the texture to update
  16185. * @param data defines the data to store
  16186. * @param format defines the data format
  16187. * @param invertY defines if data must be stored with Y axis inverted
  16188. * @param compression defines the used compression (can be null)
  16189. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16190. */
  16191. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16192. if (compression === void 0) { compression = null; }
  16193. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16194. var internalType = this._getWebGLTextureType(textureType);
  16195. var internalFormat = this._getInternalFormat(format);
  16196. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16197. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16198. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16199. if (!this._doNotHandleContextLost) {
  16200. texture._bufferView = data;
  16201. texture.format = format;
  16202. texture.invertY = invertY;
  16203. texture._compression = compression;
  16204. }
  16205. if (texture.width % 4 !== 0) {
  16206. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16207. }
  16208. if (compression && data) {
  16209. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16210. }
  16211. else {
  16212. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16213. }
  16214. if (texture.generateMipMaps) {
  16215. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16216. }
  16217. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16218. // this.resetTextureCache();
  16219. texture.isReady = true;
  16220. };
  16221. /**
  16222. * Creates a new raw 3D texture
  16223. * @param data defines the data used to create the texture
  16224. * @param width defines the width of the texture
  16225. * @param height defines the height of the texture
  16226. * @param depth defines the depth of the texture
  16227. * @param format defines the format of the texture
  16228. * @param generateMipMaps defines if the engine must generate mip levels
  16229. * @param invertY defines if data must be stored with Y axis inverted
  16230. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16231. * @param compression defines the compressed used (can be null)
  16232. * @param textureType defines the compressed used (can be null)
  16233. * @returns a new raw 3D texture (stored in an InternalTexture)
  16234. */
  16235. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16236. if (compression === void 0) { compression = null; }
  16237. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16238. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16239. texture.baseWidth = width;
  16240. texture.baseHeight = height;
  16241. texture.baseDepth = depth;
  16242. texture.width = width;
  16243. texture.height = height;
  16244. texture.depth = depth;
  16245. texture.format = format;
  16246. texture.type = textureType;
  16247. texture.generateMipMaps = generateMipMaps;
  16248. texture.samplingMode = samplingMode;
  16249. texture.is3D = true;
  16250. if (!this._doNotHandleContextLost) {
  16251. texture._bufferView = data;
  16252. }
  16253. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16254. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16255. // Filters
  16256. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16257. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16258. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16259. if (generateMipMaps) {
  16260. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16261. }
  16262. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16263. this._internalTexturesCache.push(texture);
  16264. return texture;
  16265. };
  16266. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16267. var gl = this._gl;
  16268. if (!gl) {
  16269. return;
  16270. }
  16271. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16272. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16273. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16274. if (!noMipmap && !isCompressed) {
  16275. gl.generateMipmap(gl.TEXTURE_2D);
  16276. }
  16277. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16278. // this.resetTextureCache();
  16279. if (scene) {
  16280. scene._removePendingData(texture);
  16281. }
  16282. texture.onLoadedObservable.notifyObservers(texture);
  16283. texture.onLoadedObservable.clear();
  16284. };
  16285. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16286. var _this = this;
  16287. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16288. var maxTextureSize = this.getCaps().maxTextureSize;
  16289. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16290. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16291. var gl = this._gl;
  16292. if (!gl) {
  16293. return;
  16294. }
  16295. if (!texture._webGLTexture) {
  16296. // this.resetTextureCache();
  16297. if (scene) {
  16298. scene._removePendingData(texture);
  16299. }
  16300. return;
  16301. }
  16302. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16303. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16304. texture.baseWidth = width;
  16305. texture.baseHeight = height;
  16306. texture.width = potWidth;
  16307. texture.height = potHeight;
  16308. texture.isReady = true;
  16309. if (processFunction(potWidth, potHeight, function () {
  16310. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16311. })) {
  16312. // Returning as texture needs extra async steps
  16313. return;
  16314. }
  16315. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16316. };
  16317. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16318. // Create new RGBA data container.
  16319. var rgbaData;
  16320. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16321. rgbaData = new Float32Array(width * height * 4);
  16322. }
  16323. else {
  16324. rgbaData = new Uint32Array(width * height * 4);
  16325. }
  16326. // Convert each pixel.
  16327. for (var x = 0; x < width; x++) {
  16328. for (var y = 0; y < height; y++) {
  16329. var index = (y * width + x) * 3;
  16330. var newIndex = (y * width + x) * 4;
  16331. // Map Old Value to new value.
  16332. rgbaData[newIndex + 0] = rgbData[index + 0];
  16333. rgbaData[newIndex + 1] = rgbData[index + 1];
  16334. rgbaData[newIndex + 2] = rgbData[index + 2];
  16335. // Add fully opaque alpha channel.
  16336. rgbaData[newIndex + 3] = 1;
  16337. }
  16338. }
  16339. return rgbaData;
  16340. };
  16341. /** @hidden */
  16342. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16343. var gl = this._gl;
  16344. if (texture._framebuffer) {
  16345. gl.deleteFramebuffer(texture._framebuffer);
  16346. texture._framebuffer = null;
  16347. }
  16348. if (texture._depthStencilBuffer) {
  16349. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16350. texture._depthStencilBuffer = null;
  16351. }
  16352. if (texture._MSAAFramebuffer) {
  16353. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16354. texture._MSAAFramebuffer = null;
  16355. }
  16356. if (texture._MSAARenderBuffer) {
  16357. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16358. texture._MSAARenderBuffer = null;
  16359. }
  16360. };
  16361. /** @hidden */
  16362. Engine.prototype._releaseTexture = function (texture) {
  16363. var gl = this._gl;
  16364. this._releaseFramebufferObjects(texture);
  16365. gl.deleteTexture(texture._webGLTexture);
  16366. // Unbind channels
  16367. this.unbindAllTextures();
  16368. var index = this._internalTexturesCache.indexOf(texture);
  16369. if (index !== -1) {
  16370. this._internalTexturesCache.splice(index, 1);
  16371. }
  16372. // Integrated fixed lod samplers.
  16373. if (texture._lodTextureHigh) {
  16374. texture._lodTextureHigh.dispose();
  16375. }
  16376. if (texture._lodTextureMid) {
  16377. texture._lodTextureMid.dispose();
  16378. }
  16379. if (texture._lodTextureLow) {
  16380. texture._lodTextureLow.dispose();
  16381. }
  16382. // Set output texture of post process to null if the texture has been released/disposed
  16383. this.scenes.forEach(function (scene) {
  16384. scene.postProcesses.forEach(function (postProcess) {
  16385. if (postProcess._outputTexture == texture) {
  16386. postProcess._outputTexture = null;
  16387. }
  16388. });
  16389. scene.cameras.forEach(function (camera) {
  16390. camera._postProcesses.forEach(function (postProcess) {
  16391. if (postProcess) {
  16392. if (postProcess._outputTexture == texture) {
  16393. postProcess._outputTexture = null;
  16394. }
  16395. }
  16396. });
  16397. });
  16398. });
  16399. };
  16400. Engine.prototype.setProgram = function (program) {
  16401. if (this._currentProgram !== program) {
  16402. this._gl.useProgram(program);
  16403. this._currentProgram = program;
  16404. }
  16405. };
  16406. /**
  16407. * Binds an effect to the webGL context
  16408. * @param effect defines the effect to bind
  16409. */
  16410. Engine.prototype.bindSamplers = function (effect) {
  16411. this.setProgram(effect.getProgram());
  16412. var samplers = effect.getSamplers();
  16413. for (var index = 0; index < samplers.length; index++) {
  16414. var uniform = effect.getUniform(samplers[index]);
  16415. if (uniform) {
  16416. this._boundUniforms[index] = uniform;
  16417. }
  16418. }
  16419. this._currentEffect = null;
  16420. };
  16421. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16422. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16423. return;
  16424. }
  16425. // Remove
  16426. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16427. // Bind last to it
  16428. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16429. // Bind to dummy
  16430. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16431. };
  16432. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16433. if (!internalTexture) {
  16434. return -1;
  16435. }
  16436. internalTexture._initialSlot = channel;
  16437. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16438. if (channel !== internalTexture._designatedSlot) {
  16439. this._textureCollisions.addCount(1, false);
  16440. }
  16441. }
  16442. else {
  16443. if (channel !== internalTexture._designatedSlot) {
  16444. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16445. return internalTexture._designatedSlot;
  16446. }
  16447. else {
  16448. // No slot for this texture, let's pick a new one (if we find a free slot)
  16449. if (this._nextFreeTextureSlots.length) {
  16450. return this._nextFreeTextureSlots[0];
  16451. }
  16452. // We need to recycle the oldest bound texture, sorry.
  16453. this._textureCollisions.addCount(1, false);
  16454. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16455. }
  16456. }
  16457. }
  16458. return channel;
  16459. };
  16460. Engine.prototype._linkTrackers = function (previous, next) {
  16461. previous.next = next;
  16462. next.previous = previous;
  16463. };
  16464. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16465. var currentSlot = internalTexture._designatedSlot;
  16466. if (currentSlot === -1) {
  16467. return -1;
  16468. }
  16469. internalTexture._designatedSlot = -1;
  16470. if (this.disableTextureBindingOptimization) {
  16471. return -1;
  16472. }
  16473. // Remove from bound list
  16474. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16475. // Free the slot
  16476. this._boundTexturesCache[currentSlot] = null;
  16477. this._nextFreeTextureSlots.push(currentSlot);
  16478. return currentSlot;
  16479. };
  16480. Engine.prototype._activateCurrentTexture = function () {
  16481. if (this._currentTextureChannel !== this._activeChannel) {
  16482. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16483. this._currentTextureChannel = this._activeChannel;
  16484. }
  16485. };
  16486. /** @hidden */
  16487. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16488. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16489. if (force === void 0) { force = false; }
  16490. var wasPreviouslyBound = false;
  16491. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16492. this._activeChannel = texture._designatedSlot;
  16493. }
  16494. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16495. var isTextureForRendering = texture && texture._initialSlot > -1;
  16496. if (currentTextureBound !== texture || force) {
  16497. if (currentTextureBound) {
  16498. this._removeDesignatedSlot(currentTextureBound);
  16499. }
  16500. this._activateCurrentTexture();
  16501. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16502. this._boundTexturesCache[this._activeChannel] = texture;
  16503. if (texture) {
  16504. if (!this.disableTextureBindingOptimization) {
  16505. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16506. if (slotIndex > -1) {
  16507. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16508. }
  16509. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16510. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16511. }
  16512. texture._designatedSlot = this._activeChannel;
  16513. }
  16514. }
  16515. else if (forTextureDataUpdate) {
  16516. wasPreviouslyBound = true;
  16517. this._activateCurrentTexture();
  16518. }
  16519. if (isTextureForRendering && !forTextureDataUpdate) {
  16520. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16521. }
  16522. return wasPreviouslyBound;
  16523. };
  16524. /** @hidden */
  16525. Engine.prototype._bindTexture = function (channel, texture) {
  16526. if (channel < 0) {
  16527. return;
  16528. }
  16529. if (texture) {
  16530. channel = this._getCorrectTextureChannel(channel, texture);
  16531. }
  16532. this._activeChannel = channel;
  16533. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16534. };
  16535. /**
  16536. * Sets a texture to the webGL context from a postprocess
  16537. * @param channel defines the channel to use
  16538. * @param postProcess defines the source postprocess
  16539. */
  16540. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16541. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16542. };
  16543. /**
  16544. * Binds the output of the passed in post process to the texture channel specified
  16545. * @param channel The channel the texture should be bound to
  16546. * @param postProcess The post process which's output should be bound
  16547. */
  16548. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16549. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16550. };
  16551. /**
  16552. * Unbind all textures from the webGL context
  16553. */
  16554. Engine.prototype.unbindAllTextures = function () {
  16555. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16556. this._activeChannel = channel;
  16557. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16558. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16559. if (this.webGLVersion > 1) {
  16560. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16561. }
  16562. }
  16563. };
  16564. /**
  16565. * Sets a texture to the according uniform.
  16566. * @param channel The texture channel
  16567. * @param uniform The uniform to set
  16568. * @param texture The texture to apply
  16569. */
  16570. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16571. if (channel < 0) {
  16572. return;
  16573. }
  16574. if (uniform) {
  16575. this._boundUniforms[channel] = uniform;
  16576. }
  16577. this._setTexture(channel, texture);
  16578. };
  16579. /**
  16580. * Sets a depth stencil texture from a render target to the according uniform.
  16581. * @param channel The texture channel
  16582. * @param uniform The uniform to set
  16583. * @param texture The render target texture containing the depth stencil texture to apply
  16584. */
  16585. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16586. if (channel < 0) {
  16587. return;
  16588. }
  16589. if (uniform) {
  16590. this._boundUniforms[channel] = uniform;
  16591. }
  16592. if (!texture || !texture.depthStencilTexture) {
  16593. this._setTexture(channel, null);
  16594. }
  16595. else {
  16596. this._setTexture(channel, texture, false, true);
  16597. }
  16598. };
  16599. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16600. var uniform = this._boundUniforms[sourceSlot];
  16601. if (uniform._currentState === destination) {
  16602. return;
  16603. }
  16604. this._gl.uniform1i(uniform, destination);
  16605. uniform._currentState = destination;
  16606. };
  16607. Engine.prototype._getTextureWrapMode = function (mode) {
  16608. switch (mode) {
  16609. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16610. return this._gl.REPEAT;
  16611. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16612. return this._gl.CLAMP_TO_EDGE;
  16613. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16614. return this._gl.MIRRORED_REPEAT;
  16615. }
  16616. return this._gl.REPEAT;
  16617. };
  16618. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16619. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16620. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16621. // Not ready?
  16622. if (!texture) {
  16623. if (this._boundTexturesCache[channel] != null) {
  16624. this._activeChannel = channel;
  16625. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16626. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16627. if (this.webGLVersion > 1) {
  16628. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16629. }
  16630. }
  16631. return false;
  16632. }
  16633. // Video
  16634. if (texture.video) {
  16635. this._activeChannel = channel;
  16636. texture.update();
  16637. }
  16638. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16639. texture.delayLoad();
  16640. return false;
  16641. }
  16642. var internalTexture;
  16643. if (depthStencilTexture) {
  16644. internalTexture = texture.depthStencilTexture;
  16645. }
  16646. else if (texture.isReady()) {
  16647. internalTexture = texture.getInternalTexture();
  16648. }
  16649. else if (texture.isCube) {
  16650. internalTexture = this.emptyCubeTexture;
  16651. }
  16652. else if (texture.is3D) {
  16653. internalTexture = this.emptyTexture3D;
  16654. }
  16655. else {
  16656. internalTexture = this.emptyTexture;
  16657. }
  16658. if (!isPartOfTextureArray) {
  16659. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16660. }
  16661. var needToBind = true;
  16662. if (this._boundTexturesCache[channel] === internalTexture) {
  16663. this._moveBoundTextureOnTop(internalTexture);
  16664. if (!isPartOfTextureArray) {
  16665. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16666. }
  16667. needToBind = false;
  16668. }
  16669. this._activeChannel = channel;
  16670. if (internalTexture && internalTexture.is3D) {
  16671. if (needToBind) {
  16672. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16673. }
  16674. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16675. internalTexture._cachedWrapU = texture.wrapU;
  16676. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16677. }
  16678. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16679. internalTexture._cachedWrapV = texture.wrapV;
  16680. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16681. }
  16682. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16683. internalTexture._cachedWrapR = texture.wrapR;
  16684. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16685. }
  16686. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16687. }
  16688. else if (internalTexture && internalTexture.isCube) {
  16689. if (needToBind) {
  16690. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16691. }
  16692. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16693. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16694. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16695. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16696. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16697. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16698. }
  16699. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16700. }
  16701. else {
  16702. if (needToBind) {
  16703. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16704. }
  16705. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16706. internalTexture._cachedWrapU = texture.wrapU;
  16707. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16708. }
  16709. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16710. internalTexture._cachedWrapV = texture.wrapV;
  16711. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16712. }
  16713. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16714. }
  16715. return true;
  16716. };
  16717. /**
  16718. * Sets an array of texture to the webGL context
  16719. * @param channel defines the channel where the texture array must be set
  16720. * @param uniform defines the associated uniform location
  16721. * @param textures defines the array of textures to bind
  16722. */
  16723. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16724. if (channel < 0 || !uniform) {
  16725. return;
  16726. }
  16727. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16728. this._textureUnits = new Int32Array(textures.length);
  16729. }
  16730. for (var i = 0; i < textures.length; i++) {
  16731. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16732. }
  16733. this._gl.uniform1iv(uniform, this._textureUnits);
  16734. for (var index = 0; index < textures.length; index++) {
  16735. this._setTexture(this._textureUnits[index], textures[index], true);
  16736. }
  16737. };
  16738. /** @hidden */
  16739. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16740. var internalTexture = texture.getInternalTexture();
  16741. if (!internalTexture) {
  16742. return;
  16743. }
  16744. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16745. var value = texture.anisotropicFilteringLevel;
  16746. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16747. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16748. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16749. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16750. }
  16751. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16752. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16753. internalTexture._cachedAnisotropicFilteringLevel = value;
  16754. }
  16755. };
  16756. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16757. this._bindTextureDirectly(target, texture, true, true);
  16758. this._gl.texParameterf(target, parameter, value);
  16759. };
  16760. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16761. if (texture) {
  16762. this._bindTextureDirectly(target, texture, true, true);
  16763. }
  16764. this._gl.texParameteri(target, parameter, value);
  16765. };
  16766. /**
  16767. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16768. * @param x defines the x coordinate of the rectangle where pixels must be read
  16769. * @param y defines the y coordinate of the rectangle where pixels must be read
  16770. * @param width defines the width of the rectangle where pixels must be read
  16771. * @param height defines the height of the rectangle where pixels must be read
  16772. * @returns a Uint8Array containing RGBA colors
  16773. */
  16774. Engine.prototype.readPixels = function (x, y, width, height) {
  16775. var data = new Uint8Array(height * width * 4);
  16776. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16777. return data;
  16778. };
  16779. /**
  16780. * Add an externaly attached data from its key.
  16781. * This method call will fail and return false, if such key already exists.
  16782. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16783. * @param key the unique key that identifies the data
  16784. * @param data the data object to associate to the key for this Engine instance
  16785. * @return true if no such key were already present and the data was added successfully, false otherwise
  16786. */
  16787. Engine.prototype.addExternalData = function (key, data) {
  16788. if (!this._externalData) {
  16789. this._externalData = new BABYLON.StringDictionary();
  16790. }
  16791. return this._externalData.add(key, data);
  16792. };
  16793. /**
  16794. * Get an externaly attached data from its key
  16795. * @param key the unique key that identifies the data
  16796. * @return the associated data, if present (can be null), or undefined if not present
  16797. */
  16798. Engine.prototype.getExternalData = function (key) {
  16799. if (!this._externalData) {
  16800. this._externalData = new BABYLON.StringDictionary();
  16801. }
  16802. return this._externalData.get(key);
  16803. };
  16804. /**
  16805. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16806. * @param key the unique key that identifies the data
  16807. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16808. * @return the associated data, can be null if the factory returned null.
  16809. */
  16810. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16811. if (!this._externalData) {
  16812. this._externalData = new BABYLON.StringDictionary();
  16813. }
  16814. return this._externalData.getOrAddWithFactory(key, factory);
  16815. };
  16816. /**
  16817. * Remove an externaly attached data from the Engine instance
  16818. * @param key the unique key that identifies the data
  16819. * @return true if the data was successfully removed, false if it doesn't exist
  16820. */
  16821. Engine.prototype.removeExternalData = function (key) {
  16822. if (!this._externalData) {
  16823. this._externalData = new BABYLON.StringDictionary();
  16824. }
  16825. return this._externalData.remove(key);
  16826. };
  16827. /**
  16828. * Unbind all vertex attributes from the webGL context
  16829. */
  16830. Engine.prototype.unbindAllAttributes = function () {
  16831. if (this._mustWipeVertexAttributes) {
  16832. this._mustWipeVertexAttributes = false;
  16833. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16834. this._gl.disableVertexAttribArray(i);
  16835. this._vertexAttribArraysEnabled[i] = false;
  16836. this._currentBufferPointers[i].active = false;
  16837. }
  16838. return;
  16839. }
  16840. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16841. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16842. continue;
  16843. }
  16844. this._gl.disableVertexAttribArray(i);
  16845. this._vertexAttribArraysEnabled[i] = false;
  16846. this._currentBufferPointers[i].active = false;
  16847. }
  16848. };
  16849. /**
  16850. * 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
  16851. */
  16852. Engine.prototype.releaseEffects = function () {
  16853. for (var name in this._compiledEffects) {
  16854. this._deleteProgram(this._compiledEffects[name]._program);
  16855. }
  16856. this._compiledEffects = {};
  16857. };
  16858. /**
  16859. * Dispose and release all associated resources
  16860. */
  16861. Engine.prototype.dispose = function () {
  16862. this.hideLoadingUI();
  16863. this.stopRenderLoop();
  16864. // Release postProcesses
  16865. while (this.postProcesses.length) {
  16866. this.postProcesses[0].dispose();
  16867. }
  16868. // Empty texture
  16869. if (this._emptyTexture) {
  16870. this._releaseTexture(this._emptyTexture);
  16871. this._emptyTexture = null;
  16872. }
  16873. if (this._emptyCubeTexture) {
  16874. this._releaseTexture(this._emptyCubeTexture);
  16875. this._emptyCubeTexture = null;
  16876. }
  16877. // Rescale PP
  16878. if (this._rescalePostProcess) {
  16879. this._rescalePostProcess.dispose();
  16880. }
  16881. // Release scenes
  16882. while (this.scenes.length) {
  16883. this.scenes[0].dispose();
  16884. }
  16885. // Release audio engine
  16886. if (Engine.audioEngine) {
  16887. Engine.audioEngine.dispose();
  16888. }
  16889. // Release effects
  16890. this.releaseEffects();
  16891. // Unbind
  16892. this.unbindAllAttributes();
  16893. this._boundUniforms = [];
  16894. if (this._dummyFramebuffer) {
  16895. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16896. }
  16897. //WebVR
  16898. this.disableVR();
  16899. // Events
  16900. if (BABYLON.Tools.IsWindowObjectExist()) {
  16901. window.removeEventListener("blur", this._onBlur);
  16902. window.removeEventListener("focus", this._onFocus);
  16903. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16904. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16905. if (this._renderingCanvas) {
  16906. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16907. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16908. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16909. if (!this._doNotHandleContextLost) {
  16910. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16911. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16912. }
  16913. }
  16914. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16915. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16916. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16917. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16918. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16919. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16920. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16921. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16922. if (this._onVrDisplayConnect) {
  16923. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16924. if (this._onVrDisplayDisconnect) {
  16925. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16926. }
  16927. if (this._onVrDisplayPresentChange) {
  16928. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16929. }
  16930. this._onVrDisplayConnect = null;
  16931. this._onVrDisplayDisconnect = null;
  16932. }
  16933. }
  16934. // Remove from Instances
  16935. var index = Engine.Instances.indexOf(this);
  16936. if (index >= 0) {
  16937. Engine.Instances.splice(index, 1);
  16938. }
  16939. this._workingCanvas = null;
  16940. this._workingContext = null;
  16941. this._currentBufferPointers = [];
  16942. this._renderingCanvas = null;
  16943. this._currentProgram = null;
  16944. this._bindedRenderFunction = null;
  16945. this.onResizeObservable.clear();
  16946. this.onCanvasBlurObservable.clear();
  16947. this.onCanvasFocusObservable.clear();
  16948. this.onCanvasPointerOutObservable.clear();
  16949. this.onBeginFrameObservable.clear();
  16950. this.onEndFrameObservable.clear();
  16951. BABYLON.Effect.ResetCache();
  16952. // Abort active requests
  16953. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16954. var request = _a[_i];
  16955. request.abort();
  16956. }
  16957. };
  16958. // Loading screen
  16959. /**
  16960. * Display the loading screen
  16961. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16962. */
  16963. Engine.prototype.displayLoadingUI = function () {
  16964. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16965. return;
  16966. }
  16967. var loadingScreen = this.loadingScreen;
  16968. if (loadingScreen) {
  16969. loadingScreen.displayLoadingUI();
  16970. }
  16971. };
  16972. /**
  16973. * Hide the loading screen
  16974. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16975. */
  16976. Engine.prototype.hideLoadingUI = function () {
  16977. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16978. return;
  16979. }
  16980. var loadingScreen = this.loadingScreen;
  16981. if (loadingScreen) {
  16982. loadingScreen.hideLoadingUI();
  16983. }
  16984. };
  16985. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16986. /**
  16987. * Gets the current loading screen object
  16988. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16989. */
  16990. get: function () {
  16991. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16992. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16993. return this._loadingScreen;
  16994. },
  16995. /**
  16996. * Sets the current loading screen object
  16997. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16998. */
  16999. set: function (loadingScreen) {
  17000. this._loadingScreen = loadingScreen;
  17001. },
  17002. enumerable: true,
  17003. configurable: true
  17004. });
  17005. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17006. /**
  17007. * Sets the current loading screen text
  17008. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17009. */
  17010. set: function (text) {
  17011. this.loadingScreen.loadingUIText = text;
  17012. },
  17013. enumerable: true,
  17014. configurable: true
  17015. });
  17016. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17017. /**
  17018. * Sets the current loading screen background color
  17019. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17020. */
  17021. set: function (color) {
  17022. this.loadingScreen.loadingUIBackgroundColor = color;
  17023. },
  17024. enumerable: true,
  17025. configurable: true
  17026. });
  17027. /**
  17028. * Attach a new callback raised when context lost event is fired
  17029. * @param callback defines the callback to call
  17030. */
  17031. Engine.prototype.attachContextLostEvent = function (callback) {
  17032. if (this._renderingCanvas) {
  17033. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17034. }
  17035. };
  17036. /**
  17037. * Attach a new callback raised when context restored event is fired
  17038. * @param callback defines the callback to call
  17039. */
  17040. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17041. if (this._renderingCanvas) {
  17042. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17043. }
  17044. };
  17045. /**
  17046. * Gets the source code of the vertex shader associated with a specific webGL program
  17047. * @param program defines the program to use
  17048. * @returns a string containing the source code of the vertex shader associated with the program
  17049. */
  17050. Engine.prototype.getVertexShaderSource = function (program) {
  17051. var shaders = this._gl.getAttachedShaders(program);
  17052. if (!shaders) {
  17053. return null;
  17054. }
  17055. return this._gl.getShaderSource(shaders[0]);
  17056. };
  17057. /**
  17058. * Gets the source code of the fragment shader associated with a specific webGL program
  17059. * @param program defines the program to use
  17060. * @returns a string containing the source code of the fragment shader associated with the program
  17061. */
  17062. Engine.prototype.getFragmentShaderSource = function (program) {
  17063. var shaders = this._gl.getAttachedShaders(program);
  17064. if (!shaders) {
  17065. return null;
  17066. }
  17067. return this._gl.getShaderSource(shaders[1]);
  17068. };
  17069. /**
  17070. * Get the current error code of the webGL context
  17071. * @returns the error code
  17072. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17073. */
  17074. Engine.prototype.getError = function () {
  17075. return this._gl.getError();
  17076. };
  17077. // FPS
  17078. /**
  17079. * Gets the current framerate
  17080. * @returns a number representing the framerate
  17081. */
  17082. Engine.prototype.getFps = function () {
  17083. return this._fps;
  17084. };
  17085. /**
  17086. * Gets the time spent between current and previous frame
  17087. * @returns a number representing the delta time in ms
  17088. */
  17089. Engine.prototype.getDeltaTime = function () {
  17090. return this._deltaTime;
  17091. };
  17092. Engine.prototype._measureFps = function () {
  17093. this._performanceMonitor.sampleFrame();
  17094. this._fps = this._performanceMonitor.averageFPS;
  17095. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17096. };
  17097. /** @hidden */
  17098. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17099. if (faceIndex === void 0) { faceIndex = -1; }
  17100. if (level === void 0) { level = 0; }
  17101. var gl = this._gl;
  17102. if (!this._dummyFramebuffer) {
  17103. var dummy = gl.createFramebuffer();
  17104. if (!dummy) {
  17105. throw new Error("Unable to create dummy framebuffer");
  17106. }
  17107. this._dummyFramebuffer = dummy;
  17108. }
  17109. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17110. if (faceIndex > -1) {
  17111. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17112. }
  17113. else {
  17114. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17115. }
  17116. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17117. var buffer;
  17118. switch (readType) {
  17119. case gl.UNSIGNED_BYTE:
  17120. buffer = new Uint8Array(4 * width * height);
  17121. readType = gl.UNSIGNED_BYTE;
  17122. break;
  17123. default:
  17124. buffer = new Float32Array(4 * width * height);
  17125. readType = gl.FLOAT;
  17126. break;
  17127. }
  17128. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17129. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17130. return buffer;
  17131. };
  17132. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17133. if (this._webGLVersion > 1) {
  17134. return this._caps.colorBufferFloat;
  17135. }
  17136. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17137. };
  17138. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17139. if (this._webGLVersion > 1) {
  17140. return this._caps.colorBufferFloat;
  17141. }
  17142. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17143. };
  17144. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17145. Engine.prototype._canRenderToFramebuffer = function (type) {
  17146. var gl = this._gl;
  17147. //clear existing errors
  17148. while (gl.getError() !== gl.NO_ERROR) { }
  17149. var successful = true;
  17150. var texture = gl.createTexture();
  17151. gl.bindTexture(gl.TEXTURE_2D, texture);
  17152. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17153. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17154. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17155. var fb = gl.createFramebuffer();
  17156. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17157. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17158. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17159. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17160. successful = successful && (gl.getError() === gl.NO_ERROR);
  17161. //try render by clearing frame buffer's color buffer
  17162. if (successful) {
  17163. gl.clear(gl.COLOR_BUFFER_BIT);
  17164. successful = successful && (gl.getError() === gl.NO_ERROR);
  17165. }
  17166. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17167. if (successful) {
  17168. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17169. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17170. var readFormat = gl.RGBA;
  17171. var readType = gl.UNSIGNED_BYTE;
  17172. var buffer = new Uint8Array(4);
  17173. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17174. successful = successful && (gl.getError() === gl.NO_ERROR);
  17175. }
  17176. //clean up
  17177. gl.deleteTexture(texture);
  17178. gl.deleteFramebuffer(fb);
  17179. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17180. //clear accumulated errors
  17181. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17182. return successful;
  17183. };
  17184. /** @hidden */
  17185. Engine.prototype._getWebGLTextureType = function (type) {
  17186. if (type === Engine.TEXTURETYPE_FLOAT) {
  17187. return this._gl.FLOAT;
  17188. }
  17189. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17190. // Add Half Float Constant.
  17191. return this._gl.HALF_FLOAT_OES;
  17192. }
  17193. return this._gl.UNSIGNED_BYTE;
  17194. };
  17195. ;
  17196. Engine.prototype._getInternalFormat = function (format) {
  17197. var internalFormat = this._gl.RGBA;
  17198. switch (format) {
  17199. case Engine.TEXTUREFORMAT_ALPHA:
  17200. internalFormat = this._gl.ALPHA;
  17201. break;
  17202. case Engine.TEXTUREFORMAT_LUMINANCE:
  17203. internalFormat = this._gl.LUMINANCE;
  17204. break;
  17205. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17206. internalFormat = this._gl.LUMINANCE_ALPHA;
  17207. break;
  17208. case Engine.TEXTUREFORMAT_RGB:
  17209. internalFormat = this._gl.RGB;
  17210. break;
  17211. case Engine.TEXTUREFORMAT_RGBA:
  17212. internalFormat = this._gl.RGBA;
  17213. break;
  17214. case Engine.TEXTUREFORMAT_R:
  17215. internalFormat = this._gl.RED;
  17216. break;
  17217. case Engine.TEXTUREFORMAT_RG:
  17218. internalFormat = this._gl.RG;
  17219. break;
  17220. }
  17221. return internalFormat;
  17222. };
  17223. /** @hidden */
  17224. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17225. if (this._webGLVersion === 1) {
  17226. if (format !== undefined) {
  17227. switch (format) {
  17228. case Engine.TEXTUREFORMAT_LUMINANCE:
  17229. return this._gl.LUMINANCE;
  17230. case Engine.TEXTUREFORMAT_ALPHA:
  17231. return this._gl.ALPHA;
  17232. }
  17233. }
  17234. return this._gl.RGBA;
  17235. }
  17236. if (type === Engine.TEXTURETYPE_FLOAT) {
  17237. if (format !== undefined) {
  17238. switch (format) {
  17239. case Engine.TEXTUREFORMAT_R:
  17240. return this._gl.R32F;
  17241. case Engine.TEXTUREFORMAT_RG:
  17242. return this._gl.RG32F;
  17243. case Engine.TEXTUREFORMAT_RGB:
  17244. return this._gl.RGB32F;
  17245. }
  17246. }
  17247. return this._gl.RGBA32F;
  17248. }
  17249. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17250. if (format) {
  17251. switch (format) {
  17252. case Engine.TEXTUREFORMAT_R:
  17253. return this._gl.R16F;
  17254. case Engine.TEXTUREFORMAT_RG:
  17255. return this._gl.RG16F;
  17256. case Engine.TEXTUREFORMAT_RGB:
  17257. return this._gl.RGB16F;
  17258. }
  17259. }
  17260. return this._gl.RGBA16F;
  17261. }
  17262. if (format !== undefined) {
  17263. switch (format) {
  17264. case Engine.TEXTUREFORMAT_LUMINANCE:
  17265. return this._gl.LUMINANCE;
  17266. case Engine.TEXTUREFORMAT_RGB:
  17267. return this._gl.RGB;
  17268. case Engine.TEXTUREFORMAT_R:
  17269. return this._gl.R8;
  17270. case Engine.TEXTUREFORMAT_RG:
  17271. return this._gl.RG8;
  17272. case Engine.TEXTUREFORMAT_ALPHA:
  17273. return this._gl.ALPHA;
  17274. }
  17275. }
  17276. return this._gl.RGBA;
  17277. };
  17278. ;
  17279. /** @hidden */
  17280. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17281. if (type === Engine.TEXTURETYPE_FLOAT) {
  17282. return this._gl.RGBA32F;
  17283. }
  17284. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17285. return this._gl.RGBA16F;
  17286. }
  17287. return this._gl.RGBA8;
  17288. };
  17289. ;
  17290. /**
  17291. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17292. * @return the new query
  17293. */
  17294. Engine.prototype.createQuery = function () {
  17295. return this._gl.createQuery();
  17296. };
  17297. /**
  17298. * Delete and release a webGL query
  17299. * @param query defines the query to delete
  17300. * @return the current engine
  17301. */
  17302. Engine.prototype.deleteQuery = function (query) {
  17303. this._gl.deleteQuery(query);
  17304. return this;
  17305. };
  17306. /**
  17307. * Check if a given query has resolved and got its value
  17308. * @param query defines the query to check
  17309. * @returns true if the query got its value
  17310. */
  17311. Engine.prototype.isQueryResultAvailable = function (query) {
  17312. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17313. };
  17314. /**
  17315. * Gets the value of a given query
  17316. * @param query defines the query to check
  17317. * @returns the value of the query
  17318. */
  17319. Engine.prototype.getQueryResult = function (query) {
  17320. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17321. };
  17322. /**
  17323. * Initiates an occlusion query
  17324. * @param algorithmType defines the algorithm to use
  17325. * @param query defines the query to use
  17326. * @returns the current engine
  17327. * @see http://doc.babylonjs.com/features/occlusionquery
  17328. */
  17329. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17330. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17331. this._gl.beginQuery(glAlgorithm, query);
  17332. return this;
  17333. };
  17334. /**
  17335. * Ends an occlusion query
  17336. * @see http://doc.babylonjs.com/features/occlusionquery
  17337. * @param algorithmType defines the algorithm to use
  17338. * @returns the current engine
  17339. */
  17340. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17341. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17342. this._gl.endQuery(glAlgorithm);
  17343. return this;
  17344. };
  17345. /* Time queries */
  17346. Engine.prototype._createTimeQuery = function () {
  17347. var timerQuery = this._caps.timerQuery;
  17348. if (timerQuery.createQueryEXT) {
  17349. return timerQuery.createQueryEXT();
  17350. }
  17351. return this.createQuery();
  17352. };
  17353. Engine.prototype._deleteTimeQuery = function (query) {
  17354. var timerQuery = this._caps.timerQuery;
  17355. if (timerQuery.deleteQueryEXT) {
  17356. timerQuery.deleteQueryEXT(query);
  17357. return;
  17358. }
  17359. this.deleteQuery(query);
  17360. };
  17361. Engine.prototype._getTimeQueryResult = function (query) {
  17362. var timerQuery = this._caps.timerQuery;
  17363. if (timerQuery.getQueryObjectEXT) {
  17364. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17365. }
  17366. return this.getQueryResult(query);
  17367. };
  17368. Engine.prototype._getTimeQueryAvailability = function (query) {
  17369. var timerQuery = this._caps.timerQuery;
  17370. if (timerQuery.getQueryObjectEXT) {
  17371. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17372. }
  17373. return this.isQueryResultAvailable(query);
  17374. };
  17375. /**
  17376. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17377. * Please note that only one query can be issued at a time
  17378. * @returns a time token used to track the time span
  17379. */
  17380. Engine.prototype.startTimeQuery = function () {
  17381. var timerQuery = this._caps.timerQuery;
  17382. if (!timerQuery) {
  17383. return null;
  17384. }
  17385. var token = new BABYLON._TimeToken();
  17386. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17387. if (this._caps.canUseTimestampForTimerQuery) {
  17388. token._startTimeQuery = this._createTimeQuery();
  17389. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17390. }
  17391. else {
  17392. if (this._currentNonTimestampToken) {
  17393. return this._currentNonTimestampToken;
  17394. }
  17395. token._timeElapsedQuery = this._createTimeQuery();
  17396. if (timerQuery.beginQueryEXT) {
  17397. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17398. }
  17399. else {
  17400. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17401. }
  17402. this._currentNonTimestampToken = token;
  17403. }
  17404. return token;
  17405. };
  17406. /**
  17407. * Ends a time query
  17408. * @param token defines the token used to measure the time span
  17409. * @returns the time spent (in ns)
  17410. */
  17411. Engine.prototype.endTimeQuery = function (token) {
  17412. var timerQuery = this._caps.timerQuery;
  17413. if (!timerQuery || !token) {
  17414. return -1;
  17415. }
  17416. if (this._caps.canUseTimestampForTimerQuery) {
  17417. if (!token._startTimeQuery) {
  17418. return -1;
  17419. }
  17420. if (!token._endTimeQuery) {
  17421. token._endTimeQuery = this._createTimeQuery();
  17422. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17423. }
  17424. }
  17425. else if (!token._timeElapsedQueryEnded) {
  17426. if (!token._timeElapsedQuery) {
  17427. return -1;
  17428. }
  17429. if (timerQuery.endQueryEXT) {
  17430. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17431. }
  17432. else {
  17433. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17434. }
  17435. token._timeElapsedQueryEnded = true;
  17436. }
  17437. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17438. var available = false;
  17439. if (token._endTimeQuery) {
  17440. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17441. }
  17442. else if (token._timeElapsedQuery) {
  17443. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17444. }
  17445. if (available && !disjoint) {
  17446. var result = 0;
  17447. if (this._caps.canUseTimestampForTimerQuery) {
  17448. if (!token._startTimeQuery || !token._endTimeQuery) {
  17449. return -1;
  17450. }
  17451. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17452. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17453. result = timeEnd - timeStart;
  17454. this._deleteTimeQuery(token._startTimeQuery);
  17455. this._deleteTimeQuery(token._endTimeQuery);
  17456. token._startTimeQuery = null;
  17457. token._endTimeQuery = null;
  17458. }
  17459. else {
  17460. if (!token._timeElapsedQuery) {
  17461. return -1;
  17462. }
  17463. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17464. this._deleteTimeQuery(token._timeElapsedQuery);
  17465. token._timeElapsedQuery = null;
  17466. token._timeElapsedQueryEnded = false;
  17467. this._currentNonTimestampToken = null;
  17468. }
  17469. return result;
  17470. }
  17471. return -1;
  17472. };
  17473. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17474. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17475. };
  17476. // Transform feedback
  17477. /**
  17478. * Creates a webGL transform feedback object
  17479. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17480. * @returns the webGL transform feedback object
  17481. */
  17482. Engine.prototype.createTransformFeedback = function () {
  17483. return this._gl.createTransformFeedback();
  17484. };
  17485. /**
  17486. * Delete a webGL transform feedback object
  17487. * @param value defines the webGL transform feedback object to delete
  17488. */
  17489. Engine.prototype.deleteTransformFeedback = function (value) {
  17490. this._gl.deleteTransformFeedback(value);
  17491. };
  17492. /**
  17493. * Bind a webGL transform feedback object to the webgl context
  17494. * @param value defines the webGL transform feedback object to bind
  17495. */
  17496. Engine.prototype.bindTransformFeedback = function (value) {
  17497. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17498. };
  17499. /**
  17500. * Begins a transform feedback operation
  17501. * @param usePoints defines if points or triangles must be used
  17502. */
  17503. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17504. if (usePoints === void 0) { usePoints = true; }
  17505. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17506. };
  17507. /**
  17508. * Ends a transform feedback operation
  17509. */
  17510. Engine.prototype.endTransformFeedback = function () {
  17511. this._gl.endTransformFeedback();
  17512. };
  17513. /**
  17514. * Specify the varyings to use with transform feedback
  17515. * @param program defines the associated webGL program
  17516. * @param value defines the list of strings representing the varying names
  17517. */
  17518. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17519. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17520. };
  17521. /**
  17522. * Bind a webGL buffer for a transform feedback operation
  17523. * @param value defines the webGL buffer to bind
  17524. */
  17525. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17526. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17527. };
  17528. /** @hidden */
  17529. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17530. var _this = this;
  17531. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17532. this._activeRequests.push(request);
  17533. request.onCompleteObservable.add(function (request) {
  17534. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17535. });
  17536. return request;
  17537. };
  17538. /** @hidden */
  17539. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17540. var _this = this;
  17541. return new Promise(function (resolve, reject) {
  17542. _this._loadFile(url, function (data) {
  17543. resolve(data);
  17544. }, undefined, database, useArrayBuffer, function (request, exception) {
  17545. reject(exception);
  17546. });
  17547. });
  17548. };
  17549. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17550. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17551. var onload = function (data) {
  17552. loadedFiles[index] = data;
  17553. loadedFiles._internalCount++;
  17554. if (loadedFiles._internalCount === 6) {
  17555. onfinish(loadedFiles);
  17556. }
  17557. };
  17558. var onerror = function (request, exception) {
  17559. if (onErrorCallBack && request) {
  17560. onErrorCallBack(request.status + " " + request.statusText, exception);
  17561. }
  17562. };
  17563. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17564. };
  17565. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17566. if (onError === void 0) { onError = null; }
  17567. var loadedFiles = [];
  17568. loadedFiles._internalCount = 0;
  17569. for (var index = 0; index < 6; index++) {
  17570. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17571. }
  17572. };
  17573. // Statics
  17574. /**
  17575. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17576. * @returns true if the engine can be created
  17577. * @ignorenaming
  17578. */
  17579. Engine.isSupported = function () {
  17580. try {
  17581. var tempcanvas = document.createElement("canvas");
  17582. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17583. return gl != null && !!window.WebGLRenderingContext;
  17584. }
  17585. catch (e) {
  17586. return false;
  17587. }
  17588. };
  17589. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17590. Engine.ExceptionList = [
  17591. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17592. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17593. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17594. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17595. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17596. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17597. ];
  17598. /** Gets the list of created engines */
  17599. Engine.Instances = new Array();
  17600. // Const statics
  17601. Engine._ALPHA_DISABLE = 0;
  17602. Engine._ALPHA_ADD = 1;
  17603. Engine._ALPHA_COMBINE = 2;
  17604. Engine._ALPHA_SUBTRACT = 3;
  17605. Engine._ALPHA_MULTIPLY = 4;
  17606. Engine._ALPHA_MAXIMIZED = 5;
  17607. Engine._ALPHA_ONEONE = 6;
  17608. Engine._ALPHA_PREMULTIPLIED = 7;
  17609. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17610. Engine._ALPHA_INTERPOLATE = 9;
  17611. Engine._ALPHA_SCREENMODE = 10;
  17612. Engine._DELAYLOADSTATE_NONE = 0;
  17613. Engine._DELAYLOADSTATE_LOADED = 1;
  17614. Engine._DELAYLOADSTATE_LOADING = 2;
  17615. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17616. Engine._TEXTUREFORMAT_ALPHA = 0;
  17617. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17618. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17619. Engine._TEXTUREFORMAT_RGB = 4;
  17620. Engine._TEXTUREFORMAT_RGBA = 5;
  17621. Engine._TEXTUREFORMAT_R = 6;
  17622. Engine._TEXTUREFORMAT_RG = 7;
  17623. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17624. Engine._TEXTURETYPE_FLOAT = 1;
  17625. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17626. // Depht or Stencil test Constants.
  17627. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17628. 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.
  17629. 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.
  17630. 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.
  17631. 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.
  17632. 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.
  17633. 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.
  17634. 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.
  17635. // Stencil Actions Constants.
  17636. Engine._KEEP = 0x1E00;
  17637. Engine._REPLACE = 0x1E01;
  17638. Engine._INCR = 0x1E02;
  17639. Engine._DECR = 0x1E03;
  17640. Engine._INVERT = 0x150A;
  17641. Engine._INCR_WRAP = 0x8507;
  17642. Engine._DECR_WRAP = 0x8508;
  17643. // Texture rescaling mode
  17644. Engine._SCALEMODE_FLOOR = 1;
  17645. Engine._SCALEMODE_NEAREST = 2;
  17646. Engine._SCALEMODE_CEILING = 3;
  17647. // Updatable statics so stick with vars here
  17648. /**
  17649. * Gets or sets the epsilon value used by collision engine
  17650. */
  17651. Engine.CollisionsEpsilon = 0.001;
  17652. /**
  17653. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17654. */
  17655. Engine.CodeRepository = "src/";
  17656. /**
  17657. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17658. */
  17659. Engine.ShadersRepository = "src/Shaders/";
  17660. return Engine;
  17661. }());
  17662. BABYLON.Engine = Engine;
  17663. })(BABYLON || (BABYLON = {}));
  17664. //# sourceMappingURL=babylon.engine.js.map
  17665. var BABYLON;
  17666. (function (BABYLON) {
  17667. /**
  17668. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17669. */
  17670. var Node = /** @class */ (function () {
  17671. /**
  17672. * Creates a new Node
  17673. * @param {string} name - the name and id to be given to this node
  17674. * @param {BABYLON.Scene} the scene this node will be added to
  17675. */
  17676. function Node(name, scene) {
  17677. if (scene === void 0) { scene = null; }
  17678. /**
  17679. * Gets or sets a string used to store user defined state for the node
  17680. */
  17681. this.state = "";
  17682. /**
  17683. * Gets or sets an object used to store user defined information for the node
  17684. */
  17685. this.metadata = null;
  17686. /**
  17687. * Gets or sets a boolean used to define if the node must be serialized
  17688. */
  17689. this.doNotSerialize = false;
  17690. /** @hidden */
  17691. this._isDisposed = false;
  17692. /**
  17693. * Gets a list of Animations associated with the node
  17694. */
  17695. this.animations = new Array();
  17696. this._ranges = {};
  17697. this._isEnabled = true;
  17698. this._isReady = true;
  17699. /** @hidden */
  17700. this._currentRenderId = -1;
  17701. this._parentRenderId = -1;
  17702. this._childRenderId = -1;
  17703. this._animationPropertiesOverride = null;
  17704. /**
  17705. * An event triggered when the mesh is disposed
  17706. */
  17707. this.onDisposeObservable = new BABYLON.Observable();
  17708. // Behaviors
  17709. this._behaviors = new Array();
  17710. this.name = name;
  17711. this.id = name;
  17712. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17713. this.uniqueId = this._scene.getUniqueId();
  17714. this._initCache();
  17715. }
  17716. /**
  17717. * Gets a boolean indicating if the node has been disposed
  17718. * @returns true if the node was disposed
  17719. */
  17720. Node.prototype.isDisposed = function () {
  17721. return this._isDisposed;
  17722. };
  17723. Object.defineProperty(Node.prototype, "parent", {
  17724. get: function () {
  17725. return this._parentNode;
  17726. },
  17727. /**
  17728. * Gets or sets the parent of the node
  17729. */
  17730. set: function (parent) {
  17731. if (this._parentNode === parent) {
  17732. return;
  17733. }
  17734. // Remove self from list of children of parent
  17735. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17736. var index = this._parentNode._children.indexOf(this);
  17737. if (index !== -1) {
  17738. this._parentNode._children.splice(index, 1);
  17739. }
  17740. }
  17741. // Store new parent
  17742. this._parentNode = parent;
  17743. // Add as child to new parent
  17744. if (this._parentNode) {
  17745. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17746. this._parentNode._children = new Array();
  17747. }
  17748. this._parentNode._children.push(this);
  17749. }
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17755. /**
  17756. * Gets or sets the animation properties override
  17757. */
  17758. get: function () {
  17759. if (!this._animationPropertiesOverride) {
  17760. return this._scene.animationPropertiesOverride;
  17761. }
  17762. return this._animationPropertiesOverride;
  17763. },
  17764. set: function (value) {
  17765. this._animationPropertiesOverride = value;
  17766. },
  17767. enumerable: true,
  17768. configurable: true
  17769. });
  17770. /**
  17771. * Gets a string idenfifying the name of the class
  17772. * @returns "Node" string
  17773. */
  17774. Node.prototype.getClassName = function () {
  17775. return "Node";
  17776. };
  17777. Object.defineProperty(Node.prototype, "onDispose", {
  17778. /**
  17779. * Sets a callback that will be raised when the node will be disposed
  17780. */
  17781. set: function (callback) {
  17782. if (this._onDisposeObserver) {
  17783. this.onDisposeObservable.remove(this._onDisposeObserver);
  17784. }
  17785. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17786. },
  17787. enumerable: true,
  17788. configurable: true
  17789. });
  17790. /**
  17791. * Gets the scene of the node
  17792. * @returns a {BABYLON.Scene}
  17793. */
  17794. Node.prototype.getScene = function () {
  17795. return this._scene;
  17796. };
  17797. /**
  17798. * Gets the engine of the node
  17799. * @returns a {BABYLON.Engine}
  17800. */
  17801. Node.prototype.getEngine = function () {
  17802. return this._scene.getEngine();
  17803. };
  17804. /**
  17805. * Attach a behavior to the node
  17806. * @see http://doc.babylonjs.com/features/behaviour
  17807. * @param behavior defines the behavior to attach
  17808. * @returns the current Node
  17809. */
  17810. Node.prototype.addBehavior = function (behavior) {
  17811. var _this = this;
  17812. var index = this._behaviors.indexOf(behavior);
  17813. if (index !== -1) {
  17814. return this;
  17815. }
  17816. behavior.init();
  17817. if (this._scene.isLoading) {
  17818. // We defer the attach when the scene will be loaded
  17819. this._scene.onDataLoadedObservable.addOnce(function () {
  17820. behavior.attach(_this);
  17821. });
  17822. }
  17823. else {
  17824. behavior.attach(this);
  17825. }
  17826. this._behaviors.push(behavior);
  17827. return this;
  17828. };
  17829. /**
  17830. * Remove an attached behavior
  17831. * @see http://doc.babylonjs.com/features/behaviour
  17832. * @param behavior defines the behavior to attach
  17833. * @returns the current Node
  17834. */
  17835. Node.prototype.removeBehavior = function (behavior) {
  17836. var index = this._behaviors.indexOf(behavior);
  17837. if (index === -1) {
  17838. return this;
  17839. }
  17840. this._behaviors[index].detach();
  17841. this._behaviors.splice(index, 1);
  17842. return this;
  17843. };
  17844. Object.defineProperty(Node.prototype, "behaviors", {
  17845. /**
  17846. * Gets the list of attached behaviors
  17847. * @see http://doc.babylonjs.com/features/behaviour
  17848. */
  17849. get: function () {
  17850. return this._behaviors;
  17851. },
  17852. enumerable: true,
  17853. configurable: true
  17854. });
  17855. /**
  17856. * Gets an attached behavior by name
  17857. * @param name defines the name of the behavior to look for
  17858. * @see http://doc.babylonjs.com/features/behaviour
  17859. * @returns null if behavior was not found else the requested behavior
  17860. */
  17861. Node.prototype.getBehaviorByName = function (name) {
  17862. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17863. var behavior = _a[_i];
  17864. if (behavior.name === name) {
  17865. return behavior;
  17866. }
  17867. }
  17868. return null;
  17869. };
  17870. /**
  17871. * Returns the world matrix of the node
  17872. * @returns a matrix containing the node's world matrix
  17873. */
  17874. Node.prototype.getWorldMatrix = function () {
  17875. return BABYLON.Matrix.Identity();
  17876. };
  17877. /** @hidden */
  17878. Node.prototype._getWorldMatrixDeterminant = function () {
  17879. return 1;
  17880. };
  17881. // override it in derived class if you add new variables to the cache
  17882. // and call the parent class method
  17883. /** @hidden */
  17884. Node.prototype._initCache = function () {
  17885. this._cache = {};
  17886. this._cache.parent = undefined;
  17887. };
  17888. /** @hidden */
  17889. Node.prototype.updateCache = function (force) {
  17890. if (!force && this.isSynchronized())
  17891. return;
  17892. this._cache.parent = this.parent;
  17893. this._updateCache();
  17894. };
  17895. // override it in derived class if you add new variables to the cache
  17896. // and call the parent class method if !ignoreParentClass
  17897. /** @hidden */
  17898. Node.prototype._updateCache = function (ignoreParentClass) {
  17899. };
  17900. // override it in derived class if you add new variables to the cache
  17901. /** @hidden */
  17902. Node.prototype._isSynchronized = function () {
  17903. return true;
  17904. };
  17905. /** @hidden */
  17906. Node.prototype._markSyncedWithParent = function () {
  17907. if (this.parent) {
  17908. this._parentRenderId = this.parent._childRenderId;
  17909. }
  17910. };
  17911. /** @hidden */
  17912. Node.prototype.isSynchronizedWithParent = function () {
  17913. if (!this.parent) {
  17914. return true;
  17915. }
  17916. if (this._parentRenderId !== this.parent._childRenderId) {
  17917. return false;
  17918. }
  17919. return this.parent.isSynchronized();
  17920. };
  17921. /** @hidden */
  17922. Node.prototype.isSynchronized = function (updateCache) {
  17923. var check = this.hasNewParent();
  17924. check = check || !this.isSynchronizedWithParent();
  17925. check = check || !this._isSynchronized();
  17926. if (updateCache)
  17927. this.updateCache(true);
  17928. return !check;
  17929. };
  17930. /** @hidden */
  17931. Node.prototype.hasNewParent = function (update) {
  17932. if (this._cache.parent === this.parent)
  17933. return false;
  17934. if (update)
  17935. this._cache.parent = this.parent;
  17936. return true;
  17937. };
  17938. /**
  17939. * Is this node ready to be used/rendered
  17940. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17941. * @return true if the node is ready
  17942. */
  17943. Node.prototype.isReady = function (completeCheck) {
  17944. if (completeCheck === void 0) { completeCheck = false; }
  17945. return this._isReady;
  17946. };
  17947. /**
  17948. * Is this node enabled?
  17949. * 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
  17950. * @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
  17951. * @return whether this node (and its parent) is enabled
  17952. */
  17953. Node.prototype.isEnabled = function (checkAncestors) {
  17954. if (checkAncestors === void 0) { checkAncestors = true; }
  17955. if (checkAncestors === false) {
  17956. return this._isEnabled;
  17957. }
  17958. if (this._isEnabled === false) {
  17959. return false;
  17960. }
  17961. if (this.parent !== undefined && this.parent !== null) {
  17962. return this.parent.isEnabled(checkAncestors);
  17963. }
  17964. return true;
  17965. };
  17966. /**
  17967. * Set the enabled state of this node
  17968. * @param value defines the new enabled state
  17969. */
  17970. Node.prototype.setEnabled = function (value) {
  17971. this._isEnabled = value;
  17972. };
  17973. /**
  17974. * Is this node a descendant of the given node?
  17975. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17976. * @param ancestor defines the parent node to inspect
  17977. * @returns a boolean indicating if this node is a descendant of the given node
  17978. */
  17979. Node.prototype.isDescendantOf = function (ancestor) {
  17980. if (this.parent) {
  17981. if (this.parent === ancestor) {
  17982. return true;
  17983. }
  17984. return this.parent.isDescendantOf(ancestor);
  17985. }
  17986. return false;
  17987. };
  17988. /** @hidden */
  17989. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17990. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17991. if (!this._children) {
  17992. return;
  17993. }
  17994. for (var index = 0; index < this._children.length; index++) {
  17995. var item = this._children[index];
  17996. if (!predicate || predicate(item)) {
  17997. results.push(item);
  17998. }
  17999. if (!directDescendantsOnly) {
  18000. item._getDescendants(results, false, predicate);
  18001. }
  18002. }
  18003. };
  18004. /**
  18005. * Will return all nodes that have this node as ascendant
  18006. * @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
  18007. * @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
  18008. * @return all children nodes of all types
  18009. */
  18010. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18011. var results = new Array();
  18012. this._getDescendants(results, directDescendantsOnly, predicate);
  18013. return results;
  18014. };
  18015. /**
  18016. * Get all child-meshes of this node
  18017. * @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
  18018. * @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
  18019. * @returns an array of {BABYLON.AbstractMesh}
  18020. */
  18021. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18022. var results = [];
  18023. this._getDescendants(results, directDescendantsOnly, function (node) {
  18024. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18025. });
  18026. return results;
  18027. };
  18028. /**
  18029. * Get all child-transformNodes of this node
  18030. * @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
  18031. * @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
  18032. * @returns an array of {BABYLON.TransformNode}
  18033. */
  18034. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18035. var results = [];
  18036. this._getDescendants(results, directDescendantsOnly, function (node) {
  18037. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18038. });
  18039. return results;
  18040. };
  18041. /**
  18042. * Get all direct children of this node
  18043. * @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
  18044. * @returns an array of {BABYLON.Node}
  18045. */
  18046. Node.prototype.getChildren = function (predicate) {
  18047. return this.getDescendants(true, predicate);
  18048. };
  18049. /** @hidden */
  18050. Node.prototype._setReady = function (state) {
  18051. if (state === this._isReady) {
  18052. return;
  18053. }
  18054. if (!state) {
  18055. this._isReady = false;
  18056. return;
  18057. }
  18058. if (this.onReady) {
  18059. this.onReady(this);
  18060. }
  18061. this._isReady = true;
  18062. };
  18063. /**
  18064. * Get an animation by name
  18065. * @param name defines the name of the animation to look for
  18066. * @returns null if not found else the requested animation
  18067. */
  18068. Node.prototype.getAnimationByName = function (name) {
  18069. for (var i = 0; i < this.animations.length; i++) {
  18070. var animation = this.animations[i];
  18071. if (animation.name === name) {
  18072. return animation;
  18073. }
  18074. }
  18075. return null;
  18076. };
  18077. /**
  18078. * Creates an animation range for this node
  18079. * @param name defines the name of the range
  18080. * @param from defines the starting key
  18081. * @param to defines the end key
  18082. */
  18083. Node.prototype.createAnimationRange = function (name, from, to) {
  18084. // check name not already in use
  18085. if (!this._ranges[name]) {
  18086. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18087. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18088. if (this.animations[i]) {
  18089. this.animations[i].createRange(name, from, to);
  18090. }
  18091. }
  18092. }
  18093. };
  18094. /**
  18095. * Delete a specific animation range
  18096. * @param name defines the name of the range to delete
  18097. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18098. */
  18099. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18100. if (deleteFrames === void 0) { deleteFrames = true; }
  18101. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18102. if (this.animations[i]) {
  18103. this.animations[i].deleteRange(name, deleteFrames);
  18104. }
  18105. }
  18106. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18107. };
  18108. /**
  18109. * Get an animation range by name
  18110. * @param name defines the name of the animation range to look for
  18111. * @returns null if not found else the requested animation range
  18112. */
  18113. Node.prototype.getAnimationRange = function (name) {
  18114. return this._ranges[name];
  18115. };
  18116. /**
  18117. * Will start the animation sequence
  18118. * @param name defines the range frames for animation sequence
  18119. * @param loop defines if the animation should loop (false by default)
  18120. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18121. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18122. * @returns the object created for this animation. If range does not exist, it will return null
  18123. */
  18124. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18125. var range = this.getAnimationRange(name);
  18126. if (!range) {
  18127. return null;
  18128. }
  18129. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18130. };
  18131. /**
  18132. * Serialize animation ranges into a JSON compatible object
  18133. * @returns serialization object
  18134. */
  18135. Node.prototype.serializeAnimationRanges = function () {
  18136. var serializationRanges = [];
  18137. for (var name in this._ranges) {
  18138. var localRange = this._ranges[name];
  18139. if (!localRange) {
  18140. continue;
  18141. }
  18142. var range = {};
  18143. range.name = name;
  18144. range.from = localRange.from;
  18145. range.to = localRange.to;
  18146. serializationRanges.push(range);
  18147. }
  18148. return serializationRanges;
  18149. };
  18150. /**
  18151. * Computes the world matrix of the node
  18152. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18153. * @returns the world matrix
  18154. */
  18155. Node.prototype.computeWorldMatrix = function (force) {
  18156. return BABYLON.Matrix.Identity();
  18157. };
  18158. /**
  18159. * Releases resources associated with this node.
  18160. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18161. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18162. */
  18163. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18164. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18165. if (!doNotRecurse) {
  18166. var nodes = this.getDescendants(true);
  18167. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18168. var node = nodes_1[_i];
  18169. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18170. }
  18171. }
  18172. else {
  18173. var transformNodes = this.getChildTransformNodes(true);
  18174. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18175. var transformNode = transformNodes_1[_a];
  18176. transformNode.parent = null;
  18177. transformNode.computeWorldMatrix(true);
  18178. }
  18179. }
  18180. this.parent = null;
  18181. // Callback
  18182. this.onDisposeObservable.notifyObservers(this);
  18183. this.onDisposeObservable.clear();
  18184. // Behaviors
  18185. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18186. var behavior = _c[_b];
  18187. behavior.detach();
  18188. }
  18189. this._behaviors = [];
  18190. this._isDisposed = true;
  18191. };
  18192. /**
  18193. * Parse animation range data from a serialization object and store them into a given node
  18194. * @param node defines where to store the animation ranges
  18195. * @param parsedNode defines the serialization object to read data from
  18196. * @param scene defines the hosting scene
  18197. */
  18198. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18199. if (parsedNode.ranges) {
  18200. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18201. var data = parsedNode.ranges[index];
  18202. node.createAnimationRange(data.name, data.from, data.to);
  18203. }
  18204. }
  18205. };
  18206. __decorate([
  18207. BABYLON.serialize()
  18208. ], Node.prototype, "name", void 0);
  18209. __decorate([
  18210. BABYLON.serialize()
  18211. ], Node.prototype, "id", void 0);
  18212. __decorate([
  18213. BABYLON.serialize()
  18214. ], Node.prototype, "uniqueId", void 0);
  18215. __decorate([
  18216. BABYLON.serialize()
  18217. ], Node.prototype, "state", void 0);
  18218. __decorate([
  18219. BABYLON.serialize()
  18220. ], Node.prototype, "metadata", void 0);
  18221. return Node;
  18222. }());
  18223. BABYLON.Node = Node;
  18224. })(BABYLON || (BABYLON = {}));
  18225. //# sourceMappingURL=babylon.node.js.map
  18226. var BABYLON;
  18227. (function (BABYLON) {
  18228. var BoundingSphere = /** @class */ (function () {
  18229. /**
  18230. * Creates a new bounding sphere
  18231. * @param min defines the minimum vector (in local space)
  18232. * @param max defines the maximum vector (in local space)
  18233. */
  18234. function BoundingSphere(min, max) {
  18235. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18236. this.reConstruct(min, max);
  18237. }
  18238. /**
  18239. * Recreates the entire bounding sphere from scratch
  18240. * @param min defines the new minimum vector (in local space)
  18241. * @param max defines the new maximum vector (in local space)
  18242. */
  18243. BoundingSphere.prototype.reConstruct = function (min, max) {
  18244. this.minimum = min.clone();
  18245. this.maximum = max.clone();
  18246. var distance = BABYLON.Vector3.Distance(min, max);
  18247. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18248. this.radius = distance * 0.5;
  18249. this.centerWorld = BABYLON.Vector3.Zero();
  18250. this._update(BABYLON.Matrix.Identity());
  18251. };
  18252. // Methods
  18253. BoundingSphere.prototype._update = function (world) {
  18254. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18255. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18256. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18257. };
  18258. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18259. for (var i = 0; i < 6; i++) {
  18260. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18261. return false;
  18262. }
  18263. return true;
  18264. };
  18265. BoundingSphere.prototype.intersectsPoint = function (point) {
  18266. var x = this.centerWorld.x - point.x;
  18267. var y = this.centerWorld.y - point.y;
  18268. var z = this.centerWorld.z - point.z;
  18269. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18270. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18271. return false;
  18272. return true;
  18273. };
  18274. // Statics
  18275. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18276. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18277. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18278. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18279. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18280. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18281. return false;
  18282. return true;
  18283. };
  18284. return BoundingSphere;
  18285. }());
  18286. BABYLON.BoundingSphere = BoundingSphere;
  18287. })(BABYLON || (BABYLON = {}));
  18288. //# sourceMappingURL=babylon.boundingSphere.js.map
  18289. var BABYLON;
  18290. (function (BABYLON) {
  18291. var BoundingBox = /** @class */ (function () {
  18292. /**
  18293. * Creates a new bounding box
  18294. * @param min defines the minimum vector (in local space)
  18295. * @param max defines the maximum vector (in local space)
  18296. */
  18297. function BoundingBox(min, max) {
  18298. this.vectorsWorld = new Array();
  18299. this.reConstruct(min, max);
  18300. }
  18301. // Methods
  18302. /**
  18303. * Recreates the entire bounding box from scratch
  18304. * @param min defines the new minimum vector (in local space)
  18305. * @param max defines the new maximum vector (in local space)
  18306. */
  18307. BoundingBox.prototype.reConstruct = function (min, max) {
  18308. this.minimum = min.clone();
  18309. this.maximum = max.clone();
  18310. // Bounding vectors
  18311. this.vectors = new Array();
  18312. this.vectors.push(this.minimum.clone());
  18313. this.vectors.push(this.maximum.clone());
  18314. this.vectors.push(this.minimum.clone());
  18315. this.vectors[2].x = this.maximum.x;
  18316. this.vectors.push(this.minimum.clone());
  18317. this.vectors[3].y = this.maximum.y;
  18318. this.vectors.push(this.minimum.clone());
  18319. this.vectors[4].z = this.maximum.z;
  18320. this.vectors.push(this.maximum.clone());
  18321. this.vectors[5].z = this.minimum.z;
  18322. this.vectors.push(this.maximum.clone());
  18323. this.vectors[6].x = this.minimum.x;
  18324. this.vectors.push(this.maximum.clone());
  18325. this.vectors[7].y = this.minimum.y;
  18326. // OBB
  18327. this.center = this.maximum.add(this.minimum).scale(0.5);
  18328. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18329. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18330. // World
  18331. for (var index = 0; index < this.vectors.length; index++) {
  18332. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18333. }
  18334. this.minimumWorld = BABYLON.Vector3.Zero();
  18335. this.maximumWorld = BABYLON.Vector3.Zero();
  18336. this.centerWorld = BABYLON.Vector3.Zero();
  18337. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18338. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18339. };
  18340. BoundingBox.prototype.getWorldMatrix = function () {
  18341. return this._worldMatrix;
  18342. };
  18343. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18344. this._worldMatrix.copyFrom(matrix);
  18345. return this;
  18346. };
  18347. BoundingBox.prototype._update = function (world) {
  18348. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18349. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18350. for (var index = 0; index < this.vectors.length; index++) {
  18351. var v = this.vectorsWorld[index];
  18352. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18353. if (v.x < this.minimumWorld.x)
  18354. this.minimumWorld.x = v.x;
  18355. if (v.y < this.minimumWorld.y)
  18356. this.minimumWorld.y = v.y;
  18357. if (v.z < this.minimumWorld.z)
  18358. this.minimumWorld.z = v.z;
  18359. if (v.x > this.maximumWorld.x)
  18360. this.maximumWorld.x = v.x;
  18361. if (v.y > this.maximumWorld.y)
  18362. this.maximumWorld.y = v.y;
  18363. if (v.z > this.maximumWorld.z)
  18364. this.maximumWorld.z = v.z;
  18365. }
  18366. // Extend
  18367. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18368. this.extendSizeWorld.scaleInPlace(0.5);
  18369. // OBB
  18370. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18371. this.centerWorld.scaleInPlace(0.5);
  18372. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18373. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18374. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18375. this._worldMatrix = world;
  18376. };
  18377. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18378. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18379. };
  18380. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18381. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18382. };
  18383. BoundingBox.prototype.intersectsPoint = function (point) {
  18384. var delta = -BABYLON.Epsilon;
  18385. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18386. return false;
  18387. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18388. return false;
  18389. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18390. return false;
  18391. return true;
  18392. };
  18393. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18394. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18395. };
  18396. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18397. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18398. return false;
  18399. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18400. return false;
  18401. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18402. return false;
  18403. return true;
  18404. };
  18405. // Statics
  18406. BoundingBox.Intersects = function (box0, box1) {
  18407. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18408. return false;
  18409. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18410. return false;
  18411. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18412. return false;
  18413. return true;
  18414. };
  18415. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18416. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18417. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18418. return (num <= (sphereRadius * sphereRadius));
  18419. };
  18420. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18421. for (var p = 0; p < 6; p++) {
  18422. for (var i = 0; i < 8; i++) {
  18423. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18424. return false;
  18425. }
  18426. }
  18427. }
  18428. return true;
  18429. };
  18430. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18431. for (var p = 0; p < 6; p++) {
  18432. var inCount = 8;
  18433. for (var i = 0; i < 8; i++) {
  18434. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18435. --inCount;
  18436. }
  18437. else {
  18438. break;
  18439. }
  18440. }
  18441. if (inCount === 0)
  18442. return false;
  18443. }
  18444. return true;
  18445. };
  18446. return BoundingBox;
  18447. }());
  18448. BABYLON.BoundingBox = BoundingBox;
  18449. })(BABYLON || (BABYLON = {}));
  18450. //# sourceMappingURL=babylon.boundingBox.js.map
  18451. var BABYLON;
  18452. (function (BABYLON) {
  18453. var computeBoxExtents = function (axis, box) {
  18454. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18455. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18456. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18457. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18458. var r = r0 + r1 + r2;
  18459. return {
  18460. min: p - r,
  18461. max: p + r
  18462. };
  18463. };
  18464. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18465. var axisOverlap = function (axis, box0, box1) {
  18466. var result0 = computeBoxExtents(axis, box0);
  18467. var result1 = computeBoxExtents(axis, box1);
  18468. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18469. };
  18470. var BoundingInfo = /** @class */ (function () {
  18471. function BoundingInfo(minimum, maximum) {
  18472. this.minimum = minimum;
  18473. this.maximum = maximum;
  18474. this._isLocked = false;
  18475. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18476. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18477. }
  18478. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18479. get: function () {
  18480. return this._isLocked;
  18481. },
  18482. set: function (value) {
  18483. this._isLocked = value;
  18484. },
  18485. enumerable: true,
  18486. configurable: true
  18487. });
  18488. // Methods
  18489. BoundingInfo.prototype.update = function (world) {
  18490. if (this._isLocked) {
  18491. return;
  18492. }
  18493. this.boundingBox._update(world);
  18494. this.boundingSphere._update(world);
  18495. };
  18496. /**
  18497. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18498. * @param center New center of the bounding info
  18499. * @param extend New extend of the bounding info
  18500. */
  18501. BoundingInfo.prototype.centerOn = function (center, extend) {
  18502. this.minimum = center.subtract(extend);
  18503. this.maximum = center.add(extend);
  18504. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18505. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18506. return this;
  18507. };
  18508. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18509. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18510. return false;
  18511. return this.boundingBox.isInFrustum(frustumPlanes);
  18512. };
  18513. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18514. /**
  18515. * Gets the world distance between the min and max points of the bounding box
  18516. */
  18517. get: function () {
  18518. var boundingBox = this.boundingBox;
  18519. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18520. return size.length();
  18521. },
  18522. enumerable: true,
  18523. configurable: true
  18524. });
  18525. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18526. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18527. };
  18528. BoundingInfo.prototype._checkCollision = function (collider) {
  18529. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18530. };
  18531. BoundingInfo.prototype.intersectsPoint = function (point) {
  18532. if (!this.boundingSphere.centerWorld) {
  18533. return false;
  18534. }
  18535. if (!this.boundingSphere.intersectsPoint(point)) {
  18536. return false;
  18537. }
  18538. if (!this.boundingBox.intersectsPoint(point)) {
  18539. return false;
  18540. }
  18541. return true;
  18542. };
  18543. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18544. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18545. return false;
  18546. }
  18547. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18548. return false;
  18549. }
  18550. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18551. return false;
  18552. }
  18553. if (!precise) {
  18554. return true;
  18555. }
  18556. var box0 = this.boundingBox;
  18557. var box1 = boundingInfo.boundingBox;
  18558. if (!axisOverlap(box0.directions[0], box0, box1))
  18559. return false;
  18560. if (!axisOverlap(box0.directions[1], box0, box1))
  18561. return false;
  18562. if (!axisOverlap(box0.directions[2], box0, box1))
  18563. return false;
  18564. if (!axisOverlap(box1.directions[0], box0, box1))
  18565. return false;
  18566. if (!axisOverlap(box1.directions[1], box0, box1))
  18567. return false;
  18568. if (!axisOverlap(box1.directions[2], box0, box1))
  18569. return false;
  18570. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18571. return false;
  18572. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18573. return false;
  18574. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18575. return false;
  18576. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18577. return false;
  18578. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18579. return false;
  18580. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18581. return false;
  18582. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18583. return false;
  18584. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18585. return false;
  18586. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18587. return false;
  18588. return true;
  18589. };
  18590. return BoundingInfo;
  18591. }());
  18592. BABYLON.BoundingInfo = BoundingInfo;
  18593. })(BABYLON || (BABYLON = {}));
  18594. //# sourceMappingURL=babylon.boundingInfo.js.map
  18595. var BABYLON;
  18596. (function (BABYLON) {
  18597. var TransformNode = /** @class */ (function (_super) {
  18598. __extends(TransformNode, _super);
  18599. function TransformNode(name, scene, isPure) {
  18600. if (scene === void 0) { scene = null; }
  18601. if (isPure === void 0) { isPure = true; }
  18602. var _this = _super.call(this, name, scene) || this;
  18603. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18604. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18605. _this._up = new BABYLON.Vector3(0, 1, 0);
  18606. _this._right = new BABYLON.Vector3(1, 0, 0);
  18607. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18608. // Properties
  18609. _this._rotation = BABYLON.Vector3.Zero();
  18610. _this._scaling = BABYLON.Vector3.One();
  18611. _this._isDirty = false;
  18612. /**
  18613. * Set the billboard mode. Default is 0.
  18614. *
  18615. * | Value | Type | Description |
  18616. * | --- | --- | --- |
  18617. * | 0 | BILLBOARDMODE_NONE | |
  18618. * | 1 | BILLBOARDMODE_X | |
  18619. * | 2 | BILLBOARDMODE_Y | |
  18620. * | 4 | BILLBOARDMODE_Z | |
  18621. * | 7 | BILLBOARDMODE_ALL | |
  18622. *
  18623. */
  18624. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18625. _this.scalingDeterminant = 1;
  18626. _this.infiniteDistance = false;
  18627. /**
  18628. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18629. * By default the system will update normals to compensate
  18630. */
  18631. _this.ignoreNonUniformScaling = false;
  18632. _this.position = BABYLON.Vector3.Zero();
  18633. _this._localWorld = BABYLON.Matrix.Zero();
  18634. _this._worldMatrix = BABYLON.Matrix.Zero();
  18635. _this._worldMatrixDeterminant = 0;
  18636. _this._absolutePosition = BABYLON.Vector3.Zero();
  18637. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18638. _this._postMultiplyPivotMatrix = false;
  18639. _this._isWorldMatrixFrozen = false;
  18640. /**
  18641. * An event triggered after the world matrix is updated
  18642. */
  18643. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18644. _this._nonUniformScaling = false;
  18645. if (isPure) {
  18646. _this.getScene().addTransformNode(_this);
  18647. }
  18648. return _this;
  18649. }
  18650. /**
  18651. * Gets a string idenfifying the name of the class
  18652. * @returns "TransformNode" string
  18653. */
  18654. TransformNode.prototype.getClassName = function () {
  18655. return "TransformNode";
  18656. };
  18657. Object.defineProperty(TransformNode.prototype, "rotation", {
  18658. /**
  18659. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18660. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18661. * Default : (0.0, 0.0, 0.0)
  18662. */
  18663. get: function () {
  18664. return this._rotation;
  18665. },
  18666. set: function (newRotation) {
  18667. this._rotation = newRotation;
  18668. },
  18669. enumerable: true,
  18670. configurable: true
  18671. });
  18672. Object.defineProperty(TransformNode.prototype, "scaling", {
  18673. /**
  18674. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18675. * Default : (1.0, 1.0, 1.0)
  18676. */
  18677. get: function () {
  18678. return this._scaling;
  18679. },
  18680. /**
  18681. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18682. * Default : (1.0, 1.0, 1.0)
  18683. */
  18684. set: function (newScaling) {
  18685. this._scaling = newScaling;
  18686. },
  18687. enumerable: true,
  18688. configurable: true
  18689. });
  18690. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18691. /**
  18692. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18693. * It's null by default.
  18694. * 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)
  18695. */
  18696. get: function () {
  18697. return this._rotationQuaternion;
  18698. },
  18699. set: function (quaternion) {
  18700. this._rotationQuaternion = quaternion;
  18701. //reset the rotation vector.
  18702. if (quaternion && this.rotation.length()) {
  18703. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18704. }
  18705. },
  18706. enumerable: true,
  18707. configurable: true
  18708. });
  18709. Object.defineProperty(TransformNode.prototype, "forward", {
  18710. /**
  18711. * The forward direction of that transform in world space.
  18712. */
  18713. get: function () {
  18714. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18715. },
  18716. enumerable: true,
  18717. configurable: true
  18718. });
  18719. Object.defineProperty(TransformNode.prototype, "up", {
  18720. /**
  18721. * The up direction of that transform in world space.
  18722. */
  18723. get: function () {
  18724. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18725. },
  18726. enumerable: true,
  18727. configurable: true
  18728. });
  18729. Object.defineProperty(TransformNode.prototype, "right", {
  18730. /**
  18731. * The right direction of that transform in world space.
  18732. */
  18733. get: function () {
  18734. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18735. },
  18736. enumerable: true,
  18737. configurable: true
  18738. });
  18739. /**
  18740. * Returns the latest update of the World matrix
  18741. * Returns a Matrix.
  18742. */
  18743. TransformNode.prototype.getWorldMatrix = function () {
  18744. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18745. this.computeWorldMatrix();
  18746. }
  18747. return this._worldMatrix;
  18748. };
  18749. /** @hidden */
  18750. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18751. return this._worldMatrixDeterminant;
  18752. };
  18753. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18754. /**
  18755. * Returns directly the latest state of the mesh World matrix.
  18756. * A Matrix is returned.
  18757. */
  18758. get: function () {
  18759. return this._worldMatrix;
  18760. },
  18761. enumerable: true,
  18762. configurable: true
  18763. });
  18764. /**
  18765. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18766. * Returns the TransformNode.
  18767. */
  18768. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18769. this._poseMatrix.copyFrom(matrix);
  18770. return this;
  18771. };
  18772. /**
  18773. * Returns the mesh Pose matrix.
  18774. * Returned object : Matrix
  18775. */
  18776. TransformNode.prototype.getPoseMatrix = function () {
  18777. return this._poseMatrix;
  18778. };
  18779. TransformNode.prototype._isSynchronized = function () {
  18780. if (this._isDirty) {
  18781. return false;
  18782. }
  18783. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18784. return false;
  18785. if (this._cache.pivotMatrixUpdated) {
  18786. return false;
  18787. }
  18788. if (this.infiniteDistance) {
  18789. return false;
  18790. }
  18791. if (!this._cache.position.equals(this.position))
  18792. return false;
  18793. if (this.rotationQuaternion) {
  18794. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18795. return false;
  18796. }
  18797. if (!this._cache.rotation.equals(this.rotation))
  18798. return false;
  18799. if (!this._cache.scaling.equals(this.scaling))
  18800. return false;
  18801. return true;
  18802. };
  18803. TransformNode.prototype._initCache = function () {
  18804. _super.prototype._initCache.call(this);
  18805. this._cache.localMatrixUpdated = false;
  18806. this._cache.position = BABYLON.Vector3.Zero();
  18807. this._cache.scaling = BABYLON.Vector3.Zero();
  18808. this._cache.rotation = BABYLON.Vector3.Zero();
  18809. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18810. this._cache.billboardMode = -1;
  18811. };
  18812. TransformNode.prototype.markAsDirty = function (property) {
  18813. if (property === "rotation") {
  18814. this.rotationQuaternion = null;
  18815. }
  18816. this._currentRenderId = Number.MAX_VALUE;
  18817. this._isDirty = true;
  18818. return this;
  18819. };
  18820. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18821. /**
  18822. * Returns the current mesh absolute position.
  18823. * Retuns a Vector3.
  18824. */
  18825. get: function () {
  18826. return this._absolutePosition;
  18827. },
  18828. enumerable: true,
  18829. configurable: true
  18830. });
  18831. /**
  18832. * Sets a new matrix to apply before all other transformation
  18833. * @param matrix defines the transform matrix
  18834. * @returns the current TransformNode
  18835. */
  18836. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18837. return this.setPivotMatrix(matrix, false);
  18838. };
  18839. /**
  18840. * Sets a new pivot matrix to the current node
  18841. * @param matrix defines the new pivot matrix to use
  18842. * @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
  18843. * @returns the current TransformNode
  18844. */
  18845. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18846. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18847. this._pivotMatrix = matrix.clone();
  18848. this._cache.pivotMatrixUpdated = true;
  18849. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18850. if (this._postMultiplyPivotMatrix) {
  18851. if (!this._pivotMatrixInverse) {
  18852. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18853. }
  18854. else {
  18855. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18856. }
  18857. }
  18858. return this;
  18859. };
  18860. /**
  18861. * Returns the mesh pivot matrix.
  18862. * Default : Identity.
  18863. * A Matrix is returned.
  18864. */
  18865. TransformNode.prototype.getPivotMatrix = function () {
  18866. return this._pivotMatrix;
  18867. };
  18868. /**
  18869. * Prevents the World matrix to be computed any longer.
  18870. * Returns the TransformNode.
  18871. */
  18872. TransformNode.prototype.freezeWorldMatrix = function () {
  18873. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18874. this.computeWorldMatrix(true);
  18875. this._isWorldMatrixFrozen = true;
  18876. return this;
  18877. };
  18878. /**
  18879. * Allows back the World matrix computation.
  18880. * Returns the TransformNode.
  18881. */
  18882. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18883. this._isWorldMatrixFrozen = false;
  18884. this.computeWorldMatrix(true);
  18885. return this;
  18886. };
  18887. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18888. /**
  18889. * True if the World matrix has been frozen.
  18890. * Returns a boolean.
  18891. */
  18892. get: function () {
  18893. return this._isWorldMatrixFrozen;
  18894. },
  18895. enumerable: true,
  18896. configurable: true
  18897. });
  18898. /**
  18899. * Retuns the mesh absolute position in the World.
  18900. * Returns a Vector3.
  18901. */
  18902. TransformNode.prototype.getAbsolutePosition = function () {
  18903. this.computeWorldMatrix();
  18904. return this._absolutePosition;
  18905. };
  18906. /**
  18907. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18908. * Returns the TransformNode.
  18909. */
  18910. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18911. if (!absolutePosition) {
  18912. return this;
  18913. }
  18914. var absolutePositionX;
  18915. var absolutePositionY;
  18916. var absolutePositionZ;
  18917. if (absolutePosition.x === undefined) {
  18918. if (arguments.length < 3) {
  18919. return this;
  18920. }
  18921. absolutePositionX = arguments[0];
  18922. absolutePositionY = arguments[1];
  18923. absolutePositionZ = arguments[2];
  18924. }
  18925. else {
  18926. absolutePositionX = absolutePosition.x;
  18927. absolutePositionY = absolutePosition.y;
  18928. absolutePositionZ = absolutePosition.z;
  18929. }
  18930. if (this.parent) {
  18931. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18932. invertParentWorldMatrix.invert();
  18933. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18934. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18935. }
  18936. else {
  18937. this.position.x = absolutePositionX;
  18938. this.position.y = absolutePositionY;
  18939. this.position.z = absolutePositionZ;
  18940. }
  18941. return this;
  18942. };
  18943. /**
  18944. * Sets the mesh position in its local space.
  18945. * Returns the TransformNode.
  18946. */
  18947. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18948. this.computeWorldMatrix();
  18949. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18950. return this;
  18951. };
  18952. /**
  18953. * Returns the mesh position in the local space from the current World matrix values.
  18954. * Returns a new Vector3.
  18955. */
  18956. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18957. this.computeWorldMatrix();
  18958. var invLocalWorldMatrix = this._localWorld.clone();
  18959. invLocalWorldMatrix.invert();
  18960. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18961. };
  18962. /**
  18963. * Translates the mesh along the passed Vector3 in its local space.
  18964. * Returns the TransformNode.
  18965. */
  18966. TransformNode.prototype.locallyTranslate = function (vector3) {
  18967. this.computeWorldMatrix(true);
  18968. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18969. return this;
  18970. };
  18971. /**
  18972. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18973. * @param targetPoint the position (must be in same space as current mesh) to look at
  18974. * @param yawCor optional yaw (y-axis) correction in radians
  18975. * @param pitchCor optional pitch (x-axis) correction in radians
  18976. * @param rollCor optional roll (z-axis) correction in radians
  18977. * @param space the choosen space of the target
  18978. * @returns the TransformNode.
  18979. */
  18980. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18981. if (yawCor === void 0) { yawCor = 0; }
  18982. if (pitchCor === void 0) { pitchCor = 0; }
  18983. if (rollCor === void 0) { rollCor = 0; }
  18984. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18985. var dv = TransformNode._lookAtVectorCache;
  18986. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18987. targetPoint.subtractToRef(pos, dv);
  18988. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18989. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18990. var pitch = Math.atan2(dv.y, len);
  18991. if (this.rotationQuaternion) {
  18992. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18993. }
  18994. else {
  18995. this.rotation.x = pitch + pitchCor;
  18996. this.rotation.y = yaw + yawCor;
  18997. this.rotation.z = rollCor;
  18998. }
  18999. return this;
  19000. };
  19001. /**
  19002. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19003. * This Vector3 is expressed in the World space.
  19004. */
  19005. TransformNode.prototype.getDirection = function (localAxis) {
  19006. var result = BABYLON.Vector3.Zero();
  19007. this.getDirectionToRef(localAxis, result);
  19008. return result;
  19009. };
  19010. /**
  19011. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19012. * localAxis is expressed in the mesh local space.
  19013. * result is computed in the Wordl space from the mesh World matrix.
  19014. * Returns the TransformNode.
  19015. */
  19016. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19017. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19018. return this;
  19019. };
  19020. /**
  19021. * Sets a new pivot point to the current node
  19022. * @param point defines the new pivot point to use
  19023. * @param space defines if the point is in world or local space (local by default)
  19024. * @returns the current TransformNode
  19025. */
  19026. TransformNode.prototype.setPivotPoint = function (point, space) {
  19027. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19028. if (this.getScene().getRenderId() == 0) {
  19029. this.computeWorldMatrix(true);
  19030. }
  19031. var wm = this.getWorldMatrix();
  19032. if (space == BABYLON.Space.WORLD) {
  19033. var tmat = BABYLON.Tmp.Matrix[0];
  19034. wm.invertToRef(tmat);
  19035. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19036. }
  19037. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19038. };
  19039. /**
  19040. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19041. */
  19042. TransformNode.prototype.getPivotPoint = function () {
  19043. var point = BABYLON.Vector3.Zero();
  19044. this.getPivotPointToRef(point);
  19045. return point;
  19046. };
  19047. /**
  19048. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19049. * Returns the TransformNode.
  19050. */
  19051. TransformNode.prototype.getPivotPointToRef = function (result) {
  19052. result.x = -this._pivotMatrix.m[12];
  19053. result.y = -this._pivotMatrix.m[13];
  19054. result.z = -this._pivotMatrix.m[14];
  19055. return this;
  19056. };
  19057. /**
  19058. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19059. */
  19060. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19061. var point = BABYLON.Vector3.Zero();
  19062. this.getAbsolutePivotPointToRef(point);
  19063. return point;
  19064. };
  19065. /**
  19066. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19067. * Returns the TransformNode.
  19068. */
  19069. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19070. result.x = this._pivotMatrix.m[12];
  19071. result.y = this._pivotMatrix.m[13];
  19072. result.z = this._pivotMatrix.m[14];
  19073. this.getPivotPointToRef(result);
  19074. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19075. return this;
  19076. };
  19077. /**
  19078. * Defines the passed node as the parent of the current node.
  19079. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19080. * Returns the TransformNode.
  19081. */
  19082. TransformNode.prototype.setParent = function (node) {
  19083. if (!node && !this.parent) {
  19084. return this;
  19085. }
  19086. if (!node) {
  19087. var rotation = BABYLON.Tmp.Quaternion[0];
  19088. var position = BABYLON.Tmp.Vector3[0];
  19089. var scale = BABYLON.Tmp.Vector3[1];
  19090. if (this.parent && this.parent.computeWorldMatrix) {
  19091. this.parent.computeWorldMatrix(true);
  19092. }
  19093. this.computeWorldMatrix(true);
  19094. this.getWorldMatrix().decompose(scale, rotation, position);
  19095. if (this.rotationQuaternion) {
  19096. this.rotationQuaternion.copyFrom(rotation);
  19097. }
  19098. else {
  19099. rotation.toEulerAnglesToRef(this.rotation);
  19100. }
  19101. this.scaling.x = scale.x;
  19102. this.scaling.y = scale.y;
  19103. this.scaling.z = scale.z;
  19104. this.position.x = position.x;
  19105. this.position.y = position.y;
  19106. this.position.z = position.z;
  19107. }
  19108. else {
  19109. var rotation = BABYLON.Tmp.Quaternion[0];
  19110. var position = BABYLON.Tmp.Vector3[0];
  19111. var scale = BABYLON.Tmp.Vector3[1];
  19112. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19113. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19114. this.computeWorldMatrix(true);
  19115. node.computeWorldMatrix(true);
  19116. node.getWorldMatrix().invertToRef(invParentMatrix);
  19117. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19118. diffMatrix.decompose(scale, rotation, position);
  19119. if (this.rotationQuaternion) {
  19120. this.rotationQuaternion.copyFrom(rotation);
  19121. }
  19122. else {
  19123. rotation.toEulerAnglesToRef(this.rotation);
  19124. }
  19125. this.position.x = position.x;
  19126. this.position.y = position.y;
  19127. this.position.z = position.z;
  19128. this.scaling.x = scale.x;
  19129. this.scaling.y = scale.y;
  19130. this.scaling.z = scale.z;
  19131. }
  19132. this.parent = node;
  19133. return this;
  19134. };
  19135. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19136. get: function () {
  19137. return this._nonUniformScaling;
  19138. },
  19139. enumerable: true,
  19140. configurable: true
  19141. });
  19142. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19143. if (this._nonUniformScaling === value) {
  19144. return false;
  19145. }
  19146. this._nonUniformScaling = value;
  19147. return true;
  19148. };
  19149. /**
  19150. * Attach the current TransformNode to another TransformNode associated with a bone
  19151. * @param bone Bone affecting the TransformNode
  19152. * @param affectedTransformNode TransformNode associated with the bone
  19153. */
  19154. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19155. this._transformToBoneReferal = affectedTransformNode;
  19156. this.parent = bone;
  19157. if (bone.getWorldMatrix().determinant() < 0) {
  19158. this.scalingDeterminant *= -1;
  19159. }
  19160. return this;
  19161. };
  19162. TransformNode.prototype.detachFromBone = function () {
  19163. if (!this.parent) {
  19164. return this;
  19165. }
  19166. if (this.parent.getWorldMatrix().determinant() < 0) {
  19167. this.scalingDeterminant *= -1;
  19168. }
  19169. this._transformToBoneReferal = null;
  19170. this.parent = null;
  19171. return this;
  19172. };
  19173. /**
  19174. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19175. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19176. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19177. * The passed axis is also normalized.
  19178. * Returns the TransformNode.
  19179. */
  19180. TransformNode.prototype.rotate = function (axis, amount, space) {
  19181. axis.normalize();
  19182. if (!this.rotationQuaternion) {
  19183. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19184. this.rotation = BABYLON.Vector3.Zero();
  19185. }
  19186. var rotationQuaternion;
  19187. if (!space || space === BABYLON.Space.LOCAL) {
  19188. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19189. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19190. }
  19191. else {
  19192. if (this.parent) {
  19193. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19194. invertParentWorldMatrix.invert();
  19195. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19196. }
  19197. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19198. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19199. }
  19200. return this;
  19201. };
  19202. /**
  19203. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19204. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19205. * The passed axis is also normalized.
  19206. * Returns the TransformNode.
  19207. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19208. */
  19209. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19210. axis.normalize();
  19211. if (!this.rotationQuaternion) {
  19212. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19213. this.rotation.copyFromFloats(0, 0, 0);
  19214. }
  19215. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19216. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19217. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19218. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19219. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19220. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19221. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19222. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19223. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19224. return this;
  19225. };
  19226. /**
  19227. * Translates the mesh along the axis vector for the passed distance in the given space.
  19228. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19229. * Returns the TransformNode.
  19230. */
  19231. TransformNode.prototype.translate = function (axis, distance, space) {
  19232. var displacementVector = axis.scale(distance);
  19233. if (!space || space === BABYLON.Space.LOCAL) {
  19234. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19235. this.setPositionWithLocalVector(tempV3);
  19236. }
  19237. else {
  19238. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19239. }
  19240. return this;
  19241. };
  19242. /**
  19243. * Adds a rotation step to the mesh current rotation.
  19244. * x, y, z are Euler angles expressed in radians.
  19245. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19246. * This means this rotation is made in the mesh local space only.
  19247. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19248. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19249. * ```javascript
  19250. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19251. * ```
  19252. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19253. * 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.
  19254. * Returns the TransformNode.
  19255. */
  19256. TransformNode.prototype.addRotation = function (x, y, z) {
  19257. var rotationQuaternion;
  19258. if (this.rotationQuaternion) {
  19259. rotationQuaternion = this.rotationQuaternion;
  19260. }
  19261. else {
  19262. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19263. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19264. }
  19265. var accumulation = BABYLON.Tmp.Quaternion[0];
  19266. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19267. rotationQuaternion.multiplyInPlace(accumulation);
  19268. if (!this.rotationQuaternion) {
  19269. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19270. }
  19271. return this;
  19272. };
  19273. /**
  19274. * Computes the mesh World matrix and returns it.
  19275. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19276. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19277. * If the parameter `force`is set to `true`, the actual computation is done.
  19278. * Returns the mesh World Matrix.
  19279. */
  19280. TransformNode.prototype.computeWorldMatrix = function (force) {
  19281. if (this._isWorldMatrixFrozen) {
  19282. return this._worldMatrix;
  19283. }
  19284. if (!force && this.isSynchronized(true)) {
  19285. this._currentRenderId = this.getScene().getRenderId();
  19286. return this._worldMatrix;
  19287. }
  19288. this._cache.position.copyFrom(this.position);
  19289. this._cache.scaling.copyFrom(this.scaling);
  19290. this._cache.pivotMatrixUpdated = false;
  19291. this._cache.billboardMode = this.billboardMode;
  19292. this._currentRenderId = this.getScene().getRenderId();
  19293. this._childRenderId = this.getScene().getRenderId();
  19294. this._isDirty = false;
  19295. // Scaling
  19296. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19297. // Rotation
  19298. //rotate, if quaternion is set and rotation was used
  19299. if (this.rotationQuaternion) {
  19300. var len = this.rotation.length();
  19301. if (len) {
  19302. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19303. this.rotation.copyFromFloats(0, 0, 0);
  19304. }
  19305. }
  19306. if (this.rotationQuaternion) {
  19307. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19308. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19309. }
  19310. else {
  19311. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19312. this._cache.rotation.copyFrom(this.rotation);
  19313. }
  19314. // Translation
  19315. var camera = this.getScene().activeCamera;
  19316. if (this.infiniteDistance && !this.parent && camera) {
  19317. var cameraWorldMatrix = camera.getWorldMatrix();
  19318. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19319. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19320. }
  19321. else {
  19322. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19323. }
  19324. // Composing transformations
  19325. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19326. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19327. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19328. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19329. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19330. // Need to decompose each rotation here
  19331. var currentPosition = BABYLON.Tmp.Vector3[3];
  19332. if (this.parent && this.parent.getWorldMatrix) {
  19333. if (this._transformToBoneReferal) {
  19334. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19335. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19336. }
  19337. else {
  19338. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19339. }
  19340. }
  19341. else {
  19342. currentPosition.copyFrom(this.position);
  19343. }
  19344. currentPosition.subtractInPlace(camera.globalPosition);
  19345. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19346. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19347. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19348. }
  19349. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19350. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19351. }
  19352. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19353. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19354. }
  19355. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19356. }
  19357. else {
  19358. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19359. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19360. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19361. }
  19362. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19363. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19364. }
  19365. // Local world
  19366. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19367. // Parent
  19368. if (this.parent && this.parent.getWorldMatrix) {
  19369. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19370. if (this._transformToBoneReferal) {
  19371. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19372. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19373. }
  19374. else {
  19375. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19376. }
  19377. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19378. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19379. this._worldMatrix.copyFrom(this._localWorld);
  19380. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19381. }
  19382. else {
  19383. if (this._transformToBoneReferal) {
  19384. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19385. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19386. }
  19387. else {
  19388. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19389. }
  19390. }
  19391. this._markSyncedWithParent();
  19392. }
  19393. else {
  19394. this._worldMatrix.copyFrom(this._localWorld);
  19395. }
  19396. // Post multiply inverse of pivotMatrix
  19397. if (this._postMultiplyPivotMatrix) {
  19398. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19399. }
  19400. // Normal matrix
  19401. if (!this.ignoreNonUniformScaling) {
  19402. if (this.scaling.isNonUniform) {
  19403. this._updateNonUniformScalingState(true);
  19404. }
  19405. else if (this.parent && this.parent._nonUniformScaling) {
  19406. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19407. }
  19408. else {
  19409. this._updateNonUniformScalingState(false);
  19410. }
  19411. }
  19412. else {
  19413. this._updateNonUniformScalingState(false);
  19414. }
  19415. this._afterComputeWorldMatrix();
  19416. // Absolute position
  19417. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19418. // Callbacks
  19419. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19420. if (!this._poseMatrix) {
  19421. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19422. }
  19423. // Cache the determinant
  19424. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19425. return this._worldMatrix;
  19426. };
  19427. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19428. };
  19429. /**
  19430. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19431. * @param func: callback function to add
  19432. *
  19433. * Returns the TransformNode.
  19434. */
  19435. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19436. this.onAfterWorldMatrixUpdateObservable.add(func);
  19437. return this;
  19438. };
  19439. /**
  19440. * Removes a registered callback function.
  19441. * Returns the TransformNode.
  19442. */
  19443. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19444. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19445. return this;
  19446. };
  19447. /**
  19448. * Clone the current transform node
  19449. * Returns the new transform node
  19450. * @param name Name of the new clone
  19451. * @param newParent New parent for the clone
  19452. * @param doNotCloneChildren Do not clone children hierarchy
  19453. */
  19454. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19455. var _this = this;
  19456. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19457. result.name = name;
  19458. result.id = name;
  19459. if (newParent) {
  19460. result.parent = newParent;
  19461. }
  19462. if (!doNotCloneChildren) {
  19463. // Children
  19464. var directDescendants = this.getDescendants(true);
  19465. for (var index = 0; index < directDescendants.length; index++) {
  19466. var child = directDescendants[index];
  19467. if (child.clone) {
  19468. child.clone(name + "." + child.name, result);
  19469. }
  19470. }
  19471. }
  19472. return result;
  19473. };
  19474. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19475. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19476. serializationObject.type = this.getClassName();
  19477. // Parent
  19478. if (this.parent) {
  19479. serializationObject.parentId = this.parent.id;
  19480. }
  19481. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19482. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19483. }
  19484. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19485. serializationObject.isEnabled = this.isEnabled();
  19486. // Parent
  19487. if (this.parent) {
  19488. serializationObject.parentId = this.parent.id;
  19489. }
  19490. return serializationObject;
  19491. };
  19492. // Statics
  19493. /**
  19494. * Returns a new TransformNode object parsed from the source provided.
  19495. * The parameter `parsedMesh` is the source.
  19496. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19497. */
  19498. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19499. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19500. if (BABYLON.Tags) {
  19501. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19502. }
  19503. if (parsedTransformNode.localMatrix) {
  19504. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19505. }
  19506. else if (parsedTransformNode.pivotMatrix) {
  19507. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19508. }
  19509. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19510. // Parent
  19511. if (parsedTransformNode.parentId) {
  19512. transformNode._waitingParentId = parsedTransformNode.parentId;
  19513. }
  19514. return transformNode;
  19515. };
  19516. /**
  19517. * Releases resources associated with this transform node.
  19518. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19519. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19520. */
  19521. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19522. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19523. // Animations
  19524. this.getScene().stopAnimation(this);
  19525. // Remove from scene
  19526. this.getScene().removeTransformNode(this);
  19527. this.onAfterWorldMatrixUpdateObservable.clear();
  19528. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19529. };
  19530. // Statics
  19531. TransformNode.BILLBOARDMODE_NONE = 0;
  19532. TransformNode.BILLBOARDMODE_X = 1;
  19533. TransformNode.BILLBOARDMODE_Y = 2;
  19534. TransformNode.BILLBOARDMODE_Z = 4;
  19535. TransformNode.BILLBOARDMODE_ALL = 7;
  19536. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19537. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19538. __decorate([
  19539. BABYLON.serializeAsVector3()
  19540. ], TransformNode.prototype, "_rotation", void 0);
  19541. __decorate([
  19542. BABYLON.serializeAsQuaternion()
  19543. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19544. __decorate([
  19545. BABYLON.serializeAsVector3()
  19546. ], TransformNode.prototype, "_scaling", void 0);
  19547. __decorate([
  19548. BABYLON.serialize()
  19549. ], TransformNode.prototype, "billboardMode", void 0);
  19550. __decorate([
  19551. BABYLON.serialize()
  19552. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19553. __decorate([
  19554. BABYLON.serialize()
  19555. ], TransformNode.prototype, "infiniteDistance", void 0);
  19556. __decorate([
  19557. BABYLON.serialize()
  19558. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19559. __decorate([
  19560. BABYLON.serializeAsVector3()
  19561. ], TransformNode.prototype, "position", void 0);
  19562. return TransformNode;
  19563. }(BABYLON.Node));
  19564. BABYLON.TransformNode = TransformNode;
  19565. })(BABYLON || (BABYLON = {}));
  19566. //# sourceMappingURL=babylon.transformNode.js.map
  19567. var BABYLON;
  19568. (function (BABYLON) {
  19569. /**
  19570. * Class used to store all common mesh properties
  19571. */
  19572. var AbstractMesh = /** @class */ (function (_super) {
  19573. __extends(AbstractMesh, _super);
  19574. // Constructor
  19575. /**
  19576. * Creates a new AbstractMesh
  19577. * @param name defines the name of the mesh
  19578. * @param scene defines the hosting scene
  19579. */
  19580. function AbstractMesh(name, scene) {
  19581. if (scene === void 0) { scene = null; }
  19582. var _this = _super.call(this, name, scene, false) || this;
  19583. _this._facetNb = 0; // facet number
  19584. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19585. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19586. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19587. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19588. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19589. _this._subDiv = {
  19590. max: 1,
  19591. X: 1,
  19592. Y: 1,
  19593. Z: 1
  19594. };
  19595. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19596. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19597. // Events
  19598. /**
  19599. * An event triggered when this mesh collides with another one
  19600. */
  19601. _this.onCollideObservable = new BABYLON.Observable();
  19602. /**
  19603. * An event triggered when the collision's position changes
  19604. */
  19605. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19606. /**
  19607. * An event triggered when material is changed
  19608. */
  19609. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19610. // Properties
  19611. /**
  19612. * Gets or sets the orientation for POV movement & rotation
  19613. */
  19614. _this.definedFacingForward = true;
  19615. /**
  19616. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19617. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19618. * * 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.
  19619. * @see http://doc.babylonjs.com/features/occlusionquery
  19620. */
  19621. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19622. /**
  19623. * 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:
  19624. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19625. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19626. * * 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.
  19627. * @see http://doc.babylonjs.com/features/occlusionquery
  19628. */
  19629. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19630. /**
  19631. * 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.
  19632. * The default value is -1 which means don't break the query and wait till the result
  19633. * @see http://doc.babylonjs.com/features/occlusionquery
  19634. */
  19635. _this.occlusionRetryCount = -1;
  19636. _this._occlusionInternalRetryCounter = 0;
  19637. _this._isOccluded = false;
  19638. _this._isOcclusionQueryInProgress = false;
  19639. _this._visibility = 1.0;
  19640. /** Gets or sets the alpha index used to sort transparent meshes
  19641. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19642. */
  19643. _this.alphaIndex = Number.MAX_VALUE;
  19644. /**
  19645. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19646. */
  19647. _this.isVisible = true;
  19648. /**
  19649. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19650. */
  19651. _this.isPickable = true;
  19652. /**
  19653. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19654. */
  19655. _this.showBoundingBox = false;
  19656. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19657. _this.showSubMeshesBoundingBox = false;
  19658. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19659. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19660. */
  19661. _this.isBlocker = false;
  19662. /**
  19663. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19664. */
  19665. _this.enablePointerMoveEvents = false;
  19666. /**
  19667. * Specifies the rendering group id for this mesh (0 by default)
  19668. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19669. */
  19670. _this.renderingGroupId = 0;
  19671. _this._receiveShadows = false;
  19672. /**
  19673. * Gets or sets a boolean indicating if the outline must be rendered as well
  19674. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19675. */
  19676. _this.renderOutline = false;
  19677. /** Defines color to use when rendering outline */
  19678. _this.outlineColor = BABYLON.Color3.Red();
  19679. /** Define width to use when rendering outline */
  19680. _this.outlineWidth = 0.02;
  19681. /**
  19682. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19683. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19684. */
  19685. _this.renderOverlay = false;
  19686. /** Defines color to use when rendering overlay */
  19687. _this.overlayColor = BABYLON.Color3.Red();
  19688. /** Defines alpha to use when rendering overlay */
  19689. _this.overlayAlpha = 0.5;
  19690. _this._hasVertexAlpha = false;
  19691. _this._useVertexColors = true;
  19692. _this._computeBonesUsingShaders = true;
  19693. _this._numBoneInfluencers = 4;
  19694. _this._applyFog = true;
  19695. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19696. _this.useOctreeForRenderingSelection = true;
  19697. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19698. _this.useOctreeForPicking = true;
  19699. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19700. _this.useOctreeForCollisions = true;
  19701. _this._layerMask = 0x0FFFFFFF;
  19702. /**
  19703. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19704. */
  19705. _this.alwaysSelectAsActiveMesh = false;
  19706. /**
  19707. * Gets or sets the current action manager
  19708. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19709. */
  19710. _this.actionManager = null;
  19711. /**
  19712. * Gets or sets impostor used for physic simulation
  19713. * @see http://doc.babylonjs.com/features/physics_engine
  19714. */
  19715. _this.physicsImpostor = null;
  19716. // Collisions
  19717. _this._checkCollisions = false;
  19718. _this._collisionMask = -1;
  19719. _this._collisionGroup = -1;
  19720. /**
  19721. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19722. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19723. */
  19724. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19725. /**
  19726. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19727. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19728. */
  19729. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19730. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19731. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19732. // Edges
  19733. /**
  19734. * Defines edge width used when edgesRenderer is enabled
  19735. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19736. */
  19737. _this.edgesWidth = 1;
  19738. /**
  19739. * Defines edge color used when edgesRenderer is enabled
  19740. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19741. */
  19742. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19743. // Cache
  19744. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19745. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19746. /** @hidden */
  19747. _this._renderId = 0;
  19748. /** @hidden */
  19749. _this._intersectionsInProgress = new Array();
  19750. /** @hidden */
  19751. _this._unIndexed = false;
  19752. /** @hidden */
  19753. _this._lightSources = new Array();
  19754. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19755. if (collidedMesh === void 0) { collidedMesh = null; }
  19756. //TODO move this to the collision coordinator!
  19757. if (_this.getScene().workerCollisions)
  19758. newPosition.multiplyInPlace(_this._collider._radius);
  19759. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19760. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19761. _this.position.addInPlace(_this._diffPositionForCollisions);
  19762. }
  19763. if (collidedMesh) {
  19764. _this.onCollideObservable.notifyObservers(collidedMesh);
  19765. }
  19766. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19767. };
  19768. _this.getScene().addMesh(_this);
  19769. _this._resyncLightSources();
  19770. return _this;
  19771. }
  19772. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19773. /**
  19774. * No billboard
  19775. */
  19776. get: function () {
  19777. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19783. /** Billboard on X axis */
  19784. get: function () {
  19785. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19786. },
  19787. enumerable: true,
  19788. configurable: true
  19789. });
  19790. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19791. /** Billboard on Y axis */
  19792. get: function () {
  19793. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19799. /** Billboard on Z axis */
  19800. get: function () {
  19801. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19807. /** Billboard on all axes */
  19808. get: function () {
  19809. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19815. /**
  19816. * Gets the number of facets in the mesh
  19817. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19818. */
  19819. get: function () {
  19820. return this._facetNb;
  19821. },
  19822. enumerable: true,
  19823. configurable: true
  19824. });
  19825. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19826. /**
  19827. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19828. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19829. */
  19830. get: function () {
  19831. return this._partitioningSubdivisions;
  19832. },
  19833. set: function (nb) {
  19834. this._partitioningSubdivisions = nb;
  19835. },
  19836. enumerable: true,
  19837. configurable: true
  19838. });
  19839. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19840. /**
  19841. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19842. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19843. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19844. */
  19845. get: function () {
  19846. return this._partitioningBBoxRatio;
  19847. },
  19848. set: function (ratio) {
  19849. this._partitioningBBoxRatio = ratio;
  19850. },
  19851. enumerable: true,
  19852. configurable: true
  19853. });
  19854. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19855. /**
  19856. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19857. * Works only for updatable meshes.
  19858. * Doesn't work with multi-materials
  19859. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19860. */
  19861. get: function () {
  19862. return this._facetDepthSort;
  19863. },
  19864. set: function (sort) {
  19865. this._facetDepthSort = sort;
  19866. },
  19867. enumerable: true,
  19868. configurable: true
  19869. });
  19870. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19871. /**
  19872. * The location (Vector3) where the facet depth sort must be computed from.
  19873. * By default, the active camera position.
  19874. * Used only when facet depth sort is enabled
  19875. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19876. */
  19877. get: function () {
  19878. return this._facetDepthSortFrom;
  19879. },
  19880. set: function (location) {
  19881. this._facetDepthSortFrom = location;
  19882. },
  19883. enumerable: true,
  19884. configurable: true
  19885. });
  19886. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19887. /**
  19888. * gets a boolean indicating if facetData is enabled
  19889. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19890. */
  19891. get: function () {
  19892. return this._facetDataEnabled;
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. /** @hidden */
  19898. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19899. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19900. return false;
  19901. }
  19902. this._markSubMeshesAsMiscDirty();
  19903. return true;
  19904. };
  19905. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19906. /** Set a function to call when this mesh collides with another one */
  19907. set: function (callback) {
  19908. if (this._onCollideObserver) {
  19909. this.onCollideObservable.remove(this._onCollideObserver);
  19910. }
  19911. this._onCollideObserver = this.onCollideObservable.add(callback);
  19912. },
  19913. enumerable: true,
  19914. configurable: true
  19915. });
  19916. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19917. /** Set a function to call when the collision's position changes */
  19918. set: function (callback) {
  19919. if (this._onCollisionPositionChangeObserver) {
  19920. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19921. }
  19922. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19923. },
  19924. enumerable: true,
  19925. configurable: true
  19926. });
  19927. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19928. /**
  19929. * Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not
  19930. * @see http://doc.babylonjs.com/features/occlusionquery
  19931. */
  19932. get: function () {
  19933. return this._isOccluded;
  19934. },
  19935. set: function (value) {
  19936. this._isOccluded = value;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19942. /**
  19943. * Flag to check the progress status of the query
  19944. * @see http://doc.babylonjs.com/features/occlusionquery
  19945. */
  19946. get: function () {
  19947. return this._isOcclusionQueryInProgress;
  19948. },
  19949. enumerable: true,
  19950. configurable: true
  19951. });
  19952. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19953. /**
  19954. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19955. */
  19956. get: function () {
  19957. return this._visibility;
  19958. },
  19959. /**
  19960. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19961. */
  19962. set: function (value) {
  19963. if (this._visibility === value) {
  19964. return;
  19965. }
  19966. this._visibility = value;
  19967. this._markSubMeshesAsMiscDirty();
  19968. },
  19969. enumerable: true,
  19970. configurable: true
  19971. });
  19972. Object.defineProperty(AbstractMesh.prototype, "material", {
  19973. /** Gets or sets current material */
  19974. get: function () {
  19975. return this._material;
  19976. },
  19977. set: function (value) {
  19978. if (this._material === value) {
  19979. return;
  19980. }
  19981. this._material = value;
  19982. if (this.onMaterialChangedObservable.hasObservers) {
  19983. this.onMaterialChangedObservable.notifyObservers(this);
  19984. }
  19985. if (!this.subMeshes) {
  19986. return;
  19987. }
  19988. this._unBindEffect();
  19989. },
  19990. enumerable: true,
  19991. configurable: true
  19992. });
  19993. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19994. /**
  19995. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19996. * @see http://doc.babylonjs.com/babylon101/shadows
  19997. */
  19998. get: function () {
  19999. return this._receiveShadows;
  20000. },
  20001. set: function (value) {
  20002. if (this._receiveShadows === value) {
  20003. return;
  20004. }
  20005. this._receiveShadows = value;
  20006. this._markSubMeshesAsLightDirty();
  20007. },
  20008. enumerable: true,
  20009. configurable: true
  20010. });
  20011. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20012. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20013. get: function () {
  20014. return this._hasVertexAlpha;
  20015. },
  20016. set: function (value) {
  20017. if (this._hasVertexAlpha === value) {
  20018. return;
  20019. }
  20020. this._hasVertexAlpha = value;
  20021. this._markSubMeshesAsAttributesDirty();
  20022. this._markSubMeshesAsMiscDirty();
  20023. },
  20024. enumerable: true,
  20025. configurable: true
  20026. });
  20027. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20028. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20029. get: function () {
  20030. return this._useVertexColors;
  20031. },
  20032. set: function (value) {
  20033. if (this._useVertexColors === value) {
  20034. return;
  20035. }
  20036. this._useVertexColors = value;
  20037. this._markSubMeshesAsAttributesDirty();
  20038. },
  20039. enumerable: true,
  20040. configurable: true
  20041. });
  20042. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20043. /**
  20044. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20045. */
  20046. get: function () {
  20047. return this._computeBonesUsingShaders;
  20048. },
  20049. set: function (value) {
  20050. if (this._computeBonesUsingShaders === value) {
  20051. return;
  20052. }
  20053. this._computeBonesUsingShaders = value;
  20054. this._markSubMeshesAsAttributesDirty();
  20055. },
  20056. enumerable: true,
  20057. configurable: true
  20058. });
  20059. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20060. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20061. get: function () {
  20062. return this._numBoneInfluencers;
  20063. },
  20064. set: function (value) {
  20065. if (this._numBoneInfluencers === value) {
  20066. return;
  20067. }
  20068. this._numBoneInfluencers = value;
  20069. this._markSubMeshesAsAttributesDirty();
  20070. },
  20071. enumerable: true,
  20072. configurable: true
  20073. });
  20074. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20075. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20076. get: function () {
  20077. return this._applyFog;
  20078. },
  20079. set: function (value) {
  20080. if (this._applyFog === value) {
  20081. return;
  20082. }
  20083. this._applyFog = value;
  20084. this._markSubMeshesAsMiscDirty();
  20085. },
  20086. enumerable: true,
  20087. configurable: true
  20088. });
  20089. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20090. /**
  20091. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20092. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20093. */
  20094. get: function () {
  20095. return this._layerMask;
  20096. },
  20097. set: function (value) {
  20098. if (value === this._layerMask) {
  20099. return;
  20100. }
  20101. this._layerMask = value;
  20102. this._resyncLightSources();
  20103. },
  20104. enumerable: true,
  20105. configurable: true
  20106. });
  20107. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20108. /**
  20109. * Gets or sets a collision mask used to mask collisions (default is -1).
  20110. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20111. */
  20112. get: function () {
  20113. return this._collisionMask;
  20114. },
  20115. set: function (mask) {
  20116. this._collisionMask = !isNaN(mask) ? mask : -1;
  20117. },
  20118. enumerable: true,
  20119. configurable: true
  20120. });
  20121. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20122. /**
  20123. * Gets or sets the current collision group mask (-1 by default).
  20124. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20125. */
  20126. get: function () {
  20127. return this._collisionGroup;
  20128. },
  20129. set: function (mask) {
  20130. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20131. },
  20132. enumerable: true,
  20133. configurable: true
  20134. });
  20135. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20136. /** @hidden */
  20137. get: function () {
  20138. return null;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20144. get: function () {
  20145. return this._skeleton;
  20146. },
  20147. /**
  20148. * Gets or sets a skeleton to apply skining transformations
  20149. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20150. */
  20151. set: function (value) {
  20152. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20153. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20154. }
  20155. if (value && value.needInitialSkinMatrix) {
  20156. value._registerMeshWithPoseMatrix(this);
  20157. }
  20158. this._skeleton = value;
  20159. if (!this._skeleton) {
  20160. this._bonesTransformMatrices = null;
  20161. }
  20162. this._markSubMeshesAsAttributesDirty();
  20163. },
  20164. enumerable: true,
  20165. configurable: true
  20166. });
  20167. /**
  20168. * Returns the string "AbstractMesh"
  20169. * @returns "AbstractMesh"
  20170. */
  20171. AbstractMesh.prototype.getClassName = function () {
  20172. return "AbstractMesh";
  20173. };
  20174. /**
  20175. * Gets a string representation of the current mesh
  20176. * @param fullDetails defines a boolean indicating if full details must be included
  20177. * @returns a string representation of the current mesh
  20178. */
  20179. AbstractMesh.prototype.toString = function (fullDetails) {
  20180. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20181. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20182. if (this._skeleton) {
  20183. ret += ", skeleton: " + this._skeleton.name;
  20184. }
  20185. if (fullDetails) {
  20186. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20187. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20188. }
  20189. return ret;
  20190. };
  20191. /** @hidden */
  20192. AbstractMesh.prototype._rebuild = function () {
  20193. if (this._occlusionQuery) {
  20194. this._occlusionQuery = null;
  20195. }
  20196. if (this._edgesRenderer) {
  20197. this._edgesRenderer._rebuild();
  20198. }
  20199. if (!this.subMeshes) {
  20200. return;
  20201. }
  20202. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20203. var subMesh = _a[_i];
  20204. subMesh._rebuild();
  20205. }
  20206. };
  20207. /** @hidden */
  20208. AbstractMesh.prototype._resyncLightSources = function () {
  20209. this._lightSources.length = 0;
  20210. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20211. var light = _a[_i];
  20212. if (!light.isEnabled()) {
  20213. continue;
  20214. }
  20215. if (light.canAffectMesh(this)) {
  20216. this._lightSources.push(light);
  20217. }
  20218. }
  20219. this._markSubMeshesAsLightDirty();
  20220. };
  20221. /** @hidden */
  20222. AbstractMesh.prototype._resyncLighSource = function (light) {
  20223. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20224. var index = this._lightSources.indexOf(light);
  20225. if (index === -1) {
  20226. if (!isIn) {
  20227. return;
  20228. }
  20229. this._lightSources.push(light);
  20230. }
  20231. else {
  20232. if (isIn) {
  20233. return;
  20234. }
  20235. this._lightSources.splice(index, 1);
  20236. }
  20237. this._markSubMeshesAsLightDirty();
  20238. };
  20239. /** @hidden */
  20240. AbstractMesh.prototype._unBindEffect = function () {
  20241. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20242. var subMesh = _a[_i];
  20243. subMesh.setEffect(null);
  20244. }
  20245. };
  20246. /** @hidden */
  20247. AbstractMesh.prototype._removeLightSource = function (light) {
  20248. var index = this._lightSources.indexOf(light);
  20249. if (index === -1) {
  20250. return;
  20251. }
  20252. this._lightSources.splice(index, 1);
  20253. this._markSubMeshesAsLightDirty();
  20254. };
  20255. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20256. if (!this.subMeshes) {
  20257. return;
  20258. }
  20259. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20260. var subMesh = _a[_i];
  20261. if (subMesh._materialDefines) {
  20262. func(subMesh._materialDefines);
  20263. }
  20264. }
  20265. };
  20266. /** @hidden */
  20267. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20268. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20269. };
  20270. /** @hidden */
  20271. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20272. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20273. };
  20274. /** @hidden */
  20275. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20276. if (!this.subMeshes) {
  20277. return;
  20278. }
  20279. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20280. var subMesh = _a[_i];
  20281. var material = subMesh.getMaterial();
  20282. if (material) {
  20283. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20284. }
  20285. }
  20286. };
  20287. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20288. /**
  20289. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20290. */
  20291. get: function () {
  20292. return this._scaling;
  20293. },
  20294. set: function (newScaling) {
  20295. this._scaling = newScaling;
  20296. if (this.physicsImpostor) {
  20297. this.physicsImpostor.forceUpdate();
  20298. }
  20299. },
  20300. enumerable: true,
  20301. configurable: true
  20302. });
  20303. // Methods
  20304. /**
  20305. * Disables the mesh edge rendering mode
  20306. * @returns the currentAbstractMesh
  20307. */
  20308. AbstractMesh.prototype.disableEdgesRendering = function () {
  20309. if (this._edgesRenderer) {
  20310. this._edgesRenderer.dispose();
  20311. this._edgesRenderer = null;
  20312. }
  20313. return this;
  20314. };
  20315. /**
  20316. * Enables the edge rendering mode on the mesh.
  20317. * This mode makes the mesh edges visible
  20318. * @param epsilon defines the maximal distance between two angles to detect a face
  20319. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20320. * @returns the currentAbstractMesh
  20321. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20322. */
  20323. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20324. if (epsilon === void 0) { epsilon = 0.95; }
  20325. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20326. this.disableEdgesRendering();
  20327. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20328. return this;
  20329. };
  20330. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20331. /**
  20332. * Gets the edgesRenderer associated with the mesh
  20333. */
  20334. get: function () {
  20335. return this._edgesRenderer;
  20336. },
  20337. enumerable: true,
  20338. configurable: true
  20339. });
  20340. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20341. /**
  20342. * Returns true if the mesh is blocked. Implemented by child classes
  20343. */
  20344. get: function () {
  20345. return false;
  20346. },
  20347. enumerable: true,
  20348. configurable: true
  20349. });
  20350. /**
  20351. * Returns the mesh itself by default. Implemented by child classes
  20352. * @param camera defines the camera to use to pick the right LOD level
  20353. * @returns the currentAbstractMesh
  20354. */
  20355. AbstractMesh.prototype.getLOD = function (camera) {
  20356. return this;
  20357. };
  20358. /**
  20359. * Returns 0 by default. Implemented by child classes
  20360. * @returns an integer
  20361. */
  20362. AbstractMesh.prototype.getTotalVertices = function () {
  20363. return 0;
  20364. };
  20365. /**
  20366. * Returns null by default. Implemented by child classes
  20367. * @returns null
  20368. */
  20369. AbstractMesh.prototype.getIndices = function () {
  20370. return null;
  20371. };
  20372. /**
  20373. * Returns the array of the requested vertex data kind. Implemented by child classes
  20374. * @param kind defines the vertex data kind to use
  20375. * @returns null
  20376. */
  20377. AbstractMesh.prototype.getVerticesData = function (kind) {
  20378. return null;
  20379. };
  20380. /**
  20381. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20382. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20383. * Note that a new underlying VertexBuffer object is created each call.
  20384. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20385. * @param kind defines vertex data kind:
  20386. * * BABYLON.VertexBuffer.PositionKind
  20387. * * BABYLON.VertexBuffer.UVKind
  20388. * * BABYLON.VertexBuffer.UV2Kind
  20389. * * BABYLON.VertexBuffer.UV3Kind
  20390. * * BABYLON.VertexBuffer.UV4Kind
  20391. * * BABYLON.VertexBuffer.UV5Kind
  20392. * * BABYLON.VertexBuffer.UV6Kind
  20393. * * BABYLON.VertexBuffer.ColorKind
  20394. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20395. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20396. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20397. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20398. * @param data defines the data source
  20399. * @param updatable defines if the data must be flagged as updatable (or static)
  20400. * @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
  20401. * @returns the current mesh
  20402. */
  20403. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20404. return this;
  20405. };
  20406. /**
  20407. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20408. * If the mesh has no geometry, it is simply returned as it is.
  20409. * @param kind defines vertex data kind:
  20410. * * BABYLON.VertexBuffer.PositionKind
  20411. * * BABYLON.VertexBuffer.UVKind
  20412. * * BABYLON.VertexBuffer.UV2Kind
  20413. * * BABYLON.VertexBuffer.UV3Kind
  20414. * * BABYLON.VertexBuffer.UV4Kind
  20415. * * BABYLON.VertexBuffer.UV5Kind
  20416. * * BABYLON.VertexBuffer.UV6Kind
  20417. * * BABYLON.VertexBuffer.ColorKind
  20418. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20419. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20420. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20421. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20422. * @param data defines the data source
  20423. * @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
  20424. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20425. * @returns the current mesh
  20426. */
  20427. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20428. return this;
  20429. };
  20430. /**
  20431. * Sets the mesh indices,
  20432. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20433. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20434. * @param totalVertices Defines the total number of vertices
  20435. * @returns the current mesh
  20436. */
  20437. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20438. return this;
  20439. };
  20440. /**
  20441. * Gets a boolean indicating if specific vertex data is present
  20442. * @param kind defines the vertex data kind to use
  20443. * @returns true is data kind is present
  20444. */
  20445. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20446. return false;
  20447. };
  20448. /**
  20449. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20450. * @returns a BoundingInfo
  20451. */
  20452. AbstractMesh.prototype.getBoundingInfo = function () {
  20453. if (this._masterMesh) {
  20454. return this._masterMesh.getBoundingInfo();
  20455. }
  20456. if (!this._boundingInfo) {
  20457. // this._boundingInfo is being created here
  20458. this._updateBoundingInfo();
  20459. }
  20460. // cannot be null.
  20461. return this._boundingInfo;
  20462. };
  20463. /**
  20464. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20465. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20466. * @returns the current mesh
  20467. */
  20468. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20469. if (includeDescendants === void 0) { includeDescendants = true; }
  20470. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20471. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20472. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20473. if (maxDimension === 0) {
  20474. return this;
  20475. }
  20476. var scale = 1 / maxDimension;
  20477. this.scaling.scaleInPlace(scale);
  20478. return this;
  20479. };
  20480. /**
  20481. * Overwrite the current bounding info
  20482. * @param boundingInfo defines the new bounding info
  20483. * @returns the current mesh
  20484. */
  20485. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20486. this._boundingInfo = boundingInfo;
  20487. return this;
  20488. };
  20489. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20490. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20491. get: function () {
  20492. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20493. },
  20494. enumerable: true,
  20495. configurable: true
  20496. });
  20497. /** @hidden */
  20498. AbstractMesh.prototype._preActivate = function () {
  20499. };
  20500. /** @hidden */
  20501. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20502. };
  20503. /** @hidden */
  20504. AbstractMesh.prototype._activate = function (renderId) {
  20505. this._renderId = renderId;
  20506. };
  20507. /**
  20508. * Gets the current world matrix
  20509. * @returns a Matrix
  20510. */
  20511. AbstractMesh.prototype.getWorldMatrix = function () {
  20512. if (this._masterMesh) {
  20513. return this._masterMesh.getWorldMatrix();
  20514. }
  20515. return _super.prototype.getWorldMatrix.call(this);
  20516. };
  20517. /** @hidden */
  20518. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20519. if (this._masterMesh) {
  20520. return this._masterMesh._getWorldMatrixDeterminant();
  20521. }
  20522. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20523. };
  20524. // ================================== Point of View Movement =================================
  20525. /**
  20526. * Perform relative position change from the point of view of behind the front of the mesh.
  20527. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20528. * Supports definition of mesh facing forward or backward
  20529. * @param amountRight defines the distance on the right axis
  20530. * @param amountUp defines the distance on the up axis
  20531. * @param amountForward defines the distance on the forward axis
  20532. * @returns the current mesh
  20533. */
  20534. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20535. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20536. return this;
  20537. };
  20538. /**
  20539. * Calculate relative position change from the point of view of behind the front of the mesh.
  20540. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20541. * Supports definition of mesh facing forward or backward
  20542. * @param amountRight defines the distance on the right axis
  20543. * @param amountUp defines the distance on the up axis
  20544. * @param amountForward defines the distance on the forward axis
  20545. * @returns the new displacement vector
  20546. */
  20547. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20548. var rotMatrix = new BABYLON.Matrix();
  20549. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20550. rotQuaternion.toRotationMatrix(rotMatrix);
  20551. var translationDelta = BABYLON.Vector3.Zero();
  20552. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20553. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20554. return translationDelta;
  20555. };
  20556. // ================================== Point of View Rotation =================================
  20557. /**
  20558. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20559. * Supports definition of mesh facing forward or backward
  20560. * @param flipBack defines the flip
  20561. * @param twirlClockwise defines the twirl
  20562. * @param tiltRight defines the tilt
  20563. * @returns the current mesh
  20564. */
  20565. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20566. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20567. return this;
  20568. };
  20569. /**
  20570. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20571. * Supports definition of mesh facing forward or backward.
  20572. * @param flipBack defines the flip
  20573. * @param twirlClockwise defines the twirl
  20574. * @param tiltRight defines the tilt
  20575. * @returns the new rotation vector
  20576. */
  20577. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20578. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20579. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20580. };
  20581. /**
  20582. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20583. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20584. * @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
  20585. * @returns the new bounding vectors
  20586. */
  20587. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20588. if (includeDescendants === void 0) { includeDescendants = true; }
  20589. if (predicate === void 0) { predicate = null; }
  20590. // Ensures that all world matrix will be recomputed.
  20591. this.getScene().incrementRenderId();
  20592. this.computeWorldMatrix(true);
  20593. var min;
  20594. var max;
  20595. var boundingInfo = this.getBoundingInfo();
  20596. if (!this.subMeshes) {
  20597. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20598. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20599. }
  20600. else {
  20601. min = boundingInfo.boundingBox.minimumWorld;
  20602. max = boundingInfo.boundingBox.maximumWorld;
  20603. }
  20604. if (includeDescendants) {
  20605. var descendants = this.getDescendants(false);
  20606. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20607. var descendant = descendants_1[_i];
  20608. var childMesh = descendant;
  20609. childMesh.computeWorldMatrix(true);
  20610. // Filters meshes based on custom predicate function.
  20611. if (predicate && !predicate(childMesh)) {
  20612. continue;
  20613. }
  20614. //make sure we have the needed params to get mix and max
  20615. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20616. continue;
  20617. }
  20618. var childBoundingInfo = childMesh.getBoundingInfo();
  20619. var boundingBox = childBoundingInfo.boundingBox;
  20620. var minBox = boundingBox.minimumWorld;
  20621. var maxBox = boundingBox.maximumWorld;
  20622. BABYLON.Tools.CheckExtends(minBox, min, max);
  20623. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20624. }
  20625. }
  20626. return {
  20627. min: min,
  20628. max: max
  20629. };
  20630. };
  20631. /** @hidden */
  20632. AbstractMesh.prototype._updateBoundingInfo = function () {
  20633. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20634. this._boundingInfo.update(this.worldMatrixFromCache);
  20635. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20636. return this;
  20637. };
  20638. /** @hidden */
  20639. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20640. if (!this.subMeshes) {
  20641. return this;
  20642. }
  20643. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20644. var subMesh = this.subMeshes[subIndex];
  20645. if (!subMesh.IsGlobal) {
  20646. subMesh.updateBoundingInfo(matrix);
  20647. }
  20648. }
  20649. return this;
  20650. };
  20651. /** @hidden */
  20652. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20653. // Bounding info
  20654. this._updateBoundingInfo();
  20655. };
  20656. /**
  20657. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20658. * A mesh is in the frustum if its bounding box intersects the frustum
  20659. * @param frustumPlanes defines the frustum to test
  20660. * @returns true if the mesh is in the frustum planes
  20661. */
  20662. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20663. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20664. };
  20665. /**
  20666. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20667. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20668. * @param frustumPlanes defines the frustum to test
  20669. * @returns true if the mesh is completely in the frustum planes
  20670. */
  20671. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20672. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20673. };
  20674. /**
  20675. * True if the mesh intersects another mesh or a SolidParticle object
  20676. * @param mesh defines a target mesh or SolidParticle to test
  20677. * @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)
  20678. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20679. * @returns true if there is an intersection
  20680. */
  20681. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20682. if (precise === void 0) { precise = false; }
  20683. if (!this._boundingInfo || !mesh._boundingInfo) {
  20684. return false;
  20685. }
  20686. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20687. return true;
  20688. }
  20689. if (includeDescendants) {
  20690. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20691. var child = _a[_i];
  20692. if (child.intersectsMesh(mesh, precise, true)) {
  20693. return true;
  20694. }
  20695. }
  20696. }
  20697. return false;
  20698. };
  20699. /**
  20700. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20701. * @param point defines the point to test
  20702. * @returns true if there is an intersection
  20703. */
  20704. AbstractMesh.prototype.intersectsPoint = function (point) {
  20705. if (!this._boundingInfo) {
  20706. return false;
  20707. }
  20708. return this._boundingInfo.intersectsPoint(point);
  20709. };
  20710. /**
  20711. * Gets the current physics impostor
  20712. * @see http://doc.babylonjs.com/features/physics_engine
  20713. * @returns a physics impostor or null
  20714. */
  20715. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20716. return this.physicsImpostor;
  20717. };
  20718. /**
  20719. * Gets the position of the current mesh in camera space
  20720. * @param camera defines the camera to use
  20721. * @returns a position
  20722. */
  20723. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20724. if (camera === void 0) { camera = null; }
  20725. if (!camera) {
  20726. camera = this.getScene().activeCamera;
  20727. }
  20728. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20729. };
  20730. /**
  20731. * Returns the distance from the mesh to the active camera
  20732. * @param camera defines the camera to use
  20733. * @returns the distance
  20734. */
  20735. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20736. if (camera === void 0) { camera = null; }
  20737. if (!camera) {
  20738. camera = this.getScene().activeCamera;
  20739. }
  20740. return this.absolutePosition.subtract(camera.position).length();
  20741. };
  20742. /**
  20743. * Apply a physic impulse to the mesh
  20744. * @param force defines the force to apply
  20745. * @param contactPoint defines where to apply the force
  20746. * @returns the current mesh
  20747. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20748. */
  20749. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20750. if (!this.physicsImpostor) {
  20751. return this;
  20752. }
  20753. this.physicsImpostor.applyImpulse(force, contactPoint);
  20754. return this;
  20755. };
  20756. /**
  20757. * Creates a physic joint between two meshes
  20758. * @param otherMesh defines the other mesh to use
  20759. * @param pivot1 defines the pivot to use on this mesh
  20760. * @param pivot2 defines the pivot to use on the other mesh
  20761. * @param options defines additional options (can be plugin dependent)
  20762. * @returns the current mesh
  20763. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20764. */
  20765. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20766. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20767. return this;
  20768. }
  20769. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20770. mainPivot: pivot1,
  20771. connectedPivot: pivot2,
  20772. nativeParams: options
  20773. });
  20774. return this;
  20775. };
  20776. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20777. // Collisions
  20778. /**
  20779. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20780. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20781. */
  20782. get: function () {
  20783. return this._checkCollisions;
  20784. },
  20785. set: function (collisionEnabled) {
  20786. this._checkCollisions = collisionEnabled;
  20787. if (this.getScene().workerCollisions) {
  20788. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20789. }
  20790. },
  20791. enumerable: true,
  20792. configurable: true
  20793. });
  20794. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20795. /**
  20796. * Gets Collider object used to compute collisions (not physics)
  20797. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20798. */
  20799. get: function () {
  20800. return this._collider;
  20801. },
  20802. enumerable: true,
  20803. configurable: true
  20804. });
  20805. /**
  20806. * Move the mesh using collision engine
  20807. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20808. * @param displacement defines the requested displacement vector
  20809. * @returns the current mesh
  20810. */
  20811. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20812. var globalPosition = this.getAbsolutePosition();
  20813. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20814. if (!this._collider) {
  20815. this._collider = new BABYLON.Collider();
  20816. }
  20817. this._collider._radius = this.ellipsoid;
  20818. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20819. return this;
  20820. };
  20821. // Submeshes octree
  20822. /**
  20823. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20824. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20825. * @param maxCapacity defines the maximum size of each block (64 by default)
  20826. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20827. * @returns the new octree
  20828. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20829. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20830. */
  20831. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20832. if (maxCapacity === void 0) { maxCapacity = 64; }
  20833. if (maxDepth === void 0) { maxDepth = 2; }
  20834. if (!this._submeshesOctree) {
  20835. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20836. }
  20837. this.computeWorldMatrix(true);
  20838. var boundingInfo = this.getBoundingInfo();
  20839. // Update octree
  20840. var bbox = boundingInfo.boundingBox;
  20841. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20842. return this._submeshesOctree;
  20843. };
  20844. // Collisions
  20845. /** @hidden */
  20846. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20847. this._generatePointsArray();
  20848. if (!this._positions) {
  20849. return this;
  20850. }
  20851. // Transformation
  20852. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20853. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20854. subMesh._lastColliderWorldVertices = [];
  20855. subMesh._trianglePlanes = [];
  20856. var start = subMesh.verticesStart;
  20857. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20858. for (var i = start; i < end; i++) {
  20859. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20860. }
  20861. }
  20862. // Collide
  20863. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20864. if (collider.collisionFound) {
  20865. collider.collidedMesh = this;
  20866. }
  20867. return this;
  20868. };
  20869. /** @hidden */
  20870. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20871. var subMeshes;
  20872. var len;
  20873. // Octrees
  20874. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20875. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20876. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20877. len = intersections.length;
  20878. subMeshes = intersections.data;
  20879. }
  20880. else {
  20881. subMeshes = this.subMeshes;
  20882. len = subMeshes.length;
  20883. }
  20884. for (var index = 0; index < len; index++) {
  20885. var subMesh = subMeshes[index];
  20886. // Bounding test
  20887. if (len > 1 && !subMesh._checkCollision(collider))
  20888. continue;
  20889. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20890. }
  20891. return this;
  20892. };
  20893. /** @hidden */
  20894. AbstractMesh.prototype._checkCollision = function (collider) {
  20895. // Bounding box test
  20896. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20897. return this;
  20898. // Transformation matrix
  20899. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20900. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20901. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20902. return this;
  20903. };
  20904. // Picking
  20905. /** @hidden */
  20906. AbstractMesh.prototype._generatePointsArray = function () {
  20907. return false;
  20908. };
  20909. /**
  20910. * Checks if the passed Ray intersects with the mesh
  20911. * @param ray defines the ray to use
  20912. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20913. * @returns the picking info
  20914. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20915. */
  20916. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20917. var pickingInfo = new BABYLON.PickingInfo();
  20918. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20919. return pickingInfo;
  20920. }
  20921. if (!this._generatePointsArray()) {
  20922. return pickingInfo;
  20923. }
  20924. var intersectInfo = null;
  20925. // Octrees
  20926. var subMeshes;
  20927. var len;
  20928. if (this._submeshesOctree && this.useOctreeForPicking) {
  20929. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20930. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20931. len = intersections.length;
  20932. subMeshes = intersections.data;
  20933. }
  20934. else {
  20935. subMeshes = this.subMeshes;
  20936. len = subMeshes.length;
  20937. }
  20938. for (var index = 0; index < len; index++) {
  20939. var subMesh = subMeshes[index];
  20940. // Bounding test
  20941. if (len > 1 && !subMesh.canIntersects(ray))
  20942. continue;
  20943. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20944. if (currentIntersectInfo) {
  20945. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20946. intersectInfo = currentIntersectInfo;
  20947. intersectInfo.subMeshId = index;
  20948. if (fastCheck) {
  20949. break;
  20950. }
  20951. }
  20952. }
  20953. }
  20954. if (intersectInfo) {
  20955. // Get picked point
  20956. var world = this.getWorldMatrix();
  20957. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20958. var direction = ray.direction.clone();
  20959. direction = direction.scale(intersectInfo.distance);
  20960. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20961. var pickedPoint = worldOrigin.add(worldDirection);
  20962. // Return result
  20963. pickingInfo.hit = true;
  20964. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20965. pickingInfo.pickedPoint = pickedPoint;
  20966. pickingInfo.pickedMesh = this;
  20967. pickingInfo.bu = intersectInfo.bu || 0;
  20968. pickingInfo.bv = intersectInfo.bv || 0;
  20969. pickingInfo.faceId = intersectInfo.faceId;
  20970. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20971. return pickingInfo;
  20972. }
  20973. return pickingInfo;
  20974. };
  20975. /**
  20976. * Clones the current mesh
  20977. * @param name defines the mesh name
  20978. * @param newParent defines the new mesh parent
  20979. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20980. * @returns the new mesh
  20981. */
  20982. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20983. return null;
  20984. };
  20985. /**
  20986. * Disposes all the submeshes of the current meshnp
  20987. * @returns the current mesh
  20988. */
  20989. AbstractMesh.prototype.releaseSubMeshes = function () {
  20990. if (this.subMeshes) {
  20991. while (this.subMeshes.length) {
  20992. this.subMeshes[0].dispose();
  20993. }
  20994. }
  20995. else {
  20996. this.subMeshes = new Array();
  20997. }
  20998. return this;
  20999. };
  21000. /**
  21001. * Releases resources associated with this abstract mesh.
  21002. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21003. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21004. */
  21005. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21006. var _this = this;
  21007. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21008. var index;
  21009. // Smart Array Retainers.
  21010. this.getScene().freeActiveMeshes();
  21011. this.getScene().freeRenderingGroups();
  21012. // Action manager
  21013. if (this.actionManager !== undefined && this.actionManager !== null) {
  21014. this.actionManager.dispose();
  21015. this.actionManager = null;
  21016. }
  21017. // Skeleton
  21018. this._skeleton = null;
  21019. // Physics
  21020. if (this.physicsImpostor) {
  21021. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21022. }
  21023. // Intersections in progress
  21024. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21025. var other = this._intersectionsInProgress[index];
  21026. var pos = other._intersectionsInProgress.indexOf(this);
  21027. other._intersectionsInProgress.splice(pos, 1);
  21028. }
  21029. this._intersectionsInProgress = [];
  21030. // Lights
  21031. var lights = this.getScene().lights;
  21032. lights.forEach(function (light) {
  21033. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21034. if (meshIndex !== -1) {
  21035. light.includedOnlyMeshes.splice(meshIndex, 1);
  21036. }
  21037. meshIndex = light.excludedMeshes.indexOf(_this);
  21038. if (meshIndex !== -1) {
  21039. light.excludedMeshes.splice(meshIndex, 1);
  21040. }
  21041. // Shadow generators
  21042. var generator = light.getShadowGenerator();
  21043. if (generator) {
  21044. var shadowMap = generator.getShadowMap();
  21045. if (shadowMap && shadowMap.renderList) {
  21046. meshIndex = shadowMap.renderList.indexOf(_this);
  21047. if (meshIndex !== -1) {
  21048. shadowMap.renderList.splice(meshIndex, 1);
  21049. }
  21050. }
  21051. }
  21052. });
  21053. // Edges
  21054. if (this._edgesRenderer) {
  21055. this._edgesRenderer.dispose();
  21056. this._edgesRenderer = null;
  21057. }
  21058. // SubMeshes
  21059. if (this.getClassName() !== "InstancedMesh") {
  21060. this.releaseSubMeshes();
  21061. }
  21062. // Octree
  21063. var sceneOctree = this.getScene().selectionOctree;
  21064. if (sceneOctree !== undefined && sceneOctree !== null) {
  21065. var index = sceneOctree.dynamicContent.indexOf(this);
  21066. if (index !== -1) {
  21067. sceneOctree.dynamicContent.splice(index, 1);
  21068. }
  21069. }
  21070. // Query
  21071. var engine = this.getScene().getEngine();
  21072. if (this._occlusionQuery) {
  21073. this._isOcclusionQueryInProgress = false;
  21074. engine.deleteQuery(this._occlusionQuery);
  21075. this._occlusionQuery = null;
  21076. }
  21077. // Engine
  21078. engine.wipeCaches();
  21079. // Remove from scene
  21080. this.getScene().removeMesh(this);
  21081. if (disposeMaterialAndTextures) {
  21082. if (this.material) {
  21083. this.material.dispose(false, true);
  21084. }
  21085. }
  21086. if (!doNotRecurse) {
  21087. // Particles
  21088. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21089. if (this.getScene().particleSystems[index].emitter === this) {
  21090. this.getScene().particleSystems[index].dispose();
  21091. index--;
  21092. }
  21093. }
  21094. }
  21095. // facet data
  21096. if (this._facetDataEnabled) {
  21097. this.disableFacetData();
  21098. }
  21099. this.onAfterWorldMatrixUpdateObservable.clear();
  21100. this.onCollideObservable.clear();
  21101. this.onCollisionPositionChangeObservable.clear();
  21102. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21103. };
  21104. /**
  21105. * Adds the passed mesh as a child to the current mesh
  21106. * @param mesh defines the child mesh
  21107. * @returns the current mesh
  21108. */
  21109. AbstractMesh.prototype.addChild = function (mesh) {
  21110. mesh.setParent(this);
  21111. return this;
  21112. };
  21113. /**
  21114. * Removes the passed mesh from the current mesh children list
  21115. * @param mesh defines the child mesh
  21116. * @returns the current mesh
  21117. */
  21118. AbstractMesh.prototype.removeChild = function (mesh) {
  21119. mesh.setParent(null);
  21120. return this;
  21121. };
  21122. // Facet data
  21123. /** @hidden */
  21124. AbstractMesh.prototype._initFacetData = function () {
  21125. if (!this._facetNormals) {
  21126. this._facetNormals = new Array();
  21127. }
  21128. if (!this._facetPositions) {
  21129. this._facetPositions = new Array();
  21130. }
  21131. if (!this._facetPartitioning) {
  21132. this._facetPartitioning = new Array();
  21133. }
  21134. this._facetNb = (this.getIndices().length / 3) | 0;
  21135. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21136. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21137. for (var f = 0; f < this._facetNb; f++) {
  21138. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21139. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21140. }
  21141. this._facetDataEnabled = true;
  21142. return this;
  21143. };
  21144. /**
  21145. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21146. * This method can be called within the render loop.
  21147. * 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
  21148. * @returns the current mesh
  21149. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21150. */
  21151. AbstractMesh.prototype.updateFacetData = function () {
  21152. if (!this._facetDataEnabled) {
  21153. this._initFacetData();
  21154. }
  21155. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21156. var indices = this.getIndices();
  21157. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21158. var bInfo = this.getBoundingInfo();
  21159. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21160. // init arrays, matrix and sort function on first call
  21161. this._facetDepthSortEnabled = true;
  21162. if (indices instanceof Uint16Array) {
  21163. this._depthSortedIndices = new Uint16Array(indices);
  21164. }
  21165. else if (indices instanceof Uint32Array) {
  21166. this._depthSortedIndices = new Uint32Array(indices);
  21167. }
  21168. else {
  21169. var needs32bits = false;
  21170. for (var i = 0; i < indices.length; i++) {
  21171. if (indices[i] > 65535) {
  21172. needs32bits = true;
  21173. break;
  21174. }
  21175. }
  21176. if (needs32bits) {
  21177. this._depthSortedIndices = new Uint32Array(indices);
  21178. }
  21179. else {
  21180. this._depthSortedIndices = new Uint16Array(indices);
  21181. }
  21182. }
  21183. this._facetDepthSortFunction = function (f1, f2) {
  21184. return (f2.sqDistance - f1.sqDistance);
  21185. };
  21186. if (!this._facetDepthSortFrom) {
  21187. var camera = this.getScene().activeCamera;
  21188. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21189. }
  21190. this._depthSortedFacets = [];
  21191. for (var f = 0; f < this._facetNb; f++) {
  21192. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21193. this._depthSortedFacets.push(depthSortedFacet);
  21194. }
  21195. this._invertedMatrix = BABYLON.Matrix.Identity();
  21196. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21197. }
  21198. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21199. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21200. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21201. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21202. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21203. this._subDiv.max = this._partitioningSubdivisions;
  21204. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21205. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21206. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21207. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21208. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21209. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21210. // set the parameters for ComputeNormals()
  21211. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21212. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21213. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21214. this._facetParameters.bInfo = bInfo;
  21215. this._facetParameters.bbSize = this._bbSize;
  21216. this._facetParameters.subDiv = this._subDiv;
  21217. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21218. this._facetParameters.depthSort = this._facetDepthSort;
  21219. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21220. this.computeWorldMatrix(true);
  21221. this._worldMatrix.invertToRef(this._invertedMatrix);
  21222. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21223. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21224. }
  21225. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21226. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21227. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21228. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21229. var l = (this._depthSortedIndices.length / 3) | 0;
  21230. for (var f = 0; f < l; f++) {
  21231. var sind = this._depthSortedFacets[f].ind;
  21232. this._depthSortedIndices[f * 3] = indices[sind];
  21233. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21234. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21235. }
  21236. this.updateIndices(this._depthSortedIndices);
  21237. }
  21238. return this;
  21239. };
  21240. /**
  21241. * Returns the facetLocalNormals array.
  21242. * The normals are expressed in the mesh local spac
  21243. * @returns an array of Vector3
  21244. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21245. */
  21246. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21247. if (!this._facetNormals) {
  21248. this.updateFacetData();
  21249. }
  21250. return this._facetNormals;
  21251. };
  21252. /**
  21253. * Returns the facetLocalPositions array.
  21254. * The facet positions are expressed in the mesh local space
  21255. * @returns an array of Vector3
  21256. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21257. */
  21258. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21259. if (!this._facetPositions) {
  21260. this.updateFacetData();
  21261. }
  21262. return this._facetPositions;
  21263. };
  21264. /**
  21265. * Returns the facetLocalPartioning array
  21266. * @returns an array of array of numbers
  21267. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21268. */
  21269. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21270. if (!this._facetPartitioning) {
  21271. this.updateFacetData();
  21272. }
  21273. return this._facetPartitioning;
  21274. };
  21275. /**
  21276. * Returns the i-th facet position in the world system.
  21277. * This method allocates a new Vector3 per call
  21278. * @param i defines the facet index
  21279. * @returns a new Vector3
  21280. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21281. */
  21282. AbstractMesh.prototype.getFacetPosition = function (i) {
  21283. var pos = BABYLON.Vector3.Zero();
  21284. this.getFacetPositionToRef(i, pos);
  21285. return pos;
  21286. };
  21287. /**
  21288. * Sets the reference Vector3 with the i-th facet position in the world system
  21289. * @param i defines the facet index
  21290. * @param ref defines the target vector
  21291. * @returns the current mesh
  21292. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21293. */
  21294. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21295. var localPos = (this.getFacetLocalPositions())[i];
  21296. var world = this.getWorldMatrix();
  21297. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21298. return this;
  21299. };
  21300. /**
  21301. * Returns the i-th facet normal in the world system.
  21302. * This method allocates a new Vector3 per call
  21303. * @param i defines the facet index
  21304. * @returns a new Vector3
  21305. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21306. */
  21307. AbstractMesh.prototype.getFacetNormal = function (i) {
  21308. var norm = BABYLON.Vector3.Zero();
  21309. this.getFacetNormalToRef(i, norm);
  21310. return norm;
  21311. };
  21312. /**
  21313. * Sets the reference Vector3 with the i-th facet normal in the world system
  21314. * @param i defines the facet index
  21315. * @param ref defines the target vector
  21316. * @returns the current mesh
  21317. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21318. */
  21319. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21320. var localNorm = (this.getFacetLocalNormals())[i];
  21321. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21322. return this;
  21323. };
  21324. /**
  21325. * 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)
  21326. * @param x defines x coordinate
  21327. * @param y defines y coordinate
  21328. * @param z defines z coordinate
  21329. * @returns the array of facet indexes
  21330. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21331. */
  21332. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21333. var bInfo = this.getBoundingInfo();
  21334. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21335. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21336. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21337. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21338. return null;
  21339. }
  21340. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21341. };
  21342. /**
  21343. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21344. * @param projected sets as the (x,y,z) world projection on the facet
  21345. * @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
  21346. * @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
  21347. * @param x defines x coordinate
  21348. * @param y defines y coordinate
  21349. * @param z defines z coordinate
  21350. * @returns the face index if found (or null instead)
  21351. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21352. */
  21353. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21354. if (checkFace === void 0) { checkFace = false; }
  21355. if (facing === void 0) { facing = true; }
  21356. var world = this.getWorldMatrix();
  21357. var invMat = BABYLON.Tmp.Matrix[5];
  21358. world.invertToRef(invMat);
  21359. var invVect = BABYLON.Tmp.Vector3[8];
  21360. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21361. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21362. if (projected) {
  21363. // tranform the local computed projected vector to world coordinates
  21364. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21365. }
  21366. return closest;
  21367. };
  21368. /**
  21369. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21370. * @param projected sets as the (x,y,z) local projection on the facet
  21371. * @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
  21372. * @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
  21373. * @param x defines x coordinate
  21374. * @param y defines y coordinate
  21375. * @param z defines z coordinate
  21376. * @returns the face index if found (or null instead)
  21377. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21378. */
  21379. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21380. if (checkFace === void 0) { checkFace = false; }
  21381. if (facing === void 0) { facing = true; }
  21382. var closest = null;
  21383. var tmpx = 0.0;
  21384. var tmpy = 0.0;
  21385. var tmpz = 0.0;
  21386. var d = 0.0; // tmp dot facet normal * facet position
  21387. var t0 = 0.0;
  21388. var projx = 0.0;
  21389. var projy = 0.0;
  21390. var projz = 0.0;
  21391. // Get all the facets in the same partitioning block than (x, y, z)
  21392. var facetPositions = this.getFacetLocalPositions();
  21393. var facetNormals = this.getFacetLocalNormals();
  21394. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21395. if (!facetsInBlock) {
  21396. return null;
  21397. }
  21398. // Get the closest facet to (x, y, z)
  21399. var shortest = Number.MAX_VALUE; // init distance vars
  21400. var tmpDistance = shortest;
  21401. var fib; // current facet in the block
  21402. var norm; // current facet normal
  21403. var p0; // current facet barycenter position
  21404. // loop on all the facets in the current partitioning block
  21405. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21406. fib = facetsInBlock[idx];
  21407. norm = facetNormals[fib];
  21408. p0 = facetPositions[fib];
  21409. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21410. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21411. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21412. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21413. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21414. projx = x + norm.x * t0;
  21415. projy = y + norm.y * t0;
  21416. projz = z + norm.z * t0;
  21417. tmpx = projx - x;
  21418. tmpy = projy - y;
  21419. tmpz = projz - z;
  21420. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21421. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21422. shortest = tmpDistance;
  21423. closest = fib;
  21424. if (projected) {
  21425. projected.x = projx;
  21426. projected.y = projy;
  21427. projected.z = projz;
  21428. }
  21429. }
  21430. }
  21431. }
  21432. return closest;
  21433. };
  21434. /**
  21435. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21436. * @returns the parameters
  21437. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21438. */
  21439. AbstractMesh.prototype.getFacetDataParameters = function () {
  21440. return this._facetParameters;
  21441. };
  21442. /**
  21443. * Disables the feature FacetData and frees the related memory
  21444. * @returns the current mesh
  21445. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21446. */
  21447. AbstractMesh.prototype.disableFacetData = function () {
  21448. if (this._facetDataEnabled) {
  21449. this._facetDataEnabled = false;
  21450. this._facetPositions = new Array();
  21451. this._facetNormals = new Array();
  21452. this._facetPartitioning = new Array();
  21453. this._facetParameters = null;
  21454. this._depthSortedIndices = new Uint32Array(0);
  21455. }
  21456. return this;
  21457. };
  21458. /**
  21459. * Updates the AbstractMesh indices array
  21460. * @param indices defines the data source
  21461. * @returns the current mesh
  21462. */
  21463. AbstractMesh.prototype.updateIndices = function (indices) {
  21464. return this;
  21465. };
  21466. /**
  21467. * Creates new normals data for the mesh
  21468. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21469. * @returns the current mesh
  21470. */
  21471. AbstractMesh.prototype.createNormals = function (updatable) {
  21472. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21473. var indices = this.getIndices();
  21474. var normals;
  21475. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21476. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21477. }
  21478. else {
  21479. normals = [];
  21480. }
  21481. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21482. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21483. return this;
  21484. };
  21485. /**
  21486. * Align the mesh with a normal
  21487. * @param normal defines the normal to use
  21488. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21489. * @returns the current mesh
  21490. */
  21491. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21492. if (!upDirection) {
  21493. upDirection = BABYLON.Axis.Y;
  21494. }
  21495. var axisX = BABYLON.Tmp.Vector3[0];
  21496. var axisZ = BABYLON.Tmp.Vector3[1];
  21497. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21498. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21499. if (this.rotationQuaternion) {
  21500. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21501. }
  21502. else {
  21503. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21504. }
  21505. return this;
  21506. };
  21507. /** @hidden */
  21508. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21509. var engine = this.getEngine();
  21510. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21511. this._isOccluded = false;
  21512. return;
  21513. }
  21514. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21515. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21516. if (isOcclusionQueryAvailable) {
  21517. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21518. this._isOcclusionQueryInProgress = false;
  21519. this._occlusionInternalRetryCounter = 0;
  21520. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21521. }
  21522. else {
  21523. this._occlusionInternalRetryCounter++;
  21524. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21525. this._isOcclusionQueryInProgress = false;
  21526. this._occlusionInternalRetryCounter = 0;
  21527. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21528. // if strict continue the last state of the object.
  21529. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21530. }
  21531. else {
  21532. return;
  21533. }
  21534. }
  21535. }
  21536. var scene = this.getScene();
  21537. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21538. if (!this._occlusionQuery) {
  21539. this._occlusionQuery = engine.createQuery();
  21540. }
  21541. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21542. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21543. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21544. this._isOcclusionQueryInProgress = true;
  21545. };
  21546. /** No occlusion */
  21547. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21548. /** Occlusion set to optimisitic */
  21549. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21550. /** Occlusion set to strict */
  21551. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21552. /** Use an accurante occlusion algorithm */
  21553. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21554. /** Use a conservative occlusion algorithm */
  21555. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21556. return AbstractMesh;
  21557. }(BABYLON.TransformNode));
  21558. BABYLON.AbstractMesh = AbstractMesh;
  21559. })(BABYLON || (BABYLON = {}));
  21560. //# sourceMappingURL=babylon.abstractMesh.js.map
  21561. var BABYLON;
  21562. (function (BABYLON) {
  21563. /**
  21564. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21565. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21566. * 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.
  21567. */
  21568. var Light = /** @class */ (function (_super) {
  21569. __extends(Light, _super);
  21570. /**
  21571. * Creates a Light object in the scene.
  21572. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21573. * @param name The firendly name of the light
  21574. * @param scene The scene the light belongs too
  21575. */
  21576. function Light(name, scene) {
  21577. var _this = _super.call(this, name, scene) || this;
  21578. /**
  21579. * Diffuse gives the basic color to an object.
  21580. */
  21581. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21582. /**
  21583. * Specular produces a highlight color on an object.
  21584. * Note: This is note affecting PBR materials.
  21585. */
  21586. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21587. /**
  21588. * Strength of the light.
  21589. * Note: By default it is define in the framework own unit.
  21590. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21591. */
  21592. _this.intensity = 1.0;
  21593. /**
  21594. * Defines how far from the source the light is impacting in scene units.
  21595. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21596. */
  21597. _this.range = Number.MAX_VALUE;
  21598. /**
  21599. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21600. * of light.
  21601. */
  21602. _this._photometricScale = 1.0;
  21603. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21604. _this._radius = 0.00001;
  21605. /**
  21606. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21607. * exceeding the number allowed of the materials.
  21608. */
  21609. _this.renderPriority = 0;
  21610. _this._shadowEnabled = true;
  21611. _this._excludeWithLayerMask = 0;
  21612. _this._includeOnlyWithLayerMask = 0;
  21613. _this._lightmapMode = 0;
  21614. /**
  21615. * @hidden Internal use only.
  21616. */
  21617. _this._excludedMeshesIds = new Array();
  21618. /**
  21619. * @hidden Internal use only.
  21620. */
  21621. _this._includedOnlyMeshesIds = new Array();
  21622. _this.getScene().addLight(_this);
  21623. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21624. _this._buildUniformLayout();
  21625. _this.includedOnlyMeshes = new Array();
  21626. _this.excludedMeshes = new Array();
  21627. _this._resyncMeshes();
  21628. return _this;
  21629. }
  21630. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21631. /**
  21632. * If every light affecting the material is in this lightmapMode,
  21633. * material.lightmapTexture adds or multiplies
  21634. * (depends on material.useLightmapAsShadowmap)
  21635. * after every other light calculations.
  21636. */
  21637. get: function () {
  21638. return Light._LIGHTMAP_DEFAULT;
  21639. },
  21640. enumerable: true,
  21641. configurable: true
  21642. });
  21643. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21644. /**
  21645. * material.lightmapTexture as only diffuse lighting from this light
  21646. * adds only specular lighting from this light
  21647. * adds dynamic shadows
  21648. */
  21649. get: function () {
  21650. return Light._LIGHTMAP_SPECULAR;
  21651. },
  21652. enumerable: true,
  21653. configurable: true
  21654. });
  21655. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21656. /**
  21657. * material.lightmapTexture as only lighting
  21658. * no light calculation from this light
  21659. * only adds dynamic shadows from this light
  21660. */
  21661. get: function () {
  21662. return Light._LIGHTMAP_SHADOWSONLY;
  21663. },
  21664. enumerable: true,
  21665. configurable: true
  21666. });
  21667. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21668. /**
  21669. * Each light type uses the default quantity according to its type:
  21670. * point/spot lights use luminous intensity
  21671. * directional lights use illuminance
  21672. */
  21673. get: function () {
  21674. return Light._INTENSITYMODE_AUTOMATIC;
  21675. },
  21676. enumerable: true,
  21677. configurable: true
  21678. });
  21679. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21680. /**
  21681. * lumen (lm)
  21682. */
  21683. get: function () {
  21684. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21685. },
  21686. enumerable: true,
  21687. configurable: true
  21688. });
  21689. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21690. /**
  21691. * candela (lm/sr)
  21692. */
  21693. get: function () {
  21694. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21695. },
  21696. enumerable: true,
  21697. configurable: true
  21698. });
  21699. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21700. /**
  21701. * lux (lm/m^2)
  21702. */
  21703. get: function () {
  21704. return Light._INTENSITYMODE_ILLUMINANCE;
  21705. },
  21706. enumerable: true,
  21707. configurable: true
  21708. });
  21709. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21710. /**
  21711. * nit (cd/m^2)
  21712. */
  21713. get: function () {
  21714. return Light._INTENSITYMODE_LUMINANCE;
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21720. /**
  21721. * Light type const id of the point light.
  21722. */
  21723. get: function () {
  21724. return Light._LIGHTTYPEID_POINTLIGHT;
  21725. },
  21726. enumerable: true,
  21727. configurable: true
  21728. });
  21729. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21730. /**
  21731. * Light type const id of the directional light.
  21732. */
  21733. get: function () {
  21734. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21735. },
  21736. enumerable: true,
  21737. configurable: true
  21738. });
  21739. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21740. /**
  21741. * Light type const id of the spot light.
  21742. */
  21743. get: function () {
  21744. return Light._LIGHTTYPEID_SPOTLIGHT;
  21745. },
  21746. enumerable: true,
  21747. configurable: true
  21748. });
  21749. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21750. /**
  21751. * Light type const id of the hemispheric light.
  21752. */
  21753. get: function () {
  21754. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. Object.defineProperty(Light.prototype, "intensityMode", {
  21760. /**
  21761. * Gets the photometric scale used to interpret the intensity.
  21762. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21763. */
  21764. get: function () {
  21765. return this._intensityMode;
  21766. },
  21767. /**
  21768. * Sets the photometric scale used to interpret the intensity.
  21769. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21770. */
  21771. set: function (value) {
  21772. this._intensityMode = value;
  21773. this._computePhotometricScale();
  21774. },
  21775. enumerable: true,
  21776. configurable: true
  21777. });
  21778. ;
  21779. ;
  21780. Object.defineProperty(Light.prototype, "radius", {
  21781. /**
  21782. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21783. */
  21784. get: function () {
  21785. return this._radius;
  21786. },
  21787. /**
  21788. * sets the light radius used by PBR Materials to simulate soft area lights.
  21789. */
  21790. set: function (value) {
  21791. this._radius = value;
  21792. this._computePhotometricScale();
  21793. },
  21794. enumerable: true,
  21795. configurable: true
  21796. });
  21797. ;
  21798. ;
  21799. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21800. /**
  21801. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21802. * the current shadow generator.
  21803. */
  21804. get: function () {
  21805. return this._shadowEnabled;
  21806. },
  21807. /**
  21808. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21809. * the current shadow generator.
  21810. */
  21811. set: function (value) {
  21812. if (this._shadowEnabled === value) {
  21813. return;
  21814. }
  21815. this._shadowEnabled = value;
  21816. this._markMeshesAsLightDirty();
  21817. },
  21818. enumerable: true,
  21819. configurable: true
  21820. });
  21821. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21822. /**
  21823. * Gets the only meshes impacted by this light.
  21824. */
  21825. get: function () {
  21826. return this._includedOnlyMeshes;
  21827. },
  21828. /**
  21829. * Sets the only meshes impacted by this light.
  21830. */
  21831. set: function (value) {
  21832. this._includedOnlyMeshes = value;
  21833. this._hookArrayForIncludedOnly(value);
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21839. /**
  21840. * Gets the meshes not impacted by this light.
  21841. */
  21842. get: function () {
  21843. return this._excludedMeshes;
  21844. },
  21845. /**
  21846. * Sets the meshes not impacted by this light.
  21847. */
  21848. set: function (value) {
  21849. this._excludedMeshes = value;
  21850. this._hookArrayForExcluded(value);
  21851. },
  21852. enumerable: true,
  21853. configurable: true
  21854. });
  21855. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21856. /**
  21857. * Gets the layer id use to find what meshes are not impacted by the light.
  21858. * Inactive if 0
  21859. */
  21860. get: function () {
  21861. return this._excludeWithLayerMask;
  21862. },
  21863. /**
  21864. * Sets the layer id use to find what meshes are not impacted by the light.
  21865. * Inactive if 0
  21866. */
  21867. set: function (value) {
  21868. this._excludeWithLayerMask = value;
  21869. this._resyncMeshes();
  21870. },
  21871. enumerable: true,
  21872. configurable: true
  21873. });
  21874. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21875. /**
  21876. * Gets the layer id use to find what meshes are impacted by the light.
  21877. * Inactive if 0
  21878. */
  21879. get: function () {
  21880. return this._includeOnlyWithLayerMask;
  21881. },
  21882. /**
  21883. * Sets the layer id use to find what meshes are impacted by the light.
  21884. * Inactive if 0
  21885. */
  21886. set: function (value) {
  21887. this._includeOnlyWithLayerMask = value;
  21888. this._resyncMeshes();
  21889. },
  21890. enumerable: true,
  21891. configurable: true
  21892. });
  21893. Object.defineProperty(Light.prototype, "lightmapMode", {
  21894. /**
  21895. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21896. */
  21897. get: function () {
  21898. return this._lightmapMode;
  21899. },
  21900. /**
  21901. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21902. */
  21903. set: function (value) {
  21904. if (this._lightmapMode === value) {
  21905. return;
  21906. }
  21907. this._lightmapMode = value;
  21908. this._markMeshesAsLightDirty();
  21909. },
  21910. enumerable: true,
  21911. configurable: true
  21912. });
  21913. /**
  21914. * Returns the string "Light".
  21915. * @returns the class name
  21916. */
  21917. Light.prototype.getClassName = function () {
  21918. return "Light";
  21919. };
  21920. /**
  21921. * Converts the light information to a readable string for debug purpose.
  21922. * @param fullDetails Supports for multiple levels of logging within scene loading
  21923. * @returns the human readable light info
  21924. */
  21925. Light.prototype.toString = function (fullDetails) {
  21926. var ret = "Name: " + this.name;
  21927. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21928. if (this.animations) {
  21929. for (var i = 0; i < this.animations.length; i++) {
  21930. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21931. }
  21932. }
  21933. if (fullDetails) {
  21934. }
  21935. return ret;
  21936. };
  21937. /**
  21938. * Set the enabled state of this node.
  21939. * @param value - the new enabled state
  21940. */
  21941. Light.prototype.setEnabled = function (value) {
  21942. _super.prototype.setEnabled.call(this, value);
  21943. this._resyncMeshes();
  21944. };
  21945. /**
  21946. * Returns the Light associated shadow generator if any.
  21947. * @return the associated shadow generator.
  21948. */
  21949. Light.prototype.getShadowGenerator = function () {
  21950. return this._shadowGenerator;
  21951. };
  21952. /**
  21953. * Returns a Vector3, the absolute light position in the World.
  21954. * @returns the world space position of the light
  21955. */
  21956. Light.prototype.getAbsolutePosition = function () {
  21957. return BABYLON.Vector3.Zero();
  21958. };
  21959. /**
  21960. * Specifies if the light will affect the passed mesh.
  21961. * @param mesh The mesh to test against the light
  21962. * @return true the mesh is affected otherwise, false.
  21963. */
  21964. Light.prototype.canAffectMesh = function (mesh) {
  21965. if (!mesh) {
  21966. return true;
  21967. }
  21968. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21969. return false;
  21970. }
  21971. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21972. return false;
  21973. }
  21974. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21975. return false;
  21976. }
  21977. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21978. return false;
  21979. }
  21980. return true;
  21981. };
  21982. /**
  21983. * Computes and Returns the light World matrix.
  21984. * @returns the world matrix
  21985. */
  21986. Light.prototype.getWorldMatrix = function () {
  21987. this._currentRenderId = this.getScene().getRenderId();
  21988. this._childRenderId = this._currentRenderId;
  21989. var worldMatrix = this._getWorldMatrix();
  21990. if (this.parent && this.parent.getWorldMatrix) {
  21991. if (!this._parentedWorldMatrix) {
  21992. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21993. }
  21994. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21995. this._markSyncedWithParent();
  21996. return this._parentedWorldMatrix;
  21997. }
  21998. return worldMatrix;
  21999. };
  22000. /**
  22001. * Sort function to order lights for rendering.
  22002. * @param a First Light object to compare to second.
  22003. * @param b Second Light object to compare first.
  22004. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22005. */
  22006. Light.CompareLightsPriority = function (a, b) {
  22007. //shadow-casting lights have priority over non-shadow-casting lights
  22008. //the renderPrioirty is a secondary sort criterion
  22009. if (a.shadowEnabled !== b.shadowEnabled) {
  22010. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22011. }
  22012. return b.renderPriority - a.renderPriority;
  22013. };
  22014. /**
  22015. * Releases resources associated with this node.
  22016. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22017. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22018. */
  22019. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22020. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22021. if (this._shadowGenerator) {
  22022. this._shadowGenerator.dispose();
  22023. this._shadowGenerator = null;
  22024. }
  22025. // Animations
  22026. this.getScene().stopAnimation(this);
  22027. // Remove from meshes
  22028. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22029. var mesh = _a[_i];
  22030. mesh._removeLightSource(this);
  22031. }
  22032. this._uniformBuffer.dispose();
  22033. // Remove from scene
  22034. this.getScene().removeLight(this);
  22035. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22036. };
  22037. /**
  22038. * Returns the light type ID (integer).
  22039. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22040. */
  22041. Light.prototype.getTypeID = function () {
  22042. return 0;
  22043. };
  22044. /**
  22045. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22046. * @returns the scaled intensity in intensity mode unit
  22047. */
  22048. Light.prototype.getScaledIntensity = function () {
  22049. return this._photometricScale * this.intensity;
  22050. };
  22051. /**
  22052. * Returns a new Light object, named "name", from the current one.
  22053. * @param name The name of the cloned light
  22054. * @returns the new created light
  22055. */
  22056. Light.prototype.clone = function (name) {
  22057. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22058. if (!constructor) {
  22059. return null;
  22060. }
  22061. return BABYLON.SerializationHelper.Clone(constructor, this);
  22062. };
  22063. /**
  22064. * Serializes the current light into a Serialization object.
  22065. * @returns the serialized object.
  22066. */
  22067. Light.prototype.serialize = function () {
  22068. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22069. // Type
  22070. serializationObject.type = this.getTypeID();
  22071. // Parent
  22072. if (this.parent) {
  22073. serializationObject.parentId = this.parent.id;
  22074. }
  22075. // Inclusion / exclusions
  22076. if (this.excludedMeshes.length > 0) {
  22077. serializationObject.excludedMeshesIds = [];
  22078. this.excludedMeshes.forEach(function (mesh) {
  22079. serializationObject.excludedMeshesIds.push(mesh.id);
  22080. });
  22081. }
  22082. if (this.includedOnlyMeshes.length > 0) {
  22083. serializationObject.includedOnlyMeshesIds = [];
  22084. this.includedOnlyMeshes.forEach(function (mesh) {
  22085. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22086. });
  22087. }
  22088. // Animations
  22089. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22090. serializationObject.ranges = this.serializeAnimationRanges();
  22091. return serializationObject;
  22092. };
  22093. /**
  22094. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22095. * This new light is named "name" and added to the passed scene.
  22096. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22097. * @param name The friendly name of the light
  22098. * @param scene The scene the new light will belong to
  22099. * @returns the constructor function
  22100. */
  22101. Light.GetConstructorFromName = function (type, name, scene) {
  22102. switch (type) {
  22103. case 0:
  22104. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22105. case 1:
  22106. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22107. case 2:
  22108. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22109. case 3:
  22110. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22111. }
  22112. return null;
  22113. };
  22114. /**
  22115. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22116. * @param parsedLight The JSON representation of the light
  22117. * @param scene The scene to create the parsed light in
  22118. * @returns the created light after parsing
  22119. */
  22120. Light.Parse = function (parsedLight, scene) {
  22121. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22122. if (!constructor) {
  22123. return null;
  22124. }
  22125. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22126. // Inclusion / exclusions
  22127. if (parsedLight.excludedMeshesIds) {
  22128. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22129. }
  22130. if (parsedLight.includedOnlyMeshesIds) {
  22131. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22132. }
  22133. // Parent
  22134. if (parsedLight.parentId) {
  22135. light._waitingParentId = parsedLight.parentId;
  22136. }
  22137. // Animations
  22138. if (parsedLight.animations) {
  22139. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22140. var parsedAnimation = parsedLight.animations[animationIndex];
  22141. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22142. }
  22143. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22144. }
  22145. if (parsedLight.autoAnimate) {
  22146. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22147. }
  22148. return light;
  22149. };
  22150. Light.prototype._hookArrayForExcluded = function (array) {
  22151. var _this = this;
  22152. var oldPush = array.push;
  22153. array.push = function () {
  22154. var items = [];
  22155. for (var _i = 0; _i < arguments.length; _i++) {
  22156. items[_i] = arguments[_i];
  22157. }
  22158. var result = oldPush.apply(array, items);
  22159. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22160. var item = items_1[_a];
  22161. item._resyncLighSource(_this);
  22162. }
  22163. return result;
  22164. };
  22165. var oldSplice = array.splice;
  22166. array.splice = function (index, deleteCount) {
  22167. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22168. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22169. var item = deleted_1[_i];
  22170. item._resyncLighSource(_this);
  22171. }
  22172. return deleted;
  22173. };
  22174. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22175. var item = array_1[_i];
  22176. item._resyncLighSource(this);
  22177. }
  22178. };
  22179. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22180. var _this = this;
  22181. var oldPush = array.push;
  22182. array.push = function () {
  22183. var items = [];
  22184. for (var _i = 0; _i < arguments.length; _i++) {
  22185. items[_i] = arguments[_i];
  22186. }
  22187. var result = oldPush.apply(array, items);
  22188. _this._resyncMeshes();
  22189. return result;
  22190. };
  22191. var oldSplice = array.splice;
  22192. array.splice = function (index, deleteCount) {
  22193. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22194. _this._resyncMeshes();
  22195. return deleted;
  22196. };
  22197. this._resyncMeshes();
  22198. };
  22199. Light.prototype._resyncMeshes = function () {
  22200. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22201. var mesh = _a[_i];
  22202. mesh._resyncLighSource(this);
  22203. }
  22204. };
  22205. /**
  22206. * Forces the meshes to update their light related information in their rendering used effects
  22207. * @hidden Internal Use Only
  22208. */
  22209. Light.prototype._markMeshesAsLightDirty = function () {
  22210. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22211. var mesh = _a[_i];
  22212. if (mesh._lightSources.indexOf(this) !== -1) {
  22213. mesh._markSubMeshesAsLightDirty();
  22214. }
  22215. }
  22216. };
  22217. /**
  22218. * Recomputes the cached photometric scale if needed.
  22219. */
  22220. Light.prototype._computePhotometricScale = function () {
  22221. this._photometricScale = this._getPhotometricScale();
  22222. this.getScene().resetCachedMaterial();
  22223. };
  22224. /**
  22225. * Returns the Photometric Scale according to the light type and intensity mode.
  22226. */
  22227. Light.prototype._getPhotometricScale = function () {
  22228. var photometricScale = 0.0;
  22229. var lightTypeID = this.getTypeID();
  22230. //get photometric mode
  22231. var photometricMode = this.intensityMode;
  22232. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22233. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22234. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22235. }
  22236. else {
  22237. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22238. }
  22239. }
  22240. //compute photometric scale
  22241. switch (lightTypeID) {
  22242. case Light.LIGHTTYPEID_POINTLIGHT:
  22243. case Light.LIGHTTYPEID_SPOTLIGHT:
  22244. switch (photometricMode) {
  22245. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22246. photometricScale = 1.0 / (4.0 * Math.PI);
  22247. break;
  22248. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22249. photometricScale = 1.0;
  22250. break;
  22251. case Light.INTENSITYMODE_LUMINANCE:
  22252. photometricScale = this.radius * this.radius;
  22253. break;
  22254. }
  22255. break;
  22256. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22257. switch (photometricMode) {
  22258. case Light.INTENSITYMODE_ILLUMINANCE:
  22259. photometricScale = 1.0;
  22260. break;
  22261. case Light.INTENSITYMODE_LUMINANCE:
  22262. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22263. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22264. var apexAngleRadians = this.radius;
  22265. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22266. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22267. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22268. photometricScale = solidAngle;
  22269. break;
  22270. }
  22271. break;
  22272. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22273. // No fall off in hemisperic light.
  22274. photometricScale = 1.0;
  22275. break;
  22276. }
  22277. return photometricScale;
  22278. };
  22279. /**
  22280. * Reorder the light in the scene according to their defined priority.
  22281. * @hidden Internal Use Only
  22282. */
  22283. Light.prototype._reorderLightsInScene = function () {
  22284. var scene = this.getScene();
  22285. if (this._renderPriority != 0) {
  22286. scene.requireLightSorting = true;
  22287. }
  22288. this.getScene().sortLightsByPriority();
  22289. };
  22290. //lightmapMode Consts
  22291. Light._LIGHTMAP_DEFAULT = 0;
  22292. Light._LIGHTMAP_SPECULAR = 1;
  22293. Light._LIGHTMAP_SHADOWSONLY = 2;
  22294. // Intensity Mode Consts
  22295. Light._INTENSITYMODE_AUTOMATIC = 0;
  22296. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22297. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22298. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22299. Light._INTENSITYMODE_LUMINANCE = 4;
  22300. // Light types ids const.
  22301. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22302. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22303. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22304. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22305. __decorate([
  22306. BABYLON.serializeAsColor3()
  22307. ], Light.prototype, "diffuse", void 0);
  22308. __decorate([
  22309. BABYLON.serializeAsColor3()
  22310. ], Light.prototype, "specular", void 0);
  22311. __decorate([
  22312. BABYLON.serialize()
  22313. ], Light.prototype, "intensity", void 0);
  22314. __decorate([
  22315. BABYLON.serialize()
  22316. ], Light.prototype, "range", void 0);
  22317. __decorate([
  22318. BABYLON.serialize()
  22319. ], Light.prototype, "intensityMode", null);
  22320. __decorate([
  22321. BABYLON.serialize()
  22322. ], Light.prototype, "radius", null);
  22323. __decorate([
  22324. BABYLON.serialize()
  22325. ], Light.prototype, "_renderPriority", void 0);
  22326. __decorate([
  22327. BABYLON.expandToProperty("_reorderLightsInScene")
  22328. ], Light.prototype, "renderPriority", void 0);
  22329. __decorate([
  22330. BABYLON.serialize("shadowEnabled")
  22331. ], Light.prototype, "_shadowEnabled", void 0);
  22332. __decorate([
  22333. BABYLON.serialize("excludeWithLayerMask")
  22334. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22335. __decorate([
  22336. BABYLON.serialize("includeOnlyWithLayerMask")
  22337. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22338. __decorate([
  22339. BABYLON.serialize("lightmapMode")
  22340. ], Light.prototype, "_lightmapMode", void 0);
  22341. return Light;
  22342. }(BABYLON.Node));
  22343. BABYLON.Light = Light;
  22344. })(BABYLON || (BABYLON = {}));
  22345. //# sourceMappingURL=babylon.light.js.map
  22346. var BABYLON;
  22347. (function (BABYLON) {
  22348. var Camera = /** @class */ (function (_super) {
  22349. __extends(Camera, _super);
  22350. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22351. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22352. var _this = _super.call(this, name, scene) || this;
  22353. /**
  22354. * The vector the camera should consider as up.
  22355. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22356. */
  22357. _this.upVector = BABYLON.Vector3.Up();
  22358. _this.orthoLeft = null;
  22359. _this.orthoRight = null;
  22360. _this.orthoBottom = null;
  22361. _this.orthoTop = null;
  22362. /**
  22363. * FOV is set in Radians. (default is 0.8)
  22364. */
  22365. _this.fov = 0.8;
  22366. _this.minZ = 1;
  22367. _this.maxZ = 10000.0;
  22368. _this.inertia = 0.9;
  22369. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22370. _this.isIntermediate = false;
  22371. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22372. /**
  22373. * Restricts the camera to viewing objects with the same layerMask.
  22374. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22375. */
  22376. _this.layerMask = 0x0FFFFFFF;
  22377. /**
  22378. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22379. */
  22380. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22381. // Camera rig members
  22382. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22383. _this._rigCameras = new Array();
  22384. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22385. _this._skipRendering = false;
  22386. _this.customRenderTargets = new Array();
  22387. // Observables
  22388. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22389. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22390. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22391. _this.onRestoreStateObservable = new BABYLON.Observable();
  22392. // Cache
  22393. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22394. _this._projectionMatrix = new BABYLON.Matrix();
  22395. _this._doNotComputeProjectionMatrix = false;
  22396. _this._worldMatrix = BABYLON.Matrix.Identity();
  22397. _this._postProcesses = new Array();
  22398. _this._transformMatrix = BABYLON.Matrix.Zero();
  22399. _this._activeMeshes = new BABYLON.SmartArray(256);
  22400. _this._globalPosition = BABYLON.Vector3.Zero();
  22401. _this._refreshFrustumPlanes = true;
  22402. _this.getScene().addCamera(_this);
  22403. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22404. _this.getScene().activeCamera = _this;
  22405. }
  22406. _this.position = position;
  22407. return _this;
  22408. }
  22409. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22410. get: function () {
  22411. return Camera._PERSPECTIVE_CAMERA;
  22412. },
  22413. enumerable: true,
  22414. configurable: true
  22415. });
  22416. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22417. get: function () {
  22418. return Camera._ORTHOGRAPHIC_CAMERA;
  22419. },
  22420. enumerable: true,
  22421. configurable: true
  22422. });
  22423. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22424. /**
  22425. * This is the default FOV mode for perspective cameras.
  22426. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22427. *
  22428. */
  22429. get: function () {
  22430. return Camera._FOVMODE_VERTICAL_FIXED;
  22431. },
  22432. enumerable: true,
  22433. configurable: true
  22434. });
  22435. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22436. /**
  22437. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22438. *
  22439. */
  22440. get: function () {
  22441. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22442. },
  22443. enumerable: true,
  22444. configurable: true
  22445. });
  22446. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22447. get: function () {
  22448. return Camera._RIG_MODE_NONE;
  22449. },
  22450. enumerable: true,
  22451. configurable: true
  22452. });
  22453. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22454. get: function () {
  22455. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22456. },
  22457. enumerable: true,
  22458. configurable: true
  22459. });
  22460. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22461. get: function () {
  22462. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22463. },
  22464. enumerable: true,
  22465. configurable: true
  22466. });
  22467. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22468. get: function () {
  22469. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22470. },
  22471. enumerable: true,
  22472. configurable: true
  22473. });
  22474. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22475. get: function () {
  22476. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22477. },
  22478. enumerable: true,
  22479. configurable: true
  22480. });
  22481. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22482. get: function () {
  22483. return Camera._RIG_MODE_VR;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22489. get: function () {
  22490. return Camera._RIG_MODE_WEBVR;
  22491. },
  22492. enumerable: true,
  22493. configurable: true
  22494. });
  22495. /**
  22496. * Store current camera state (fov, position, etc..)
  22497. */
  22498. Camera.prototype.storeState = function () {
  22499. this._stateStored = true;
  22500. this._storedFov = this.fov;
  22501. return this;
  22502. };
  22503. /**
  22504. * Restores the camera state values if it has been stored. You must call storeState() first
  22505. */
  22506. Camera.prototype._restoreStateValues = function () {
  22507. if (!this._stateStored) {
  22508. return false;
  22509. }
  22510. this.fov = this._storedFov;
  22511. return true;
  22512. };
  22513. /**
  22514. * Restored camera state. You must call storeState() first
  22515. */
  22516. Camera.prototype.restoreState = function () {
  22517. if (this._restoreStateValues()) {
  22518. this.onRestoreStateObservable.notifyObservers(this);
  22519. return true;
  22520. }
  22521. return false;
  22522. };
  22523. Camera.prototype.getClassName = function () {
  22524. return "Camera";
  22525. };
  22526. /**
  22527. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22528. */
  22529. Camera.prototype.toString = function (fullDetails) {
  22530. var ret = "Name: " + this.name;
  22531. ret += ", type: " + this.getClassName();
  22532. if (this.animations) {
  22533. for (var i = 0; i < this.animations.length; i++) {
  22534. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22535. }
  22536. }
  22537. if (fullDetails) {
  22538. }
  22539. return ret;
  22540. };
  22541. Object.defineProperty(Camera.prototype, "globalPosition", {
  22542. get: function () {
  22543. return this._globalPosition;
  22544. },
  22545. enumerable: true,
  22546. configurable: true
  22547. });
  22548. Camera.prototype.getActiveMeshes = function () {
  22549. return this._activeMeshes;
  22550. };
  22551. Camera.prototype.isActiveMesh = function (mesh) {
  22552. return (this._activeMeshes.indexOf(mesh) !== -1);
  22553. };
  22554. /**
  22555. * Is this camera ready to be used/rendered
  22556. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22557. * @return true if the camera is ready
  22558. */
  22559. Camera.prototype.isReady = function (completeCheck) {
  22560. if (completeCheck === void 0) { completeCheck = false; }
  22561. if (completeCheck) {
  22562. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22563. var pp = _a[_i];
  22564. if (pp && !pp.isReady()) {
  22565. return false;
  22566. }
  22567. }
  22568. }
  22569. return _super.prototype.isReady.call(this, completeCheck);
  22570. };
  22571. //Cache
  22572. Camera.prototype._initCache = function () {
  22573. _super.prototype._initCache.call(this);
  22574. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22575. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22576. this._cache.mode = undefined;
  22577. this._cache.minZ = undefined;
  22578. this._cache.maxZ = undefined;
  22579. this._cache.fov = undefined;
  22580. this._cache.fovMode = undefined;
  22581. this._cache.aspectRatio = undefined;
  22582. this._cache.orthoLeft = undefined;
  22583. this._cache.orthoRight = undefined;
  22584. this._cache.orthoBottom = undefined;
  22585. this._cache.orthoTop = undefined;
  22586. this._cache.renderWidth = undefined;
  22587. this._cache.renderHeight = undefined;
  22588. };
  22589. Camera.prototype._updateCache = function (ignoreParentClass) {
  22590. if (!ignoreParentClass) {
  22591. _super.prototype._updateCache.call(this);
  22592. }
  22593. this._cache.position.copyFrom(this.position);
  22594. this._cache.upVector.copyFrom(this.upVector);
  22595. };
  22596. // Synchronized
  22597. Camera.prototype._isSynchronized = function () {
  22598. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22599. };
  22600. Camera.prototype._isSynchronizedViewMatrix = function () {
  22601. if (!_super.prototype._isSynchronized.call(this))
  22602. return false;
  22603. return this._cache.position.equals(this.position)
  22604. && this._cache.upVector.equals(this.upVector)
  22605. && this.isSynchronizedWithParent();
  22606. };
  22607. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22608. var check = this._cache.mode === this.mode
  22609. && this._cache.minZ === this.minZ
  22610. && this._cache.maxZ === this.maxZ;
  22611. if (!check) {
  22612. return false;
  22613. }
  22614. var engine = this.getEngine();
  22615. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22616. check = this._cache.fov === this.fov
  22617. && this._cache.fovMode === this.fovMode
  22618. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22619. }
  22620. else {
  22621. check = this._cache.orthoLeft === this.orthoLeft
  22622. && this._cache.orthoRight === this.orthoRight
  22623. && this._cache.orthoBottom === this.orthoBottom
  22624. && this._cache.orthoTop === this.orthoTop
  22625. && this._cache.renderWidth === engine.getRenderWidth()
  22626. && this._cache.renderHeight === engine.getRenderHeight();
  22627. }
  22628. return check;
  22629. };
  22630. // Controls
  22631. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22632. };
  22633. Camera.prototype.detachControl = function (element) {
  22634. };
  22635. Camera.prototype.update = function () {
  22636. this._checkInputs();
  22637. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22638. this._updateRigCameras();
  22639. }
  22640. };
  22641. Camera.prototype._checkInputs = function () {
  22642. this.onAfterCheckInputsObservable.notifyObservers(this);
  22643. };
  22644. Object.defineProperty(Camera.prototype, "rigCameras", {
  22645. get: function () {
  22646. return this._rigCameras;
  22647. },
  22648. enumerable: true,
  22649. configurable: true
  22650. });
  22651. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22652. get: function () {
  22653. return this._rigPostProcess;
  22654. },
  22655. enumerable: true,
  22656. configurable: true
  22657. });
  22658. /**
  22659. * Internal, gets the first post proces.
  22660. * @returns the first post process to be run on this camera.
  22661. */
  22662. Camera.prototype._getFirstPostProcess = function () {
  22663. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22664. if (this._postProcesses[ppIndex] !== null) {
  22665. return this._postProcesses[ppIndex];
  22666. }
  22667. }
  22668. return null;
  22669. };
  22670. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22671. // invalidate framebuffer
  22672. var firstPostProcess = this._getFirstPostProcess();
  22673. if (firstPostProcess) {
  22674. firstPostProcess.markTextureDirty();
  22675. }
  22676. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22677. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22678. var cam = this._rigCameras[i];
  22679. var rigPostProcess = cam._rigPostProcess;
  22680. // for VR rig, there does not have to be a post process
  22681. if (rigPostProcess) {
  22682. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22683. if (isPass) {
  22684. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22685. cam.isIntermediate = this._postProcesses.length === 0;
  22686. }
  22687. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22688. rigPostProcess.markTextureDirty();
  22689. }
  22690. else {
  22691. cam._postProcesses = this._postProcesses.slice(0);
  22692. }
  22693. }
  22694. };
  22695. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22696. if (insertAt === void 0) { insertAt = null; }
  22697. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22698. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22699. return 0;
  22700. }
  22701. if (insertAt == null || insertAt < 0) {
  22702. this._postProcesses.push(postProcess);
  22703. }
  22704. else if (this._postProcesses[insertAt] === null) {
  22705. this._postProcesses[insertAt] = postProcess;
  22706. }
  22707. else {
  22708. this._postProcesses.splice(insertAt, 0, postProcess);
  22709. }
  22710. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22711. return this._postProcesses.indexOf(postProcess);
  22712. };
  22713. Camera.prototype.detachPostProcess = function (postProcess) {
  22714. var idx = this._postProcesses.indexOf(postProcess);
  22715. if (idx !== -1) {
  22716. this._postProcesses[idx] = null;
  22717. }
  22718. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22719. };
  22720. Camera.prototype.getWorldMatrix = function () {
  22721. if (this._isSynchronizedViewMatrix()) {
  22722. return this._worldMatrix;
  22723. }
  22724. // Getting the the view matrix will also compute the world matrix.
  22725. this.getViewMatrix();
  22726. return this._worldMatrix;
  22727. };
  22728. Camera.prototype._getViewMatrix = function () {
  22729. return BABYLON.Matrix.Identity();
  22730. };
  22731. Camera.prototype.getViewMatrix = function (force) {
  22732. if (!force && this._isSynchronizedViewMatrix()) {
  22733. return this._computedViewMatrix;
  22734. }
  22735. this.updateCache();
  22736. this._computedViewMatrix = this._getViewMatrix();
  22737. this._currentRenderId = this.getScene().getRenderId();
  22738. this._childRenderId = this._currentRenderId;
  22739. this._refreshFrustumPlanes = true;
  22740. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22741. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22742. }
  22743. this.onViewMatrixChangedObservable.notifyObservers(this);
  22744. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22745. return this._computedViewMatrix;
  22746. };
  22747. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22748. this._doNotComputeProjectionMatrix = true;
  22749. if (projection !== undefined) {
  22750. this._projectionMatrix = projection;
  22751. }
  22752. };
  22753. ;
  22754. Camera.prototype.unfreezeProjectionMatrix = function () {
  22755. this._doNotComputeProjectionMatrix = false;
  22756. };
  22757. ;
  22758. Camera.prototype.getProjectionMatrix = function (force) {
  22759. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22760. return this._projectionMatrix;
  22761. }
  22762. // Cache
  22763. this._cache.mode = this.mode;
  22764. this._cache.minZ = this.minZ;
  22765. this._cache.maxZ = this.maxZ;
  22766. // Matrix
  22767. this._refreshFrustumPlanes = true;
  22768. var engine = this.getEngine();
  22769. var scene = this.getScene();
  22770. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22771. this._cache.fov = this.fov;
  22772. this._cache.fovMode = this.fovMode;
  22773. this._cache.aspectRatio = engine.getAspectRatio(this);
  22774. if (this.minZ <= 0) {
  22775. this.minZ = 0.1;
  22776. }
  22777. if (scene.useRightHandedSystem) {
  22778. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22779. }
  22780. else {
  22781. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22782. }
  22783. }
  22784. else {
  22785. var halfWidth = engine.getRenderWidth() / 2.0;
  22786. var halfHeight = engine.getRenderHeight() / 2.0;
  22787. if (scene.useRightHandedSystem) {
  22788. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22789. }
  22790. else {
  22791. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22792. }
  22793. this._cache.orthoLeft = this.orthoLeft;
  22794. this._cache.orthoRight = this.orthoRight;
  22795. this._cache.orthoBottom = this.orthoBottom;
  22796. this._cache.orthoTop = this.orthoTop;
  22797. this._cache.renderWidth = engine.getRenderWidth();
  22798. this._cache.renderHeight = engine.getRenderHeight();
  22799. }
  22800. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22801. return this._projectionMatrix;
  22802. };
  22803. Camera.prototype.getTranformationMatrix = function () {
  22804. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22805. return this._transformMatrix;
  22806. };
  22807. Camera.prototype.updateFrustumPlanes = function () {
  22808. if (!this._refreshFrustumPlanes) {
  22809. return;
  22810. }
  22811. this.getTranformationMatrix();
  22812. if (!this._frustumPlanes) {
  22813. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22814. }
  22815. else {
  22816. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22817. }
  22818. this._refreshFrustumPlanes = false;
  22819. };
  22820. Camera.prototype.isInFrustum = function (target) {
  22821. this.updateFrustumPlanes();
  22822. return target.isInFrustum(this._frustumPlanes);
  22823. };
  22824. Camera.prototype.isCompletelyInFrustum = function (target) {
  22825. this.updateFrustumPlanes();
  22826. return target.isCompletelyInFrustum(this._frustumPlanes);
  22827. };
  22828. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22829. if (length === void 0) { length = 100; }
  22830. if (!transform) {
  22831. transform = this.getWorldMatrix();
  22832. }
  22833. if (!origin) {
  22834. origin = this.position;
  22835. }
  22836. var forward = new BABYLON.Vector3(0, 0, 1);
  22837. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22838. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22839. return new BABYLON.Ray(origin, direction, length);
  22840. };
  22841. /**
  22842. * Releases resources associated with this node.
  22843. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22844. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22845. */
  22846. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22847. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22848. // Observables
  22849. this.onViewMatrixChangedObservable.clear();
  22850. this.onProjectionMatrixChangedObservable.clear();
  22851. this.onAfterCheckInputsObservable.clear();
  22852. this.onRestoreStateObservable.clear();
  22853. // Inputs
  22854. if (this.inputs) {
  22855. this.inputs.clear();
  22856. }
  22857. // Animations
  22858. this.getScene().stopAnimation(this);
  22859. // Remove from scene
  22860. this.getScene().removeCamera(this);
  22861. while (this._rigCameras.length > 0) {
  22862. var camera = this._rigCameras.pop();
  22863. if (camera) {
  22864. camera.dispose();
  22865. }
  22866. }
  22867. // Postprocesses
  22868. if (this._rigPostProcess) {
  22869. this._rigPostProcess.dispose(this);
  22870. this._rigPostProcess = null;
  22871. this._postProcesses = [];
  22872. }
  22873. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22874. this._rigPostProcess = null;
  22875. this._postProcesses = [];
  22876. }
  22877. else {
  22878. var i = this._postProcesses.length;
  22879. while (--i >= 0) {
  22880. var postProcess = this._postProcesses[i];
  22881. if (postProcess) {
  22882. postProcess.dispose(this);
  22883. }
  22884. }
  22885. }
  22886. // Render targets
  22887. var i = this.customRenderTargets.length;
  22888. while (--i >= 0) {
  22889. this.customRenderTargets[i].dispose();
  22890. }
  22891. this.customRenderTargets = [];
  22892. // Active Meshes
  22893. this._activeMeshes.dispose();
  22894. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22895. };
  22896. Object.defineProperty(Camera.prototype, "leftCamera", {
  22897. // ---- Camera rigs section ----
  22898. get: function () {
  22899. if (this._rigCameras.length < 1) {
  22900. return null;
  22901. }
  22902. return this._rigCameras[0];
  22903. },
  22904. enumerable: true,
  22905. configurable: true
  22906. });
  22907. Object.defineProperty(Camera.prototype, "rightCamera", {
  22908. get: function () {
  22909. if (this._rigCameras.length < 2) {
  22910. return null;
  22911. }
  22912. return this._rigCameras[1];
  22913. },
  22914. enumerable: true,
  22915. configurable: true
  22916. });
  22917. Camera.prototype.getLeftTarget = function () {
  22918. if (this._rigCameras.length < 1) {
  22919. return null;
  22920. }
  22921. return this._rigCameras[0].getTarget();
  22922. };
  22923. Camera.prototype.getRightTarget = function () {
  22924. if (this._rigCameras.length < 2) {
  22925. return null;
  22926. }
  22927. return this._rigCameras[1].getTarget();
  22928. };
  22929. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22930. if (this.cameraRigMode === mode) {
  22931. return;
  22932. }
  22933. while (this._rigCameras.length > 0) {
  22934. var camera = this._rigCameras.pop();
  22935. if (camera) {
  22936. camera.dispose();
  22937. }
  22938. }
  22939. this.cameraRigMode = mode;
  22940. this._cameraRigParams = {};
  22941. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22942. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22943. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22944. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22945. // create the rig cameras, unless none
  22946. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22947. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22948. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22949. if (leftCamera && rightCamera) {
  22950. this._rigCameras.push(leftCamera);
  22951. this._rigCameras.push(rightCamera);
  22952. }
  22953. }
  22954. switch (this.cameraRigMode) {
  22955. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22956. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22957. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22958. break;
  22959. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22960. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22961. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22962. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22963. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22964. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22965. break;
  22966. case Camera.RIG_MODE_VR:
  22967. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22968. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22969. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22970. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22971. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22972. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22973. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22974. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22975. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22976. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22977. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22978. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22979. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22980. if (metrics.compensateDistortion) {
  22981. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22982. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22983. }
  22984. break;
  22985. case Camera.RIG_MODE_WEBVR:
  22986. if (rigParams.vrDisplay) {
  22987. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22988. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22989. //Left eye
  22990. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22991. this._rigCameras[0].setCameraRigParameter("left", true);
  22992. //leaving this for future reference
  22993. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22994. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22995. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22996. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22997. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22998. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22999. this._rigCameras[0].parent = this;
  23000. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23001. //Right eye
  23002. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23003. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23004. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23005. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23006. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23007. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23008. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23009. this._rigCameras[1].parent = this;
  23010. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23011. if (Camera.UseAlternateWebVRRendering) {
  23012. this._rigCameras[1]._skipRendering = true;
  23013. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23014. }
  23015. }
  23016. break;
  23017. }
  23018. this._cascadePostProcessesToRigCams();
  23019. this.update();
  23020. };
  23021. Camera.prototype._getVRProjectionMatrix = function () {
  23022. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23023. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23024. return this._projectionMatrix;
  23025. };
  23026. Camera.prototype._updateCameraRotationMatrix = function () {
  23027. //Here for WebVR
  23028. };
  23029. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23030. //Here for WebVR
  23031. };
  23032. /**
  23033. * This function MUST be overwritten by the different WebVR cameras available.
  23034. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23035. */
  23036. Camera.prototype._getWebVRProjectionMatrix = function () {
  23037. return BABYLON.Matrix.Identity();
  23038. };
  23039. /**
  23040. * This function MUST be overwritten by the different WebVR cameras available.
  23041. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23042. */
  23043. Camera.prototype._getWebVRViewMatrix = function () {
  23044. return BABYLON.Matrix.Identity();
  23045. };
  23046. Camera.prototype.setCameraRigParameter = function (name, value) {
  23047. if (!this._cameraRigParams) {
  23048. this._cameraRigParams = {};
  23049. }
  23050. this._cameraRigParams[name] = value;
  23051. //provisionnally:
  23052. if (name === "interaxialDistance") {
  23053. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23054. }
  23055. };
  23056. /**
  23057. * needs to be overridden by children so sub has required properties to be copied
  23058. */
  23059. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23060. return null;
  23061. };
  23062. /**
  23063. * May need to be overridden by children
  23064. */
  23065. Camera.prototype._updateRigCameras = function () {
  23066. for (var i = 0; i < this._rigCameras.length; i++) {
  23067. this._rigCameras[i].minZ = this.minZ;
  23068. this._rigCameras[i].maxZ = this.maxZ;
  23069. this._rigCameras[i].fov = this.fov;
  23070. }
  23071. // only update viewport when ANAGLYPH
  23072. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23073. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23074. }
  23075. };
  23076. Camera.prototype._setupInputs = function () {
  23077. };
  23078. Camera.prototype.serialize = function () {
  23079. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23080. // Type
  23081. serializationObject.type = this.getClassName();
  23082. // Parent
  23083. if (this.parent) {
  23084. serializationObject.parentId = this.parent.id;
  23085. }
  23086. if (this.inputs) {
  23087. this.inputs.serialize(serializationObject);
  23088. }
  23089. // Animations
  23090. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23091. serializationObject.ranges = this.serializeAnimationRanges();
  23092. return serializationObject;
  23093. };
  23094. Camera.prototype.clone = function (name) {
  23095. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23096. };
  23097. Camera.prototype.getDirection = function (localAxis) {
  23098. var result = BABYLON.Vector3.Zero();
  23099. this.getDirectionToRef(localAxis, result);
  23100. return result;
  23101. };
  23102. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23103. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23104. };
  23105. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23106. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23107. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23108. switch (type) {
  23109. case "ArcRotateCamera":
  23110. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23111. case "DeviceOrientationCamera":
  23112. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23113. case "FollowCamera":
  23114. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23115. case "ArcFollowCamera":
  23116. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23117. case "GamepadCamera":
  23118. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23119. case "TouchCamera":
  23120. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23121. case "VirtualJoysticksCamera":
  23122. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23123. case "WebVRFreeCamera":
  23124. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23125. case "WebVRGamepadCamera":
  23126. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23127. case "VRDeviceOrientationFreeCamera":
  23128. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23129. case "VRDeviceOrientationGamepadCamera":
  23130. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23131. case "AnaglyphArcRotateCamera":
  23132. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23133. case "AnaglyphFreeCamera":
  23134. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23135. case "AnaglyphGamepadCamera":
  23136. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23137. case "AnaglyphUniversalCamera":
  23138. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23139. case "StereoscopicArcRotateCamera":
  23140. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23141. case "StereoscopicFreeCamera":
  23142. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23143. case "StereoscopicGamepadCamera":
  23144. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23145. case "StereoscopicUniversalCamera":
  23146. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23147. case "FreeCamera": // Forcing Universal here
  23148. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23149. default: // Universal Camera is the default value
  23150. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23151. }
  23152. };
  23153. Camera.prototype.computeWorldMatrix = function () {
  23154. return this.getWorldMatrix();
  23155. };
  23156. Camera.Parse = function (parsedCamera, scene) {
  23157. var type = parsedCamera.type;
  23158. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23159. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23160. // Parent
  23161. if (parsedCamera.parentId) {
  23162. camera._waitingParentId = parsedCamera.parentId;
  23163. }
  23164. //If camera has an input manager, let it parse inputs settings
  23165. if (camera.inputs) {
  23166. camera.inputs.parse(parsedCamera);
  23167. camera._setupInputs();
  23168. }
  23169. if (camera.setPosition) { // need to force position
  23170. camera.position.copyFromFloats(0, 0, 0);
  23171. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23172. }
  23173. // Target
  23174. if (parsedCamera.target) {
  23175. if (camera.setTarget) {
  23176. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23177. }
  23178. }
  23179. // Apply 3d rig, when found
  23180. if (parsedCamera.cameraRigMode) {
  23181. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23182. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23183. }
  23184. // Animations
  23185. if (parsedCamera.animations) {
  23186. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23187. var parsedAnimation = parsedCamera.animations[animationIndex];
  23188. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23189. }
  23190. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23191. }
  23192. if (parsedCamera.autoAnimate) {
  23193. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23194. }
  23195. return camera;
  23196. };
  23197. // Statics
  23198. Camera._PERSPECTIVE_CAMERA = 0;
  23199. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23200. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23201. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23202. Camera._RIG_MODE_NONE = 0;
  23203. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23204. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23205. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23206. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23207. Camera._RIG_MODE_VR = 20;
  23208. Camera._RIG_MODE_WEBVR = 21;
  23209. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23210. Camera.UseAlternateWebVRRendering = false;
  23211. __decorate([
  23212. BABYLON.serializeAsVector3()
  23213. ], Camera.prototype, "position", void 0);
  23214. __decorate([
  23215. BABYLON.serializeAsVector3()
  23216. ], Camera.prototype, "upVector", void 0);
  23217. __decorate([
  23218. BABYLON.serialize()
  23219. ], Camera.prototype, "orthoLeft", void 0);
  23220. __decorate([
  23221. BABYLON.serialize()
  23222. ], Camera.prototype, "orthoRight", void 0);
  23223. __decorate([
  23224. BABYLON.serialize()
  23225. ], Camera.prototype, "orthoBottom", void 0);
  23226. __decorate([
  23227. BABYLON.serialize()
  23228. ], Camera.prototype, "orthoTop", void 0);
  23229. __decorate([
  23230. BABYLON.serialize()
  23231. ], Camera.prototype, "fov", void 0);
  23232. __decorate([
  23233. BABYLON.serialize()
  23234. ], Camera.prototype, "minZ", void 0);
  23235. __decorate([
  23236. BABYLON.serialize()
  23237. ], Camera.prototype, "maxZ", void 0);
  23238. __decorate([
  23239. BABYLON.serialize()
  23240. ], Camera.prototype, "inertia", void 0);
  23241. __decorate([
  23242. BABYLON.serialize()
  23243. ], Camera.prototype, "mode", void 0);
  23244. __decorate([
  23245. BABYLON.serialize()
  23246. ], Camera.prototype, "layerMask", void 0);
  23247. __decorate([
  23248. BABYLON.serialize()
  23249. ], Camera.prototype, "fovMode", void 0);
  23250. __decorate([
  23251. BABYLON.serialize()
  23252. ], Camera.prototype, "cameraRigMode", void 0);
  23253. __decorate([
  23254. BABYLON.serialize()
  23255. ], Camera.prototype, "interaxialDistance", void 0);
  23256. __decorate([
  23257. BABYLON.serialize()
  23258. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23259. return Camera;
  23260. }(BABYLON.Node));
  23261. BABYLON.Camera = Camera;
  23262. })(BABYLON || (BABYLON = {}));
  23263. //# sourceMappingURL=babylon.camera.js.map
  23264. var BABYLON;
  23265. (function (BABYLON) {
  23266. var RenderingManager = /** @class */ (function () {
  23267. function RenderingManager(scene) {
  23268. this._renderingGroups = new Array();
  23269. this._autoClearDepthStencil = {};
  23270. this._customOpaqueSortCompareFn = {};
  23271. this._customAlphaTestSortCompareFn = {};
  23272. this._customTransparentSortCompareFn = {};
  23273. this._renderinGroupInfo = null;
  23274. this._scene = scene;
  23275. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23276. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23277. }
  23278. }
  23279. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23280. if (depth === void 0) { depth = true; }
  23281. if (stencil === void 0) { stencil = true; }
  23282. if (this._depthStencilBufferAlreadyCleaned) {
  23283. return;
  23284. }
  23285. this._scene.getEngine().clear(null, false, depth, stencil);
  23286. this._depthStencilBufferAlreadyCleaned = true;
  23287. };
  23288. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23289. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23290. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23291. var info = null;
  23292. if (observable) {
  23293. if (!this._renderinGroupInfo) {
  23294. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23295. }
  23296. info = this._renderinGroupInfo;
  23297. info.scene = this._scene;
  23298. info.camera = this._scene.activeCamera;
  23299. }
  23300. // Dispatch sprites
  23301. if (renderSprites) {
  23302. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23303. var manager = this._scene.spriteManagers[index];
  23304. this.dispatchSprites(manager);
  23305. }
  23306. }
  23307. // Render
  23308. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23309. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23310. var renderingGroup = this._renderingGroups[index];
  23311. if (!renderingGroup && !observable)
  23312. continue;
  23313. var renderingGroupMask = 0;
  23314. // Fire PRECLEAR stage
  23315. if (observable && info) {
  23316. renderingGroupMask = Math.pow(2, index);
  23317. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23318. info.renderingGroupId = index;
  23319. observable.notifyObservers(info, renderingGroupMask);
  23320. }
  23321. // Clear depth/stencil if needed
  23322. if (RenderingManager.AUTOCLEAR) {
  23323. var autoClear = this._autoClearDepthStencil[index];
  23324. if (autoClear && autoClear.autoClear) {
  23325. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23326. }
  23327. }
  23328. if (observable && info) {
  23329. // Fire PREOPAQUE stage
  23330. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23331. observable.notifyObservers(info, renderingGroupMask);
  23332. // Fire PRETRANSPARENT stage
  23333. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23334. observable.notifyObservers(info, renderingGroupMask);
  23335. }
  23336. if (renderingGroup)
  23337. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23338. // Fire POSTTRANSPARENT stage
  23339. if (observable && info) {
  23340. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23341. observable.notifyObservers(info, renderingGroupMask);
  23342. }
  23343. }
  23344. };
  23345. RenderingManager.prototype.reset = function () {
  23346. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23347. var renderingGroup = this._renderingGroups[index];
  23348. if (renderingGroup) {
  23349. renderingGroup.prepare();
  23350. }
  23351. }
  23352. };
  23353. RenderingManager.prototype.dispose = function () {
  23354. this.freeRenderingGroups();
  23355. this._renderingGroups.length = 0;
  23356. };
  23357. /**
  23358. * Clear the info related to rendering groups preventing retention points during dispose.
  23359. */
  23360. RenderingManager.prototype.freeRenderingGroups = function () {
  23361. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23362. var renderingGroup = this._renderingGroups[index];
  23363. if (renderingGroup) {
  23364. renderingGroup.dispose();
  23365. }
  23366. }
  23367. };
  23368. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23369. if (this._renderingGroups[renderingGroupId] === undefined) {
  23370. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23371. }
  23372. };
  23373. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23374. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23375. this._prepareRenderingGroup(renderingGroupId);
  23376. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23377. };
  23378. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23379. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23380. this._prepareRenderingGroup(renderingGroupId);
  23381. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23382. };
  23383. /**
  23384. * @param subMesh The submesh to dispatch
  23385. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23386. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23387. */
  23388. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23389. if (mesh === undefined) {
  23390. mesh = subMesh.getMesh();
  23391. }
  23392. var renderingGroupId = mesh.renderingGroupId || 0;
  23393. this._prepareRenderingGroup(renderingGroupId);
  23394. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23395. };
  23396. /**
  23397. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23398. * This allowed control for front to back rendering or reversly depending of the special needs.
  23399. *
  23400. * @param renderingGroupId The rendering group id corresponding to its index
  23401. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23402. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23403. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23404. */
  23405. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23406. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23407. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23408. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23409. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23410. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23411. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23412. if (this._renderingGroups[renderingGroupId]) {
  23413. var group = this._renderingGroups[renderingGroupId];
  23414. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23415. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23416. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23417. }
  23418. };
  23419. /**
  23420. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23421. *
  23422. * @param renderingGroupId The rendering group id corresponding to its index
  23423. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23424. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23425. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23426. */
  23427. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23428. if (depth === void 0) { depth = true; }
  23429. if (stencil === void 0) { stencil = true; }
  23430. this._autoClearDepthStencil[renderingGroupId] = {
  23431. autoClear: autoClearDepthStencil,
  23432. depth: depth,
  23433. stencil: stencil
  23434. };
  23435. };
  23436. /**
  23437. * The max id used for rendering groups (not included)
  23438. */
  23439. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23440. /**
  23441. * The min id used for rendering groups (included)
  23442. */
  23443. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23444. /**
  23445. * Used to globally prevent autoclearing scenes.
  23446. */
  23447. RenderingManager.AUTOCLEAR = true;
  23448. return RenderingManager;
  23449. }());
  23450. BABYLON.RenderingManager = RenderingManager;
  23451. })(BABYLON || (BABYLON = {}));
  23452. //# sourceMappingURL=babylon.renderingManager.js.map
  23453. var BABYLON;
  23454. (function (BABYLON) {
  23455. var RenderingGroup = /** @class */ (function () {
  23456. /**
  23457. * Creates a new rendering group.
  23458. * @param index The rendering group index
  23459. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23460. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23461. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23462. */
  23463. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23464. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23465. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23466. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23467. this.index = index;
  23468. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23469. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23470. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23471. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23472. this._particleSystems = new BABYLON.SmartArray(256);
  23473. this._spriteManagers = new BABYLON.SmartArray(256);
  23474. this._edgesRenderers = new BABYLON.SmartArray(16);
  23475. this._scene = scene;
  23476. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23477. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23478. this.transparentSortCompareFn = transparentSortCompareFn;
  23479. }
  23480. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23481. /**
  23482. * Set the opaque sort comparison function.
  23483. * If null the sub meshes will be render in the order they were created
  23484. */
  23485. set: function (value) {
  23486. this._opaqueSortCompareFn = value;
  23487. if (value) {
  23488. this._renderOpaque = this.renderOpaqueSorted;
  23489. }
  23490. else {
  23491. this._renderOpaque = RenderingGroup.renderUnsorted;
  23492. }
  23493. },
  23494. enumerable: true,
  23495. configurable: true
  23496. });
  23497. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23498. /**
  23499. * Set the alpha test sort comparison function.
  23500. * If null the sub meshes will be render in the order they were created
  23501. */
  23502. set: function (value) {
  23503. this._alphaTestSortCompareFn = value;
  23504. if (value) {
  23505. this._renderAlphaTest = this.renderAlphaTestSorted;
  23506. }
  23507. else {
  23508. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23509. }
  23510. },
  23511. enumerable: true,
  23512. configurable: true
  23513. });
  23514. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23515. /**
  23516. * Set the transparent sort comparison function.
  23517. * If null the sub meshes will be render in the order they were created
  23518. */
  23519. set: function (value) {
  23520. if (value) {
  23521. this._transparentSortCompareFn = value;
  23522. }
  23523. else {
  23524. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23525. }
  23526. this._renderTransparent = this.renderTransparentSorted;
  23527. },
  23528. enumerable: true,
  23529. configurable: true
  23530. });
  23531. /**
  23532. * Render all the sub meshes contained in the group.
  23533. * @param customRenderFunction Used to override the default render behaviour of the group.
  23534. * @returns true if rendered some submeshes.
  23535. */
  23536. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23537. if (customRenderFunction) {
  23538. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23539. return;
  23540. }
  23541. var engine = this._scene.getEngine();
  23542. // Depth only
  23543. if (this._depthOnlySubMeshes.length !== 0) {
  23544. engine.setColorWrite(false);
  23545. this._renderAlphaTest(this._depthOnlySubMeshes);
  23546. engine.setColorWrite(true);
  23547. }
  23548. // Opaque
  23549. if (this._opaqueSubMeshes.length !== 0) {
  23550. this._renderOpaque(this._opaqueSubMeshes);
  23551. }
  23552. // Alpha test
  23553. if (this._alphaTestSubMeshes.length !== 0) {
  23554. this._renderAlphaTest(this._alphaTestSubMeshes);
  23555. }
  23556. var stencilState = engine.getStencilBuffer();
  23557. engine.setStencilBuffer(false);
  23558. // Sprites
  23559. if (renderSprites) {
  23560. this._renderSprites();
  23561. }
  23562. // Particles
  23563. if (renderParticles) {
  23564. this._renderParticles(activeMeshes);
  23565. }
  23566. if (this.onBeforeTransparentRendering) {
  23567. this.onBeforeTransparentRendering();
  23568. }
  23569. // Transparent
  23570. if (this._transparentSubMeshes.length !== 0) {
  23571. this._renderTransparent(this._transparentSubMeshes);
  23572. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23573. }
  23574. // Set back stencil to false in case it changes before the edge renderer.
  23575. engine.setStencilBuffer(false);
  23576. // Edges
  23577. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23578. this._edgesRenderers.data[edgesRendererIndex].render();
  23579. }
  23580. // Restore Stencil state.
  23581. engine.setStencilBuffer(stencilState);
  23582. };
  23583. /**
  23584. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23585. * @param subMeshes The submeshes to render
  23586. */
  23587. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23588. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23589. };
  23590. /**
  23591. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23592. * @param subMeshes The submeshes to render
  23593. */
  23594. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23595. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23596. };
  23597. /**
  23598. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23599. * @param subMeshes The submeshes to render
  23600. */
  23601. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23602. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23603. };
  23604. /**
  23605. * Renders the submeshes in a specified order.
  23606. * @param subMeshes The submeshes to sort before render
  23607. * @param sortCompareFn The comparison function use to sort
  23608. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23609. * @param transparent Specifies to activate blending if true
  23610. */
  23611. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23612. var subIndex = 0;
  23613. var subMesh;
  23614. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23615. for (; subIndex < subMeshes.length; subIndex++) {
  23616. subMesh = subMeshes.data[subIndex];
  23617. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23618. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23619. }
  23620. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23621. if (sortCompareFn) {
  23622. sortedArray.sort(sortCompareFn);
  23623. }
  23624. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23625. subMesh = sortedArray[subIndex];
  23626. if (transparent) {
  23627. var material = subMesh.getMaterial();
  23628. if (material && material.needDepthPrePass) {
  23629. var engine = material.getScene().getEngine();
  23630. engine.setColorWrite(false);
  23631. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23632. subMesh.render(false);
  23633. engine.setColorWrite(true);
  23634. }
  23635. }
  23636. subMesh.render(transparent);
  23637. }
  23638. };
  23639. /**
  23640. * Renders the submeshes in the order they were dispatched (no sort applied).
  23641. * @param subMeshes The submeshes to render
  23642. */
  23643. RenderingGroup.renderUnsorted = function (subMeshes) {
  23644. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23645. var submesh = subMeshes.data[subIndex];
  23646. submesh.render(false);
  23647. }
  23648. };
  23649. /**
  23650. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23651. * are rendered back to front if in the same alpha index.
  23652. *
  23653. * @param a The first submesh
  23654. * @param b The second submesh
  23655. * @returns The result of the comparison
  23656. */
  23657. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23658. // Alpha index first
  23659. if (a._alphaIndex > b._alphaIndex) {
  23660. return 1;
  23661. }
  23662. if (a._alphaIndex < b._alphaIndex) {
  23663. return -1;
  23664. }
  23665. // Then distance to camera
  23666. return RenderingGroup.backToFrontSortCompare(a, b);
  23667. };
  23668. /**
  23669. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23670. * are rendered back to front.
  23671. *
  23672. * @param a The first submesh
  23673. * @param b The second submesh
  23674. * @returns The result of the comparison
  23675. */
  23676. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23677. // Then distance to camera
  23678. if (a._distanceToCamera < b._distanceToCamera) {
  23679. return 1;
  23680. }
  23681. if (a._distanceToCamera > b._distanceToCamera) {
  23682. return -1;
  23683. }
  23684. return 0;
  23685. };
  23686. /**
  23687. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23688. * are rendered front to back (prevent overdraw).
  23689. *
  23690. * @param a The first submesh
  23691. * @param b The second submesh
  23692. * @returns The result of the comparison
  23693. */
  23694. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23695. // Then distance to camera
  23696. if (a._distanceToCamera < b._distanceToCamera) {
  23697. return -1;
  23698. }
  23699. if (a._distanceToCamera > b._distanceToCamera) {
  23700. return 1;
  23701. }
  23702. return 0;
  23703. };
  23704. /**
  23705. * Resets the different lists of submeshes to prepare a new frame.
  23706. */
  23707. RenderingGroup.prototype.prepare = function () {
  23708. this._opaqueSubMeshes.reset();
  23709. this._transparentSubMeshes.reset();
  23710. this._alphaTestSubMeshes.reset();
  23711. this._depthOnlySubMeshes.reset();
  23712. this._particleSystems.reset();
  23713. this._spriteManagers.reset();
  23714. this._edgesRenderers.reset();
  23715. };
  23716. RenderingGroup.prototype.dispose = function () {
  23717. this._opaqueSubMeshes.dispose();
  23718. this._transparentSubMeshes.dispose();
  23719. this._alphaTestSubMeshes.dispose();
  23720. this._depthOnlySubMeshes.dispose();
  23721. this._particleSystems.dispose();
  23722. this._spriteManagers.dispose();
  23723. this._edgesRenderers.dispose();
  23724. };
  23725. /**
  23726. * Inserts the submesh in its correct queue depending on its material.
  23727. * @param subMesh The submesh to dispatch
  23728. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23729. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23730. */
  23731. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23732. // Get mesh and materials if not provided
  23733. if (mesh === undefined) {
  23734. mesh = subMesh.getMesh();
  23735. }
  23736. if (material === undefined) {
  23737. material = subMesh.getMaterial();
  23738. }
  23739. if (material === null || material === undefined) {
  23740. return;
  23741. }
  23742. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23743. this._transparentSubMeshes.push(subMesh);
  23744. }
  23745. else if (material.needAlphaTesting()) { // Alpha test
  23746. if (material.needDepthPrePass) {
  23747. this._depthOnlySubMeshes.push(subMesh);
  23748. }
  23749. this._alphaTestSubMeshes.push(subMesh);
  23750. }
  23751. else {
  23752. if (material.needDepthPrePass) {
  23753. this._depthOnlySubMeshes.push(subMesh);
  23754. }
  23755. this._opaqueSubMeshes.push(subMesh); // Opaque
  23756. }
  23757. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23758. this._edgesRenderers.push(mesh._edgesRenderer);
  23759. }
  23760. };
  23761. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23762. this._spriteManagers.push(spriteManager);
  23763. };
  23764. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23765. this._particleSystems.push(particleSystem);
  23766. };
  23767. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23768. if (this._particleSystems.length === 0) {
  23769. return;
  23770. }
  23771. // Particles
  23772. var activeCamera = this._scene.activeCamera;
  23773. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23774. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23775. var particleSystem = this._particleSystems.data[particleIndex];
  23776. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23777. continue;
  23778. }
  23779. var emitter = particleSystem.emitter;
  23780. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23781. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23782. }
  23783. }
  23784. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23785. };
  23786. RenderingGroup.prototype._renderSprites = function () {
  23787. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23788. return;
  23789. }
  23790. // Sprites
  23791. var activeCamera = this._scene.activeCamera;
  23792. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23793. for (var id = 0; id < this._spriteManagers.length; id++) {
  23794. var spriteManager = this._spriteManagers.data[id];
  23795. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23796. spriteManager.render();
  23797. }
  23798. }
  23799. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23800. };
  23801. return RenderingGroup;
  23802. }());
  23803. BABYLON.RenderingGroup = RenderingGroup;
  23804. })(BABYLON || (BABYLON = {}));
  23805. //# sourceMappingURL=babylon.renderingGroup.js.map
  23806. var BABYLON;
  23807. (function (BABYLON) {
  23808. /** @hidden */
  23809. var ClickInfo = /** @class */ (function () {
  23810. function ClickInfo() {
  23811. this._singleClick = false;
  23812. this._doubleClick = false;
  23813. this._hasSwiped = false;
  23814. this._ignore = false;
  23815. }
  23816. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23817. get: function () {
  23818. return this._singleClick;
  23819. },
  23820. set: function (b) {
  23821. this._singleClick = b;
  23822. },
  23823. enumerable: true,
  23824. configurable: true
  23825. });
  23826. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23827. get: function () {
  23828. return this._doubleClick;
  23829. },
  23830. set: function (b) {
  23831. this._doubleClick = b;
  23832. },
  23833. enumerable: true,
  23834. configurable: true
  23835. });
  23836. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23837. get: function () {
  23838. return this._hasSwiped;
  23839. },
  23840. set: function (b) {
  23841. this._hasSwiped = b;
  23842. },
  23843. enumerable: true,
  23844. configurable: true
  23845. });
  23846. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23847. get: function () {
  23848. return this._ignore;
  23849. },
  23850. set: function (b) {
  23851. this._ignore = b;
  23852. },
  23853. enumerable: true,
  23854. configurable: true
  23855. });
  23856. return ClickInfo;
  23857. }());
  23858. /**
  23859. * This class is used by the onRenderingGroupObservable
  23860. */
  23861. var RenderingGroupInfo = /** @class */ (function () {
  23862. function RenderingGroupInfo() {
  23863. }
  23864. /**
  23865. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23866. * This stage will be fired no matter what
  23867. */
  23868. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23869. /**
  23870. * Called before opaque object are rendered.
  23871. * This stage will be fired only if there's 3D Opaque content to render
  23872. */
  23873. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23874. /**
  23875. * Called after the opaque objects are rendered and before the transparent ones
  23876. * This stage will be fired only if there's 3D transparent content to render
  23877. */
  23878. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23879. /**
  23880. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23881. * This stage will be fired no matter what
  23882. */
  23883. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23884. return RenderingGroupInfo;
  23885. }());
  23886. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23887. /**
  23888. * Represents a scene to be rendered by the engine.
  23889. * @see http://doc.babylonjs.com/features/scene
  23890. */
  23891. var Scene = /** @class */ (function () {
  23892. /**
  23893. * Creates a new Scene
  23894. * @param engine defines the engine to use to render this scene
  23895. */
  23896. function Scene(engine) {
  23897. // Members
  23898. /**
  23899. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23900. */
  23901. this.autoClear = true;
  23902. /**
  23903. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23904. */
  23905. this.autoClearDepthAndStencil = true;
  23906. /**
  23907. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23908. */
  23909. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23910. /**
  23911. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23912. */
  23913. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23914. this._forceWireframe = false;
  23915. this._forcePointsCloud = false;
  23916. /**
  23917. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23918. */
  23919. this.forceShowBoundingBoxes = false;
  23920. /**
  23921. * Gets or sets a boolean indicating if animations are enabled
  23922. */
  23923. this.animationsEnabled = true;
  23924. this._animationPropertiesOverride = null;
  23925. /**
  23926. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23927. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23928. */
  23929. this.useConstantAnimationDeltaTime = false;
  23930. /**
  23931. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23932. * Please note that it requires to run a ray cast through the scene on every frame
  23933. */
  23934. this.constantlyUpdateMeshUnderPointer = false;
  23935. /**
  23936. * Defines the HTML cursor to use when hovering over interactive elements
  23937. */
  23938. this.hoverCursor = "pointer";
  23939. /**
  23940. * Defines the HTML default cursor to use (empty by default)
  23941. */
  23942. this.defaultCursor = "";
  23943. /**
  23944. * This is used to call preventDefault() on pointer down
  23945. * in order to block unwanted artifacts like system double clicks
  23946. */
  23947. this.preventDefaultOnPointerDown = true;
  23948. // Metadata
  23949. /**
  23950. * Gets or sets user defined metadata
  23951. */
  23952. this.metadata = null;
  23953. /**
  23954. * Use this array to add regular expressions used to disable offline support for specific urls
  23955. */
  23956. this.disableOfflineSupportExceptionRules = new Array();
  23957. /**
  23958. * An event triggered when the scene is disposed.
  23959. */
  23960. this.onDisposeObservable = new BABYLON.Observable();
  23961. this._onDisposeObserver = null;
  23962. /**
  23963. * An event triggered before rendering the scene (right after animations and physics)
  23964. */
  23965. this.onBeforeRenderObservable = new BABYLON.Observable();
  23966. this._onBeforeRenderObserver = null;
  23967. /**
  23968. * An event triggered after rendering the scene
  23969. */
  23970. this.onAfterRenderObservable = new BABYLON.Observable();
  23971. this._onAfterRenderObserver = null;
  23972. /**
  23973. * An event triggered before animating the scene
  23974. */
  23975. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23976. /**
  23977. * An event triggered after animations processing
  23978. */
  23979. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23980. /**
  23981. * An event triggered before draw calls are ready to be sent
  23982. */
  23983. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23984. /**
  23985. * An event triggered after draw calls have been sent
  23986. */
  23987. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23988. /**
  23989. * An event triggered when physic simulation is about to be run
  23990. */
  23991. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23992. /**
  23993. * An event triggered when physic simulation has been done
  23994. */
  23995. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23996. /**
  23997. * An event triggered when the scene is ready
  23998. */
  23999. this.onReadyObservable = new BABYLON.Observable();
  24000. /**
  24001. * An event triggered before rendering a camera
  24002. */
  24003. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24004. this._onBeforeCameraRenderObserver = null;
  24005. /**
  24006. * An event triggered after rendering a camera
  24007. */
  24008. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24009. this._onAfterCameraRenderObserver = null;
  24010. /**
  24011. * An event triggered when active meshes evaluation is about to start
  24012. */
  24013. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24014. /**
  24015. * An event triggered when active meshes evaluation is done
  24016. */
  24017. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24018. /**
  24019. * An event triggered when particles rendering is about to start
  24020. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24021. */
  24022. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24023. /**
  24024. * An event triggered when particles rendering is done
  24025. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24026. */
  24027. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24028. /**
  24029. * An event triggered when sprites rendering is about to start
  24030. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24031. */
  24032. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24033. /**
  24034. * An event triggered when sprites rendering is done
  24035. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24036. */
  24037. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24038. /**
  24039. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24040. */
  24041. this.onDataLoadedObservable = new BABYLON.Observable();
  24042. /**
  24043. * An event triggered when a camera is created
  24044. */
  24045. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24046. /**
  24047. * An event triggered when a camera is removed
  24048. */
  24049. this.onCameraRemovedObservable = new BABYLON.Observable();
  24050. /**
  24051. * An event triggered when a light is created
  24052. */
  24053. this.onNewLightAddedObservable = new BABYLON.Observable();
  24054. /**
  24055. * An event triggered when a light is removed
  24056. */
  24057. this.onLightRemovedObservable = new BABYLON.Observable();
  24058. /**
  24059. * An event triggered when a geometry is created
  24060. */
  24061. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24062. /**
  24063. * An event triggered when a geometry is removed
  24064. */
  24065. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24066. /**
  24067. * An event triggered when a transform node is created
  24068. */
  24069. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24070. /**
  24071. * An event triggered when a transform node is removed
  24072. */
  24073. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24074. /**
  24075. * An event triggered when a mesh is created
  24076. */
  24077. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24078. /**
  24079. * An event triggered when a mesh is removed
  24080. */
  24081. this.onMeshRemovedObservable = new BABYLON.Observable();
  24082. /**
  24083. * An event triggered when render targets are about to be rendered
  24084. * Can happen multiple times per frame.
  24085. */
  24086. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24087. /**
  24088. * An event triggered when render targets were rendered.
  24089. * Can happen multiple times per frame.
  24090. */
  24091. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24092. /**
  24093. * An event triggered before calculating deterministic simulation step
  24094. */
  24095. this.onBeforeStepObservable = new BABYLON.Observable();
  24096. /**
  24097. * An event triggered after calculating deterministic simulation step
  24098. */
  24099. this.onAfterStepObservable = new BABYLON.Observable();
  24100. /**
  24101. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24102. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24103. * 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)
  24104. */
  24105. this.onRenderingGroupObservable = new BABYLON.Observable();
  24106. // Animations
  24107. /**
  24108. * Gets a list of Animations associated with the scene
  24109. */
  24110. this.animations = [];
  24111. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24112. /**
  24113. * 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).
  24114. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24115. */
  24116. this.onPrePointerObservable = new BABYLON.Observable();
  24117. /**
  24118. * Observable event triggered each time an input event is received from the rendering canvas
  24119. */
  24120. this.onPointerObservable = new BABYLON.Observable();
  24121. this._meshPickProceed = false;
  24122. this._currentPickResult = null;
  24123. this._previousPickResult = null;
  24124. this._totalPointersPressed = 0;
  24125. this._doubleClickOccured = false;
  24126. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24127. this.cameraToUseForPointers = null;
  24128. this._pointerX = 0;
  24129. this._pointerY = 0;
  24130. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24131. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24132. this._startingPointerTime = 0;
  24133. this._previousStartingPointerTime = 0;
  24134. this._pointerCaptures = {};
  24135. // Deterministic lockstep
  24136. this._timeAccumulator = 0;
  24137. this._currentStepId = 0;
  24138. this._currentInternalStep = 0;
  24139. // Keyboard
  24140. /**
  24141. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24142. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24143. */
  24144. this.onPreKeyboardObservable = new BABYLON.Observable();
  24145. /**
  24146. * Observable event triggered each time an keyboard event is received from the hosting window
  24147. */
  24148. this.onKeyboardObservable = new BABYLON.Observable();
  24149. // Coordinates system
  24150. this._useRightHandedSystem = false;
  24151. // Fog
  24152. this._fogEnabled = true;
  24153. this._fogMode = Scene.FOGMODE_NONE;
  24154. /**
  24155. * Gets or sets the fog color to use
  24156. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24157. */
  24158. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24159. /**
  24160. * Gets or sets the fog density to use
  24161. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24162. */
  24163. this.fogDensity = 0.1;
  24164. /**
  24165. * Gets or sets the fog start distance to use
  24166. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24167. */
  24168. this.fogStart = 0;
  24169. /**
  24170. * Gets or sets the fog end distance to use
  24171. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24172. */
  24173. this.fogEnd = 1000.0;
  24174. // Lights
  24175. this._shadowsEnabled = true;
  24176. this._lightsEnabled = true;
  24177. /**
  24178. * All of the lights added to this scene
  24179. * @see http://doc.babylonjs.com/babylon101/lights
  24180. */
  24181. this.lights = new Array();
  24182. // Cameras
  24183. /** All of the cameras added to this scene.
  24184. * @see http://doc.babylonjs.com/babylon101/cameras
  24185. */
  24186. this.cameras = new Array();
  24187. /** All of the active cameras added to this scene. */
  24188. this.activeCameras = new Array();
  24189. // Meshes
  24190. /**
  24191. * All of the tranform nodes added to this scene
  24192. * @see http://doc.babylonjs.com/how_to/transformnode
  24193. */
  24194. this.transformNodes = new Array();
  24195. /**
  24196. * All of the (abstract) meshes added to this scene
  24197. */
  24198. this.meshes = new Array();
  24199. /**
  24200. * All of the animation groups added to this scene
  24201. * @see http://doc.babylonjs.com/how_to/group
  24202. */
  24203. this.animationGroups = new Array();
  24204. // Geometries
  24205. this._geometries = new Array();
  24206. /**
  24207. * All of the materials added to this scene
  24208. * @see http://doc.babylonjs.com/babylon101/materials
  24209. */
  24210. this.materials = new Array();
  24211. /**
  24212. * All of the multi-materials added to this scene
  24213. * @see http://doc.babylonjs.com/how_to/multi_materials
  24214. */
  24215. this.multiMaterials = new Array();
  24216. // Textures
  24217. this._texturesEnabled = true;
  24218. /**
  24219. * All of the textures added to this scene
  24220. */
  24221. this.textures = new Array();
  24222. // Particles
  24223. /**
  24224. * Gets or sets a boolean indicating if particles are enabled on this scene
  24225. */
  24226. this.particlesEnabled = true;
  24227. /**
  24228. * All of the particle systems added to this scene
  24229. * @see http://doc.babylonjs.com/babylon101/particles
  24230. */
  24231. this.particleSystems = new Array();
  24232. // Sprites
  24233. /**
  24234. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24235. */
  24236. this.spritesEnabled = true;
  24237. /**
  24238. * All of the sprite managers added to this scene
  24239. * @see http://doc.babylonjs.com/babylon101/sprites
  24240. */
  24241. this.spriteManagers = new Array();
  24242. /**
  24243. * The list of layers (background and foreground) of the scene
  24244. */
  24245. this.layers = new Array();
  24246. /**
  24247. * The list of effect layers (highlights/glow) added to the scene
  24248. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24249. * @see http://doc.babylonjs.com/how_to/glow_layer
  24250. */
  24251. this.effectLayers = new Array();
  24252. // Skeletons
  24253. this._skeletonsEnabled = true;
  24254. /**
  24255. * The list of skeletons added to the scene
  24256. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24257. */
  24258. this.skeletons = new Array();
  24259. // Morph targets
  24260. /**
  24261. * The list of morph target managers added to the scene
  24262. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24263. */
  24264. this.morphTargetManagers = new Array();
  24265. // Lens flares
  24266. /**
  24267. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24268. */
  24269. this.lensFlaresEnabled = true;
  24270. /**
  24271. * The list of lens flare system added to the scene
  24272. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24273. */
  24274. this.lensFlareSystems = new Array();
  24275. // Collisions
  24276. /**
  24277. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24278. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24279. */
  24280. this.collisionsEnabled = true;
  24281. /**
  24282. * Defines the gravity applied to this scene (used only for collisions)
  24283. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24284. */
  24285. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24286. // Postprocesses
  24287. /**
  24288. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24289. */
  24290. this.postProcessesEnabled = true;
  24291. /**
  24292. * The list of postprocesses added to the scene
  24293. */
  24294. this.postProcesses = new Array();
  24295. // Customs render targets
  24296. /**
  24297. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24298. */
  24299. this.renderTargetsEnabled = true;
  24300. /**
  24301. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24302. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24303. */
  24304. this.dumpNextRenderTargets = false;
  24305. /**
  24306. * The list of user defined render targets added to the scene
  24307. */
  24308. this.customRenderTargets = new Array();
  24309. /**
  24310. * Gets the list of meshes imported to the scene through SceneLoader
  24311. */
  24312. this.importedMeshesFiles = new Array();
  24313. // Probes
  24314. /**
  24315. * Gets or sets a boolean indicating if probes are enabled on this scene
  24316. */
  24317. this.probesEnabled = true;
  24318. /**
  24319. * The list of reflection probes added to the scene
  24320. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24321. */
  24322. this.reflectionProbes = new Array();
  24323. /** @hidden */
  24324. this._actionManagers = new Array();
  24325. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24326. // Procedural textures
  24327. /**
  24328. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24329. */
  24330. this.proceduralTexturesEnabled = true;
  24331. /**
  24332. * The list of procedural textures added to the scene
  24333. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24334. */
  24335. this.proceduralTextures = new Array();
  24336. /**
  24337. * The list of sound tracks added to the scene
  24338. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24339. */
  24340. this.soundTracks = new Array();
  24341. this._audioEnabled = true;
  24342. this._headphone = false;
  24343. // Performance counters
  24344. this._totalVertices = new BABYLON.PerfCounter();
  24345. /** @hidden */
  24346. this._activeIndices = new BABYLON.PerfCounter();
  24347. /** @hidden */
  24348. this._activeParticles = new BABYLON.PerfCounter();
  24349. /** @hidden */
  24350. this._activeBones = new BABYLON.PerfCounter();
  24351. this._animationTime = 0;
  24352. /**
  24353. * Gets or sets a general scale for animation speed
  24354. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24355. */
  24356. this.animationTimeScale = 1;
  24357. this._renderId = 0;
  24358. this._executeWhenReadyTimeoutId = -1;
  24359. this._intermediateRendering = false;
  24360. this._viewUpdateFlag = -1;
  24361. this._projectionUpdateFlag = -1;
  24362. this._alternateViewUpdateFlag = -1;
  24363. this._alternateProjectionUpdateFlag = -1;
  24364. /** @hidden */
  24365. this._toBeDisposed = new BABYLON.SmartArray(256);
  24366. this._activeRequests = new Array();
  24367. this._pendingData = new Array();
  24368. this._isDisposed = false;
  24369. /**
  24370. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24371. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24372. */
  24373. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24374. this._activeMeshes = new BABYLON.SmartArray(256);
  24375. this._processedMaterials = new BABYLON.SmartArray(256);
  24376. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24377. /** @hidden */
  24378. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24379. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24380. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24381. /** @hidden */
  24382. this._activeAnimatables = new Array();
  24383. this._transformMatrix = BABYLON.Matrix.Zero();
  24384. this._useAlternateCameraConfiguration = false;
  24385. this._alternateRendering = false;
  24386. /**
  24387. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24388. * This is useful if there are more lights that the maximum simulteanous authorized
  24389. */
  24390. this.requireLightSorting = false;
  24391. this._depthRenderer = {};
  24392. this._activeMeshesFrozen = false;
  24393. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24394. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24395. this._engine.scenes.push(this);
  24396. this._uid = null;
  24397. this._renderingManager = new BABYLON.RenderingManager(this);
  24398. if (BABYLON.PostProcessManager) {
  24399. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24400. }
  24401. if (BABYLON.OutlineRenderer) {
  24402. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24403. }
  24404. if (BABYLON.Tools.IsWindowObjectExist()) {
  24405. this.attachControl();
  24406. }
  24407. //simplification queue
  24408. if (BABYLON.SimplificationQueue) {
  24409. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24410. }
  24411. //collision coordinator initialization. For now legacy per default.
  24412. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24413. // Uniform Buffer
  24414. this._createUbo();
  24415. // Default Image processing definition
  24416. if (BABYLON.ImageProcessingConfiguration) {
  24417. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24418. }
  24419. }
  24420. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24421. /** The fog is deactivated */
  24422. get: function () {
  24423. return Scene._FOGMODE_NONE;
  24424. },
  24425. enumerable: true,
  24426. configurable: true
  24427. });
  24428. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24429. /** The fog density is following an exponential function */
  24430. get: function () {
  24431. return Scene._FOGMODE_EXP;
  24432. },
  24433. enumerable: true,
  24434. configurable: true
  24435. });
  24436. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24437. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24438. get: function () {
  24439. return Scene._FOGMODE_EXP2;
  24440. },
  24441. enumerable: true,
  24442. configurable: true
  24443. });
  24444. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24445. /** The fog density is following a linear function. */
  24446. get: function () {
  24447. return Scene._FOGMODE_LINEAR;
  24448. },
  24449. enumerable: true,
  24450. configurable: true
  24451. });
  24452. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24453. /**
  24454. * Texture used in all pbr material as the reflection texture.
  24455. * As in the majority of the scene they are the same (exception for multi room and so on),
  24456. * this is easier to reference from here than from all the materials.
  24457. */
  24458. get: function () {
  24459. return this._environmentTexture;
  24460. },
  24461. /**
  24462. * Texture used in all pbr material as the reflection texture.
  24463. * As in the majority of the scene they are the same (exception for multi room and so on),
  24464. * this is easier to set here than in all the materials.
  24465. */
  24466. set: function (value) {
  24467. if (this._environmentTexture === value) {
  24468. return;
  24469. }
  24470. this._environmentTexture = value;
  24471. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24472. },
  24473. enumerable: true,
  24474. configurable: true
  24475. });
  24476. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24477. /**
  24478. * Default image processing configuration used either in the rendering
  24479. * Forward main pass or through the imageProcessingPostProcess if present.
  24480. * As in the majority of the scene they are the same (exception for multi camera),
  24481. * this is easier to reference from here than from all the materials and post process.
  24482. *
  24483. * No setter as we it is a shared configuration, you can set the values instead.
  24484. */
  24485. get: function () {
  24486. return this._imageProcessingConfiguration;
  24487. },
  24488. enumerable: true,
  24489. configurable: true
  24490. });
  24491. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24492. get: function () {
  24493. return this._forceWireframe;
  24494. },
  24495. /**
  24496. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24497. */
  24498. set: function (value) {
  24499. if (this._forceWireframe === value) {
  24500. return;
  24501. }
  24502. this._forceWireframe = value;
  24503. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24504. },
  24505. enumerable: true,
  24506. configurable: true
  24507. });
  24508. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24509. get: function () {
  24510. return this._forcePointsCloud;
  24511. },
  24512. /**
  24513. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24514. */
  24515. set: function (value) {
  24516. if (this._forcePointsCloud === value) {
  24517. return;
  24518. }
  24519. this._forcePointsCloud = value;
  24520. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24521. },
  24522. enumerable: true,
  24523. configurable: true
  24524. });
  24525. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24526. /**
  24527. * Gets or sets the animation properties override
  24528. */
  24529. get: function () {
  24530. return this._animationPropertiesOverride;
  24531. },
  24532. set: function (value) {
  24533. this._animationPropertiesOverride = value;
  24534. },
  24535. enumerable: true,
  24536. configurable: true
  24537. });
  24538. Object.defineProperty(Scene.prototype, "onDispose", {
  24539. /** Sets a function to be executed when this scene is disposed. */
  24540. set: function (callback) {
  24541. if (this._onDisposeObserver) {
  24542. this.onDisposeObservable.remove(this._onDisposeObserver);
  24543. }
  24544. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. Object.defineProperty(Scene.prototype, "beforeRender", {
  24550. /** Sets a function to be executed before rendering this scene */
  24551. set: function (callback) {
  24552. if (this._onBeforeRenderObserver) {
  24553. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24554. }
  24555. if (callback) {
  24556. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24557. }
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "afterRender", {
  24563. /** Sets a function to be executed after rendering this scene */
  24564. set: function (callback) {
  24565. if (this._onAfterRenderObserver) {
  24566. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24567. }
  24568. if (callback) {
  24569. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24570. }
  24571. },
  24572. enumerable: true,
  24573. configurable: true
  24574. });
  24575. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24576. /** Sets a function to be executed before rendering a camera*/
  24577. set: function (callback) {
  24578. if (this._onBeforeCameraRenderObserver) {
  24579. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24580. }
  24581. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24582. },
  24583. enumerable: true,
  24584. configurable: true
  24585. });
  24586. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24587. /** Sets a function to be executed after rendering a camera*/
  24588. set: function (callback) {
  24589. if (this._onAfterCameraRenderObserver) {
  24590. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24591. }
  24592. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24593. },
  24594. enumerable: true,
  24595. configurable: true
  24596. });
  24597. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24598. /**
  24599. * Gets the gamepad manager associated with the scene
  24600. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24601. */
  24602. get: function () {
  24603. if (!this._gamepadManager) {
  24604. this._gamepadManager = new BABYLON.GamepadManager(this);
  24605. }
  24606. return this._gamepadManager;
  24607. },
  24608. enumerable: true,
  24609. configurable: true
  24610. });
  24611. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24612. /**
  24613. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24614. */
  24615. get: function () {
  24616. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24617. },
  24618. enumerable: true,
  24619. configurable: true
  24620. });
  24621. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24622. get: function () {
  24623. return this._useRightHandedSystem;
  24624. },
  24625. /**
  24626. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24627. */
  24628. set: function (value) {
  24629. if (this._useRightHandedSystem === value) {
  24630. return;
  24631. }
  24632. this._useRightHandedSystem = value;
  24633. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24634. },
  24635. enumerable: true,
  24636. configurable: true
  24637. });
  24638. /**
  24639. * Sets the step Id used by deterministic lock step
  24640. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24641. * @param newStepId defines the step Id
  24642. */
  24643. Scene.prototype.setStepId = function (newStepId) {
  24644. this._currentStepId = newStepId;
  24645. };
  24646. ;
  24647. /**
  24648. * Gets the step Id used by deterministic lock step
  24649. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24650. * @returns the step Id
  24651. */
  24652. Scene.prototype.getStepId = function () {
  24653. return this._currentStepId;
  24654. };
  24655. ;
  24656. /**
  24657. * Gets the internal step used by deterministic lock step
  24658. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24659. * @returns the internal step
  24660. */
  24661. Scene.prototype.getInternalStep = function () {
  24662. return this._currentInternalStep;
  24663. };
  24664. ;
  24665. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24666. get: function () {
  24667. return this._fogEnabled;
  24668. },
  24669. /**
  24670. * Gets or sets a boolean indicating if fog is enabled on this scene
  24671. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24672. */
  24673. set: function (value) {
  24674. if (this._fogEnabled === value) {
  24675. return;
  24676. }
  24677. this._fogEnabled = value;
  24678. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24679. },
  24680. enumerable: true,
  24681. configurable: true
  24682. });
  24683. Object.defineProperty(Scene.prototype, "fogMode", {
  24684. get: function () {
  24685. return this._fogMode;
  24686. },
  24687. /**
  24688. * Gets or sets the fog mode to use
  24689. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24690. */
  24691. set: function (value) {
  24692. if (this._fogMode === value) {
  24693. return;
  24694. }
  24695. this._fogMode = value;
  24696. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24697. },
  24698. enumerable: true,
  24699. configurable: true
  24700. });
  24701. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24702. get: function () {
  24703. return this._shadowsEnabled;
  24704. },
  24705. /**
  24706. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24707. */
  24708. set: function (value) {
  24709. if (this._shadowsEnabled === value) {
  24710. return;
  24711. }
  24712. this._shadowsEnabled = value;
  24713. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24714. },
  24715. enumerable: true,
  24716. configurable: true
  24717. });
  24718. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24719. get: function () {
  24720. return this._lightsEnabled;
  24721. },
  24722. /**
  24723. * Gets or sets a boolean indicating if lights are enabled on this scene
  24724. */
  24725. set: function (value) {
  24726. if (this._lightsEnabled === value) {
  24727. return;
  24728. }
  24729. this._lightsEnabled = value;
  24730. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24731. },
  24732. enumerable: true,
  24733. configurable: true
  24734. });
  24735. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24736. /** The default material used on meshes when no material is affected */
  24737. get: function () {
  24738. if (!this._defaultMaterial) {
  24739. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24740. }
  24741. return this._defaultMaterial;
  24742. },
  24743. /** The default material used on meshes when no material is affected */
  24744. set: function (value) {
  24745. this._defaultMaterial = value;
  24746. },
  24747. enumerable: true,
  24748. configurable: true
  24749. });
  24750. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24751. get: function () {
  24752. return this._texturesEnabled;
  24753. },
  24754. /**
  24755. * Gets or sets a boolean indicating if textures are enabled on this scene
  24756. */
  24757. set: function (value) {
  24758. if (this._texturesEnabled === value) {
  24759. return;
  24760. }
  24761. this._texturesEnabled = value;
  24762. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24763. },
  24764. enumerable: true,
  24765. configurable: true
  24766. });
  24767. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24768. get: function () {
  24769. return this._skeletonsEnabled;
  24770. },
  24771. /**
  24772. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24773. */
  24774. set: function (value) {
  24775. if (this._skeletonsEnabled === value) {
  24776. return;
  24777. }
  24778. this._skeletonsEnabled = value;
  24779. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24780. },
  24781. enumerable: true,
  24782. configurable: true
  24783. });
  24784. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24785. /**
  24786. * Gets the postprocess render pipeline manager
  24787. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24788. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24789. */
  24790. get: function () {
  24791. if (!this._postProcessRenderPipelineManager) {
  24792. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24793. }
  24794. return this._postProcessRenderPipelineManager;
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24800. /**
  24801. * Gets the main soundtrack associated with the scene
  24802. */
  24803. get: function () {
  24804. if (!this._mainSoundTrack) {
  24805. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24806. }
  24807. return this._mainSoundTrack;
  24808. },
  24809. enumerable: true,
  24810. configurable: true
  24811. });
  24812. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24813. /** @hidden */
  24814. get: function () {
  24815. return this._alternateRendering;
  24816. },
  24817. enumerable: true,
  24818. configurable: true
  24819. });
  24820. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24821. /**
  24822. * Gets the list of frustum planes (built from the active camera)
  24823. */
  24824. get: function () {
  24825. return this._frustumPlanes;
  24826. },
  24827. enumerable: true,
  24828. configurable: true
  24829. });
  24830. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24831. /**
  24832. * Gets the current geometry buffer associated to the scene.
  24833. */
  24834. get: function () {
  24835. return this._geometryBufferRenderer;
  24836. },
  24837. /**
  24838. * Sets the current geometry buffer for the scene.
  24839. */
  24840. set: function (geometryBufferRenderer) {
  24841. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24842. this._geometryBufferRenderer = geometryBufferRenderer;
  24843. }
  24844. },
  24845. enumerable: true,
  24846. configurable: true
  24847. });
  24848. Object.defineProperty(Scene.prototype, "debugLayer", {
  24849. /**
  24850. * Gets the debug layer (aka Inspector) associated with the scene
  24851. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24852. */
  24853. get: function () {
  24854. if (!this._debugLayer) {
  24855. this._debugLayer = new BABYLON.DebugLayer(this);
  24856. }
  24857. return this._debugLayer;
  24858. },
  24859. enumerable: true,
  24860. configurable: true
  24861. });
  24862. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24863. /**
  24864. * Gets a boolean indicating if collisions are processed on a web worker
  24865. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24866. */
  24867. get: function () {
  24868. return this._workerCollisions;
  24869. },
  24870. set: function (enabled) {
  24871. if (!BABYLON.CollisionCoordinatorLegacy) {
  24872. return;
  24873. }
  24874. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24875. this._workerCollisions = enabled;
  24876. if (this.collisionCoordinator) {
  24877. this.collisionCoordinator.destroy();
  24878. }
  24879. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24880. this.collisionCoordinator.init(this);
  24881. },
  24882. enumerable: true,
  24883. configurable: true
  24884. });
  24885. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24886. /**
  24887. * Gets the octree used to boost mesh selection (picking)
  24888. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24889. */
  24890. get: function () {
  24891. return this._selectionOctree;
  24892. },
  24893. enumerable: true,
  24894. configurable: true
  24895. });
  24896. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24897. /**
  24898. * Gets the mesh that is currently under the pointer
  24899. */
  24900. get: function () {
  24901. return this._pointerOverMesh;
  24902. },
  24903. enumerable: true,
  24904. configurable: true
  24905. });
  24906. Object.defineProperty(Scene.prototype, "pointerX", {
  24907. /**
  24908. * Gets the current on-screen X position of the pointer
  24909. */
  24910. get: function () {
  24911. return this._pointerX;
  24912. },
  24913. enumerable: true,
  24914. configurable: true
  24915. });
  24916. Object.defineProperty(Scene.prototype, "pointerY", {
  24917. /**
  24918. * Gets the current on-screen Y position of the pointer
  24919. */
  24920. get: function () {
  24921. return this._pointerY;
  24922. },
  24923. enumerable: true,
  24924. configurable: true
  24925. });
  24926. /**
  24927. * Gets the cached material (ie. the latest rendered one)
  24928. * @returns the cached material
  24929. */
  24930. Scene.prototype.getCachedMaterial = function () {
  24931. return this._cachedMaterial;
  24932. };
  24933. /**
  24934. * Gets the cached effect (ie. the latest rendered one)
  24935. * @returns the cached effect
  24936. */
  24937. Scene.prototype.getCachedEffect = function () {
  24938. return this._cachedEffect;
  24939. };
  24940. /**
  24941. * Gets the cached visibility state (ie. the latest rendered one)
  24942. * @returns the cached visibility state
  24943. */
  24944. Scene.prototype.getCachedVisibility = function () {
  24945. return this._cachedVisibility;
  24946. };
  24947. /**
  24948. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24949. * @param material defines the current material
  24950. * @param effect defines the current effect
  24951. * @param visibility defines the current visibility state
  24952. * @returns true if one parameter is not cached
  24953. */
  24954. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24955. if (visibility === void 0) { visibility = 1; }
  24956. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24957. };
  24958. /**
  24959. * Gets the bounding box renderer associated with the scene
  24960. * @returns a BoundingBoxRenderer
  24961. */
  24962. Scene.prototype.getBoundingBoxRenderer = function () {
  24963. if (!this._boundingBoxRenderer) {
  24964. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24965. }
  24966. return this._boundingBoxRenderer;
  24967. };
  24968. /**
  24969. * Gets the outline renderer associated with the scene
  24970. * @returns a OutlineRenderer
  24971. */
  24972. Scene.prototype.getOutlineRenderer = function () {
  24973. return this._outlineRenderer;
  24974. };
  24975. /**
  24976. * Gets the engine associated with the scene
  24977. * @returns an Engine
  24978. */
  24979. Scene.prototype.getEngine = function () {
  24980. return this._engine;
  24981. };
  24982. /**
  24983. * Gets the total number of vertices rendered per frame
  24984. * @returns the total number of vertices rendered per frame
  24985. */
  24986. Scene.prototype.getTotalVertices = function () {
  24987. return this._totalVertices.current;
  24988. };
  24989. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24990. /**
  24991. * Gets the performance counter for total vertices
  24992. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24993. */
  24994. get: function () {
  24995. return this._totalVertices;
  24996. },
  24997. enumerable: true,
  24998. configurable: true
  24999. });
  25000. /**
  25001. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25002. * @returns the total number of active indices rendered per frame
  25003. */
  25004. Scene.prototype.getActiveIndices = function () {
  25005. return this._activeIndices.current;
  25006. };
  25007. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25008. /**
  25009. * Gets the performance counter for active indices
  25010. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25011. */
  25012. get: function () {
  25013. return this._activeIndices;
  25014. },
  25015. enumerable: true,
  25016. configurable: true
  25017. });
  25018. /**
  25019. * Gets the total number of active particles rendered per frame
  25020. * @returns the total number of active particles rendered per frame
  25021. */
  25022. Scene.prototype.getActiveParticles = function () {
  25023. return this._activeParticles.current;
  25024. };
  25025. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25026. /**
  25027. * Gets the performance counter for active particles
  25028. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25029. */
  25030. get: function () {
  25031. return this._activeParticles;
  25032. },
  25033. enumerable: true,
  25034. configurable: true
  25035. });
  25036. /**
  25037. * Gets the total number of active bones rendered per frame
  25038. * @returns the total number of active bones rendered per frame
  25039. */
  25040. Scene.prototype.getActiveBones = function () {
  25041. return this._activeBones.current;
  25042. };
  25043. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25044. /**
  25045. * Gets the performance counter for active bones
  25046. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25047. */
  25048. get: function () {
  25049. return this._activeBones;
  25050. },
  25051. enumerable: true,
  25052. configurable: true
  25053. });
  25054. /** @hidden */
  25055. Scene.prototype.getInterFramePerfCounter = function () {
  25056. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25057. return 0;
  25058. };
  25059. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25060. /** @hidden */
  25061. get: function () {
  25062. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25063. return null;
  25064. },
  25065. enumerable: true,
  25066. configurable: true
  25067. });
  25068. /** @hidden */
  25069. Scene.prototype.getLastFrameDuration = function () {
  25070. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25071. return 0;
  25072. };
  25073. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25074. /** @hidden */
  25075. get: function () {
  25076. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25077. return null;
  25078. },
  25079. enumerable: true,
  25080. configurable: true
  25081. });
  25082. /** @hidden */
  25083. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25084. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25085. return 0;
  25086. };
  25087. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25088. /** @hidden */
  25089. get: function () {
  25090. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25091. return null;
  25092. },
  25093. enumerable: true,
  25094. configurable: true
  25095. });
  25096. /**
  25097. * Gets the array of active meshes
  25098. * @returns an array of AbstractMesh
  25099. */
  25100. Scene.prototype.getActiveMeshes = function () {
  25101. return this._activeMeshes;
  25102. };
  25103. /** @hidden */
  25104. Scene.prototype.getRenderTargetsDuration = function () {
  25105. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25106. return 0;
  25107. };
  25108. /** @hidden */
  25109. Scene.prototype.getRenderDuration = function () {
  25110. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25111. return 0;
  25112. };
  25113. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25114. /** @hidden */
  25115. get: function () {
  25116. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25117. return null;
  25118. },
  25119. enumerable: true,
  25120. configurable: true
  25121. });
  25122. /** @hidden */
  25123. Scene.prototype.getParticlesDuration = function () {
  25124. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25125. return 0;
  25126. };
  25127. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25128. /** @hidden */
  25129. get: function () {
  25130. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25131. return null;
  25132. },
  25133. enumerable: true,
  25134. configurable: true
  25135. });
  25136. /** @hidden */
  25137. Scene.prototype.getSpritesDuration = function () {
  25138. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25139. return 0;
  25140. };
  25141. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25142. /** @hidden */
  25143. get: function () {
  25144. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25145. return null;
  25146. },
  25147. enumerable: true,
  25148. configurable: true
  25149. });
  25150. /**
  25151. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25152. * @returns a number
  25153. */
  25154. Scene.prototype.getAnimationRatio = function () {
  25155. return this._animationRatio;
  25156. };
  25157. /**
  25158. * Gets an unique Id for the current frame
  25159. * @returns a number
  25160. */
  25161. Scene.prototype.getRenderId = function () {
  25162. return this._renderId;
  25163. };
  25164. /** Call this function if you want to manually increment the render Id*/
  25165. Scene.prototype.incrementRenderId = function () {
  25166. this._renderId++;
  25167. };
  25168. Scene.prototype._updatePointerPosition = function (evt) {
  25169. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25170. if (!canvasRect) {
  25171. return;
  25172. }
  25173. this._pointerX = evt.clientX - canvasRect.left;
  25174. this._pointerY = evt.clientY - canvasRect.top;
  25175. this._unTranslatedPointerX = this._pointerX;
  25176. this._unTranslatedPointerY = this._pointerY;
  25177. };
  25178. Scene.prototype._createUbo = function () {
  25179. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25180. this._sceneUbo.addUniform("viewProjection", 16);
  25181. this._sceneUbo.addUniform("view", 16);
  25182. };
  25183. Scene.prototype._createAlternateUbo = function () {
  25184. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25185. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25186. this._alternateSceneUbo.addUniform("view", 16);
  25187. };
  25188. // Pointers handling
  25189. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25190. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25191. if (result) {
  25192. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25193. }
  25194. return result;
  25195. };
  25196. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25197. if (pointerInfo.pickInfo) {
  25198. if (!pointerInfo.pickInfo.ray) {
  25199. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25200. }
  25201. }
  25202. };
  25203. /**
  25204. * Use this method to simulate a pointer move on a mesh
  25205. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25206. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25207. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25208. * @returns the current scene
  25209. */
  25210. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25211. var evt = new PointerEvent("pointermove", pointerEventInit);
  25212. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25213. return this;
  25214. }
  25215. return this._processPointerMove(pickResult, evt);
  25216. };
  25217. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25218. var canvas = this._engine.getRenderingCanvas();
  25219. if (!canvas) {
  25220. return this;
  25221. }
  25222. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25223. this.setPointerOverSprite(null);
  25224. this.setPointerOverMesh(pickResult.pickedMesh);
  25225. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25226. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25227. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25228. }
  25229. else {
  25230. canvas.style.cursor = this.hoverCursor;
  25231. }
  25232. }
  25233. else {
  25234. canvas.style.cursor = this.defaultCursor;
  25235. }
  25236. }
  25237. else {
  25238. this.setPointerOverMesh(null);
  25239. // Sprites
  25240. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25241. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25242. this.setPointerOverSprite(pickResult.pickedSprite);
  25243. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25244. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25245. }
  25246. else {
  25247. canvas.style.cursor = this.hoverCursor;
  25248. }
  25249. }
  25250. else {
  25251. this.setPointerOverSprite(null);
  25252. // Restore pointer
  25253. canvas.style.cursor = this.defaultCursor;
  25254. }
  25255. }
  25256. if (pickResult) {
  25257. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25258. if (this.onPointerMove) {
  25259. this.onPointerMove(evt, pickResult, type);
  25260. }
  25261. if (this.onPointerObservable.hasObservers()) {
  25262. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25263. this._setRayOnPointerInfo(pi);
  25264. this.onPointerObservable.notifyObservers(pi, type);
  25265. }
  25266. }
  25267. return this;
  25268. };
  25269. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25270. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25271. if (pickResult) {
  25272. pi.ray = pickResult.ray;
  25273. }
  25274. this.onPrePointerObservable.notifyObservers(pi, type);
  25275. if (pi.skipOnPointerObservable) {
  25276. return true;
  25277. }
  25278. else {
  25279. return false;
  25280. }
  25281. };
  25282. /**
  25283. * Use this method to simulate a pointer down on a mesh
  25284. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25285. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25286. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25287. * @returns the current scene
  25288. */
  25289. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25290. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25291. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25292. return this;
  25293. }
  25294. return this._processPointerDown(pickResult, evt);
  25295. };
  25296. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25297. var _this = this;
  25298. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25299. this._pickedDownMesh = pickResult.pickedMesh;
  25300. var actionManager = pickResult.pickedMesh.actionManager;
  25301. if (actionManager) {
  25302. if (actionManager.hasPickTriggers) {
  25303. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25304. switch (evt.button) {
  25305. case 0:
  25306. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25307. break;
  25308. case 1:
  25309. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25310. break;
  25311. case 2:
  25312. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25313. break;
  25314. }
  25315. }
  25316. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25317. window.setTimeout(function () {
  25318. 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);
  25319. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25320. if (_this._totalPointersPressed !== 0 &&
  25321. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25322. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25323. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25324. _this._startingPointerTime = 0;
  25325. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25326. }
  25327. }
  25328. }, Scene.LongPressDelay);
  25329. }
  25330. }
  25331. }
  25332. if (pickResult) {
  25333. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25334. if (this.onPointerDown) {
  25335. this.onPointerDown(evt, pickResult, type);
  25336. }
  25337. if (this.onPointerObservable.hasObservers()) {
  25338. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25339. this._setRayOnPointerInfo(pi);
  25340. this.onPointerObservable.notifyObservers(pi, type);
  25341. }
  25342. }
  25343. return this;
  25344. };
  25345. /**
  25346. * Use this method to simulate a pointer up on a mesh
  25347. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25348. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25349. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25350. * @returns the current scene
  25351. */
  25352. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25353. var evt = new PointerEvent("pointerup", pointerEventInit);
  25354. var clickInfo = new ClickInfo();
  25355. clickInfo.singleClick = true;
  25356. clickInfo.ignore = true;
  25357. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25358. return this;
  25359. }
  25360. return this._processPointerUp(pickResult, evt, clickInfo);
  25361. };
  25362. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25363. if (pickResult && pickResult && pickResult.pickedMesh) {
  25364. this._pickedUpMesh = pickResult.pickedMesh;
  25365. if (this._pickedDownMesh === this._pickedUpMesh) {
  25366. if (this.onPointerPick) {
  25367. this.onPointerPick(evt, pickResult);
  25368. }
  25369. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25370. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25371. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25372. this._setRayOnPointerInfo(pi);
  25373. this.onPointerObservable.notifyObservers(pi, type_1);
  25374. }
  25375. }
  25376. if (pickResult.pickedMesh.actionManager) {
  25377. if (clickInfo.ignore) {
  25378. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25379. }
  25380. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25381. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25382. }
  25383. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25384. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25385. }
  25386. }
  25387. }
  25388. if (this._pickedDownMesh &&
  25389. this._pickedDownMesh.actionManager &&
  25390. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25391. this._pickedDownMesh !== this._pickedUpMesh) {
  25392. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25393. }
  25394. var type = BABYLON.PointerEventTypes.POINTERUP;
  25395. if (this.onPointerObservable.hasObservers()) {
  25396. if (!clickInfo.ignore) {
  25397. if (!clickInfo.hasSwiped) {
  25398. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25399. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25400. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25401. this._setRayOnPointerInfo(pi);
  25402. this.onPointerObservable.notifyObservers(pi, type_2);
  25403. }
  25404. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25405. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25406. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25407. this._setRayOnPointerInfo(pi);
  25408. this.onPointerObservable.notifyObservers(pi, type_3);
  25409. }
  25410. }
  25411. }
  25412. else {
  25413. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25414. this._setRayOnPointerInfo(pi);
  25415. this.onPointerObservable.notifyObservers(pi, type);
  25416. }
  25417. }
  25418. if (this.onPointerUp) {
  25419. this.onPointerUp(evt, pickResult, type);
  25420. }
  25421. return this;
  25422. };
  25423. /**
  25424. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25425. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25426. * @returns true if the pointer was captured
  25427. */
  25428. Scene.prototype.isPointerCaptured = function (pointerId) {
  25429. if (pointerId === void 0) { pointerId = 0; }
  25430. return this._pointerCaptures[pointerId];
  25431. };
  25432. /**
  25433. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25434. * @param attachUp defines if you want to attach events to pointerup
  25435. * @param attachDown defines if you want to attach events to pointerdown
  25436. * @param attachMove defines if you want to attach events to pointermove
  25437. */
  25438. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25439. var _this = this;
  25440. if (attachUp === void 0) { attachUp = true; }
  25441. if (attachDown === void 0) { attachDown = true; }
  25442. if (attachMove === void 0) { attachMove = true; }
  25443. this._initActionManager = function (act, clickInfo) {
  25444. if (!_this._meshPickProceed) {
  25445. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25446. _this._currentPickResult = pickResult;
  25447. if (pickResult) {
  25448. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25449. }
  25450. _this._meshPickProceed = true;
  25451. }
  25452. return act;
  25453. };
  25454. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25455. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25456. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25457. btn !== _this._previousButtonPressed) {
  25458. _this._doubleClickOccured = false;
  25459. clickInfo.singleClick = true;
  25460. clickInfo.ignore = false;
  25461. cb(clickInfo, _this._currentPickResult);
  25462. }
  25463. };
  25464. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25465. var clickInfo = new ClickInfo();
  25466. _this._currentPickResult = null;
  25467. var act = null;
  25468. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25469. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25470. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25471. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25472. act = _this._initActionManager(act, clickInfo);
  25473. if (act)
  25474. checkPicking = act.hasPickTriggers;
  25475. }
  25476. if (checkPicking) {
  25477. var btn = evt.button;
  25478. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25479. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25480. if (!clickInfo.hasSwiped) {
  25481. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25482. if (!checkSingleClickImmediately) {
  25483. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25484. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25485. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25486. act = _this._initActionManager(act, clickInfo);
  25487. if (act)
  25488. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25489. }
  25490. }
  25491. if (checkSingleClickImmediately) {
  25492. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25493. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25494. btn !== _this._previousButtonPressed) {
  25495. clickInfo.singleClick = true;
  25496. cb(clickInfo, _this._currentPickResult);
  25497. }
  25498. }
  25499. // at least one double click is required to be check and exclusive double click is enabled
  25500. else {
  25501. // wait that no double click has been raised during the double click delay
  25502. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25503. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25504. }
  25505. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25506. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25507. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25508. act = _this._initActionManager(act, clickInfo);
  25509. if (act)
  25510. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25511. }
  25512. if (checkDoubleClick) {
  25513. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25514. if (btn === _this._previousButtonPressed &&
  25515. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25516. !_this._doubleClickOccured) {
  25517. // pointer has not moved for 2 clicks, it's a double click
  25518. if (!clickInfo.hasSwiped &&
  25519. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25520. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25521. _this._previousStartingPointerTime = 0;
  25522. _this._doubleClickOccured = true;
  25523. clickInfo.doubleClick = true;
  25524. clickInfo.ignore = false;
  25525. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25526. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25527. }
  25528. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25529. cb(clickInfo, _this._currentPickResult);
  25530. }
  25531. // if the two successive clicks are too far, it's just two simple clicks
  25532. else {
  25533. _this._doubleClickOccured = false;
  25534. _this._previousStartingPointerTime = _this._startingPointerTime;
  25535. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25536. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25537. _this._previousButtonPressed = btn;
  25538. if (Scene.ExclusiveDoubleClickMode) {
  25539. if (_this._previousDelayedSimpleClickTimeout) {
  25540. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25541. }
  25542. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25543. cb(clickInfo, _this._previousPickResult);
  25544. }
  25545. else {
  25546. cb(clickInfo, _this._currentPickResult);
  25547. }
  25548. }
  25549. }
  25550. // just the first click of the double has been raised
  25551. else {
  25552. _this._doubleClickOccured = false;
  25553. _this._previousStartingPointerTime = _this._startingPointerTime;
  25554. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25555. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25556. _this._previousButtonPressed = btn;
  25557. }
  25558. }
  25559. }
  25560. }
  25561. clickInfo.ignore = true;
  25562. cb(clickInfo, _this._currentPickResult);
  25563. };
  25564. this._spritePredicate = function (sprite) {
  25565. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25566. };
  25567. this._onPointerMove = function (evt) {
  25568. _this._updatePointerPosition(evt);
  25569. // PreObservable support
  25570. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25571. return;
  25572. }
  25573. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25574. return;
  25575. }
  25576. if (!_this.pointerMovePredicate) {
  25577. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25578. }
  25579. // Meshes
  25580. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25581. _this._processPointerMove(pickResult, evt);
  25582. };
  25583. this._onPointerDown = function (evt) {
  25584. _this._totalPointersPressed++;
  25585. _this._pickedDownMesh = null;
  25586. _this._meshPickProceed = false;
  25587. _this._updatePointerPosition(evt);
  25588. if (_this.preventDefaultOnPointerDown && canvas) {
  25589. evt.preventDefault();
  25590. canvas.focus();
  25591. }
  25592. // PreObservable support
  25593. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25594. return;
  25595. }
  25596. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25597. return;
  25598. }
  25599. _this._pointerCaptures[evt.pointerId] = true;
  25600. _this._startingPointerPosition.x = _this._pointerX;
  25601. _this._startingPointerPosition.y = _this._pointerY;
  25602. _this._startingPointerTime = Date.now();
  25603. if (!_this.pointerDownPredicate) {
  25604. _this.pointerDownPredicate = function (mesh) {
  25605. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25606. };
  25607. }
  25608. // Meshes
  25609. _this._pickedDownMesh = null;
  25610. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25611. _this._processPointerDown(pickResult, evt);
  25612. // Sprites
  25613. _this._pickedDownSprite = null;
  25614. if (_this.spriteManagers.length > 0) {
  25615. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25616. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25617. if (pickResult.pickedSprite.actionManager) {
  25618. _this._pickedDownSprite = pickResult.pickedSprite;
  25619. switch (evt.button) {
  25620. case 0:
  25621. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25622. break;
  25623. case 1:
  25624. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25625. break;
  25626. case 2:
  25627. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25628. break;
  25629. }
  25630. if (pickResult.pickedSprite.actionManager) {
  25631. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25632. }
  25633. }
  25634. }
  25635. }
  25636. };
  25637. this._onPointerUp = function (evt) {
  25638. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25639. return; // So we need to test it the pointer down was pressed before.
  25640. }
  25641. _this._totalPointersPressed--;
  25642. _this._pickedUpMesh = null;
  25643. _this._meshPickProceed = false;
  25644. _this._updatePointerPosition(evt);
  25645. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25646. // PreObservable support
  25647. if (_this.onPrePointerObservable.hasObservers()) {
  25648. if (!clickInfo.ignore) {
  25649. if (!clickInfo.hasSwiped) {
  25650. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25651. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25652. return;
  25653. }
  25654. }
  25655. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25656. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25657. return;
  25658. }
  25659. }
  25660. }
  25661. }
  25662. else {
  25663. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25664. return;
  25665. }
  25666. }
  25667. }
  25668. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25669. return;
  25670. }
  25671. _this._pointerCaptures[evt.pointerId] = false;
  25672. if (!_this.pointerUpPredicate) {
  25673. _this.pointerUpPredicate = function (mesh) {
  25674. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25675. };
  25676. }
  25677. // Meshes
  25678. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25679. _this._initActionManager(null, clickInfo);
  25680. }
  25681. if (!pickResult) {
  25682. pickResult = _this._currentPickResult;
  25683. }
  25684. _this._processPointerUp(pickResult, evt, clickInfo);
  25685. // Sprites
  25686. if (!clickInfo.ignore) {
  25687. if (_this.spriteManagers.length > 0) {
  25688. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25689. if (spritePickResult) {
  25690. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25691. if (spritePickResult.pickedSprite.actionManager) {
  25692. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25693. if (spritePickResult.pickedSprite.actionManager) {
  25694. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25695. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25696. }
  25697. }
  25698. }
  25699. }
  25700. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25701. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25702. }
  25703. }
  25704. }
  25705. }
  25706. _this._previousPickResult = _this._currentPickResult;
  25707. });
  25708. };
  25709. this._onKeyDown = function (evt) {
  25710. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25711. if (_this.onPreKeyboardObservable.hasObservers()) {
  25712. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25713. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25714. if (pi.skipOnPointerObservable) {
  25715. return;
  25716. }
  25717. }
  25718. if (_this.onKeyboardObservable.hasObservers()) {
  25719. var pi = new BABYLON.KeyboardInfo(type, evt);
  25720. _this.onKeyboardObservable.notifyObservers(pi, type);
  25721. }
  25722. if (_this.actionManager) {
  25723. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25724. }
  25725. };
  25726. this._onKeyUp = function (evt) {
  25727. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25728. if (_this.onPreKeyboardObservable.hasObservers()) {
  25729. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25730. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25731. if (pi.skipOnPointerObservable) {
  25732. return;
  25733. }
  25734. }
  25735. if (_this.onKeyboardObservable.hasObservers()) {
  25736. var pi = new BABYLON.KeyboardInfo(type, evt);
  25737. _this.onKeyboardObservable.notifyObservers(pi, type);
  25738. }
  25739. if (_this.actionManager) {
  25740. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25741. }
  25742. };
  25743. var engine = this.getEngine();
  25744. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25745. if (!canvas) {
  25746. return;
  25747. }
  25748. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25749. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25750. });
  25751. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25752. if (!canvas) {
  25753. return;
  25754. }
  25755. canvas.removeEventListener("keydown", _this._onKeyDown);
  25756. canvas.removeEventListener("keyup", _this._onKeyUp);
  25757. });
  25758. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25759. var canvas = this._engine.getRenderingCanvas();
  25760. if (!canvas) {
  25761. return;
  25762. }
  25763. if (attachMove) {
  25764. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25765. // Wheel
  25766. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25767. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25768. }
  25769. if (attachDown) {
  25770. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25771. }
  25772. if (attachUp) {
  25773. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25774. }
  25775. canvas.tabIndex = 1;
  25776. };
  25777. /** Detaches all event handlers*/
  25778. Scene.prototype.detachControl = function () {
  25779. var engine = this.getEngine();
  25780. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25781. var canvas = engine.getRenderingCanvas();
  25782. if (!canvas) {
  25783. return;
  25784. }
  25785. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25786. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25787. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25788. if (this._onCanvasBlurObserver) {
  25789. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25790. }
  25791. if (this._onCanvasFocusObserver) {
  25792. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25793. }
  25794. // Wheel
  25795. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25796. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25797. // Keyboard
  25798. canvas.removeEventListener("keydown", this._onKeyDown);
  25799. canvas.removeEventListener("keyup", this._onKeyUp);
  25800. // Observables
  25801. this.onKeyboardObservable.clear();
  25802. this.onPreKeyboardObservable.clear();
  25803. this.onPointerObservable.clear();
  25804. this.onPrePointerObservable.clear();
  25805. };
  25806. /**
  25807. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25808. * Delay loaded resources are not taking in account
  25809. * @return true if all required resources are ready
  25810. */
  25811. Scene.prototype.isReady = function () {
  25812. if (this._isDisposed) {
  25813. return false;
  25814. }
  25815. if (this._pendingData.length > 0) {
  25816. return false;
  25817. }
  25818. var index;
  25819. var engine = this.getEngine();
  25820. // Geometries
  25821. for (index = 0; index < this._geometries.length; index++) {
  25822. var geometry = this._geometries[index];
  25823. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25824. return false;
  25825. }
  25826. }
  25827. // Meshes
  25828. for (index = 0; index < this.meshes.length; index++) {
  25829. var mesh = this.meshes[index];
  25830. if (!mesh.isEnabled()) {
  25831. continue;
  25832. }
  25833. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25834. continue;
  25835. }
  25836. if (!mesh.isReady(true)) {
  25837. return false;
  25838. }
  25839. // Effect layers
  25840. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25841. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25842. var layer = _a[_i];
  25843. if (!layer.hasMesh(mesh)) {
  25844. continue;
  25845. }
  25846. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25847. var subMesh = _c[_b];
  25848. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25849. return false;
  25850. }
  25851. }
  25852. }
  25853. }
  25854. // Post-processes
  25855. if (this.activeCameras && this.activeCameras.length > 0) {
  25856. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25857. var camera = _e[_d];
  25858. if (!camera.isReady(true)) {
  25859. return false;
  25860. }
  25861. }
  25862. }
  25863. else if (this.activeCamera) {
  25864. if (!this.activeCamera.isReady(true)) {
  25865. return false;
  25866. }
  25867. }
  25868. // Particles
  25869. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25870. var particleSystem = _g[_f];
  25871. if (!particleSystem.isReady()) {
  25872. return false;
  25873. }
  25874. }
  25875. return true;
  25876. };
  25877. /** Resets all cached information relative to material (including effect and visibility) */
  25878. Scene.prototype.resetCachedMaterial = function () {
  25879. this._cachedMaterial = null;
  25880. this._cachedEffect = null;
  25881. this._cachedVisibility = null;
  25882. };
  25883. /**
  25884. * Registers a function to be called before every frame render
  25885. * @param func defines the function to register
  25886. */
  25887. Scene.prototype.registerBeforeRender = function (func) {
  25888. this.onBeforeRenderObservable.add(func);
  25889. };
  25890. /**
  25891. * Unregisters a function called before every frame render
  25892. * @param func defines the function to unregister
  25893. */
  25894. Scene.prototype.unregisterBeforeRender = function (func) {
  25895. this.onBeforeRenderObservable.removeCallback(func);
  25896. };
  25897. /**
  25898. * Registers a function to be called after every frame render
  25899. * @param func defines the function to register
  25900. */
  25901. Scene.prototype.registerAfterRender = function (func) {
  25902. this.onAfterRenderObservable.add(func);
  25903. };
  25904. /**
  25905. * Unregisters a function called after every frame render
  25906. * @param func defines the function to unregister
  25907. */
  25908. Scene.prototype.unregisterAfterRender = function (func) {
  25909. this.onAfterRenderObservable.removeCallback(func);
  25910. };
  25911. Scene.prototype._executeOnceBeforeRender = function (func) {
  25912. var _this = this;
  25913. var execFunc = function () {
  25914. func();
  25915. setTimeout(function () {
  25916. _this.unregisterBeforeRender(execFunc);
  25917. });
  25918. };
  25919. this.registerBeforeRender(execFunc);
  25920. };
  25921. /**
  25922. * The provided function will run before render once and will be disposed afterwards.
  25923. * A timeout delay can be provided so that the function will be executed in N ms.
  25924. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25925. * @param func The function to be executed.
  25926. * @param timeout optional delay in ms
  25927. */
  25928. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25929. var _this = this;
  25930. if (timeout !== undefined) {
  25931. setTimeout(function () {
  25932. _this._executeOnceBeforeRender(func);
  25933. }, timeout);
  25934. }
  25935. else {
  25936. this._executeOnceBeforeRender(func);
  25937. }
  25938. };
  25939. /** @hidden */
  25940. Scene.prototype._addPendingData = function (data) {
  25941. this._pendingData.push(data);
  25942. };
  25943. /** @hidden */
  25944. Scene.prototype._removePendingData = function (data) {
  25945. var wasLoading = this.isLoading;
  25946. var index = this._pendingData.indexOf(data);
  25947. if (index !== -1) {
  25948. this._pendingData.splice(index, 1);
  25949. }
  25950. if (wasLoading && !this.isLoading) {
  25951. this.onDataLoadedObservable.notifyObservers(this);
  25952. }
  25953. };
  25954. /**
  25955. * Returns the number of items waiting to be loaded
  25956. * @returns the number of items waiting to be loaded
  25957. */
  25958. Scene.prototype.getWaitingItemsCount = function () {
  25959. return this._pendingData.length;
  25960. };
  25961. Object.defineProperty(Scene.prototype, "isLoading", {
  25962. /**
  25963. * Returns a boolean indicating if the scene is still loading data
  25964. */
  25965. get: function () {
  25966. return this._pendingData.length > 0;
  25967. },
  25968. enumerable: true,
  25969. configurable: true
  25970. });
  25971. /**
  25972. * Registers a function to be executed when the scene is ready
  25973. * @param {Function} func - the function to be executed
  25974. */
  25975. Scene.prototype.executeWhenReady = function (func) {
  25976. var _this = this;
  25977. this.onReadyObservable.add(func);
  25978. if (this._executeWhenReadyTimeoutId !== -1) {
  25979. return;
  25980. }
  25981. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25982. _this._checkIsReady();
  25983. }, 150);
  25984. };
  25985. /**
  25986. * Returns a promise that resolves when the scene is ready
  25987. * @returns A promise that resolves when the scene is ready
  25988. */
  25989. Scene.prototype.whenReadyAsync = function () {
  25990. var _this = this;
  25991. return new Promise(function (resolve) {
  25992. _this.executeWhenReady(function () {
  25993. resolve();
  25994. });
  25995. });
  25996. };
  25997. /** @hidden */
  25998. Scene.prototype._checkIsReady = function () {
  25999. var _this = this;
  26000. if (this.isReady()) {
  26001. this.onReadyObservable.notifyObservers(this);
  26002. this.onReadyObservable.clear();
  26003. this._executeWhenReadyTimeoutId = -1;
  26004. return;
  26005. }
  26006. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26007. _this._checkIsReady();
  26008. }, 150);
  26009. };
  26010. // Animations
  26011. /**
  26012. * Will start the animation sequence of a given target
  26013. * @param target defines the target
  26014. * @param from defines from which frame should animation start
  26015. * @param to defines until which frame should animation run.
  26016. * @param weight defines the weight to apply to the animation (1.0 by default)
  26017. * @param loop defines if the animation loops
  26018. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26019. * @param onAnimationEnd defines the function to be executed when the animation ends
  26020. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26021. * @returns the animatable object created for this animation
  26022. */
  26023. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26024. if (weight === void 0) { weight = 1.0; }
  26025. if (speedRatio === void 0) { speedRatio = 1.0; }
  26026. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26027. returnedAnimatable.weight = weight;
  26028. return returnedAnimatable;
  26029. };
  26030. /**
  26031. * Will start the animation sequence of a given target
  26032. * @param target defines the target
  26033. * @param from defines from which frame should animation start
  26034. * @param to defines until which frame should animation run.
  26035. * @param loop defines if the animation loops
  26036. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26037. * @param onAnimationEnd defines the function to be executed when the animation ends
  26038. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26039. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26040. * @returns the animatable object created for this animation
  26041. */
  26042. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26043. if (speedRatio === void 0) { speedRatio = 1.0; }
  26044. if (stopCurrent === void 0) { stopCurrent = true; }
  26045. if (from > to && speedRatio > 0) {
  26046. speedRatio *= -1;
  26047. }
  26048. if (stopCurrent) {
  26049. this.stopAnimation(target);
  26050. }
  26051. if (!animatable) {
  26052. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26053. }
  26054. // Local animations
  26055. if (target.animations) {
  26056. animatable.appendAnimations(target, target.animations);
  26057. }
  26058. // Children animations
  26059. if (target.getAnimatables) {
  26060. var animatables = target.getAnimatables();
  26061. for (var index = 0; index < animatables.length; index++) {
  26062. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26063. }
  26064. }
  26065. animatable.reset();
  26066. return animatable;
  26067. };
  26068. /**
  26069. * Begin a new animation on a given node
  26070. * @param target defines the target where the animation will take place
  26071. * @param animations defines the list of animations to start
  26072. * @param from defines the initial value
  26073. * @param to defines the final value
  26074. * @param loop defines if you want animation to loop (off by default)
  26075. * @param speedRatio defines the speed ratio to apply to all animations
  26076. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26077. * @returns the list of created animatables
  26078. */
  26079. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26080. if (speedRatio === undefined) {
  26081. speedRatio = 1.0;
  26082. }
  26083. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26084. return animatable;
  26085. };
  26086. /**
  26087. * Begin a new animation on a given node and its hierarchy
  26088. * @param target defines the root node where the animation will take place
  26089. * @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.
  26090. * @param animations defines the list of animations to start
  26091. * @param from defines the initial value
  26092. * @param to defines the final value
  26093. * @param loop defines if you want animation to loop (off by default)
  26094. * @param speedRatio defines the speed ratio to apply to all animations
  26095. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26096. * @returns the list of animatables created for all nodes
  26097. */
  26098. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26099. var children = target.getDescendants(directDescendantsOnly);
  26100. var result = [];
  26101. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26102. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26103. var child = children_1[_i];
  26104. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26105. }
  26106. return result;
  26107. };
  26108. /**
  26109. * Gets the animatable associated with a specific target
  26110. * @param target defines the target of the animatable
  26111. * @returns the required animatable if found
  26112. */
  26113. Scene.prototype.getAnimatableByTarget = function (target) {
  26114. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26115. if (this._activeAnimatables[index].target === target) {
  26116. return this._activeAnimatables[index];
  26117. }
  26118. }
  26119. return null;
  26120. };
  26121. /**
  26122. * Gets all animatables associated with a given target
  26123. * @param target defines the target to look animatables for
  26124. * @returns an array of Animatables
  26125. */
  26126. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26127. var result = [];
  26128. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26129. if (this._activeAnimatables[index].target === target) {
  26130. result.push(this._activeAnimatables[index]);
  26131. }
  26132. }
  26133. return result;
  26134. };
  26135. Object.defineProperty(Scene.prototype, "animatables", {
  26136. /**
  26137. * Gets all animatable attached to the scene
  26138. */
  26139. get: function () {
  26140. return this._activeAnimatables;
  26141. },
  26142. enumerable: true,
  26143. configurable: true
  26144. });
  26145. /**
  26146. * Will stop the animation of the given target
  26147. * @param target - the target
  26148. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26149. */
  26150. Scene.prototype.stopAnimation = function (target, animationName) {
  26151. var animatables = this.getAllAnimatablesByTarget(target);
  26152. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26153. var animatable = animatables_1[_i];
  26154. animatable.stop(animationName);
  26155. }
  26156. };
  26157. /**
  26158. * Stops and removes all animations that have been applied to the scene
  26159. */
  26160. Scene.prototype.stopAllAnimations = function () {
  26161. if (this._activeAnimatables) {
  26162. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26163. this._activeAnimatables[i].stop();
  26164. }
  26165. this._activeAnimatables = [];
  26166. }
  26167. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26168. var group = _a[_i];
  26169. group.stop();
  26170. }
  26171. };
  26172. Scene.prototype._animate = function () {
  26173. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26174. return;
  26175. }
  26176. // Getting time
  26177. var now = BABYLON.Tools.Now;
  26178. if (!this._animationTimeLast) {
  26179. if (this._pendingData.length > 0) {
  26180. return;
  26181. }
  26182. this._animationTimeLast = now;
  26183. }
  26184. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26185. this._animationTime += deltaTime;
  26186. this._animationTimeLast = now;
  26187. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26188. this._activeAnimatables[index]._animate(this._animationTime);
  26189. }
  26190. // Late animation bindings
  26191. this._processLateAnimationBindings();
  26192. };
  26193. /** @hidden */
  26194. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26195. var target = runtimeAnimation.target;
  26196. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26197. if (!target._lateAnimationHolders) {
  26198. target._lateAnimationHolders = {};
  26199. }
  26200. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26201. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26202. totalWeight: 0,
  26203. animations: [],
  26204. originalValue: originalValue
  26205. };
  26206. }
  26207. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26208. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26209. };
  26210. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26211. var normalizer = 1.0;
  26212. var finalPosition = BABYLON.Tmp.Vector3[0];
  26213. var finalScaling = BABYLON.Tmp.Vector3[1];
  26214. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26215. var startIndex = 0;
  26216. var originalAnimation = holder.animations[0];
  26217. var originalValue = holder.originalValue;
  26218. var scale = 1;
  26219. if (holder.totalWeight < 1.0) {
  26220. // We need to mix the original value in
  26221. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26222. scale = 1.0 - holder.totalWeight;
  26223. }
  26224. else {
  26225. startIndex = 1;
  26226. // We need to normalize the weights
  26227. normalizer = holder.totalWeight;
  26228. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26229. scale = originalAnimation.weight / normalizer;
  26230. if (scale == 1) {
  26231. return originalAnimation.currentValue;
  26232. }
  26233. }
  26234. finalScaling.scaleInPlace(scale);
  26235. finalPosition.scaleInPlace(scale);
  26236. finalQuaternion.scaleInPlace(scale);
  26237. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26238. var runtimeAnimation = holder.animations[animIndex];
  26239. var scale = runtimeAnimation.weight / normalizer;
  26240. var currentPosition = BABYLON.Tmp.Vector3[2];
  26241. var currentScaling = BABYLON.Tmp.Vector3[3];
  26242. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26243. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26244. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26245. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26246. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26247. }
  26248. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26249. return originalAnimation._workValue;
  26250. };
  26251. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26252. var originalAnimation = holder.animations[0];
  26253. var originalValue = holder.originalValue;
  26254. if (holder.animations.length === 1) {
  26255. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26256. }
  26257. var normalizer = 1.0;
  26258. var quaternions;
  26259. var weights;
  26260. if (holder.totalWeight < 1.0) {
  26261. var scale = 1.0 - holder.totalWeight;
  26262. quaternions = [];
  26263. weights = [];
  26264. quaternions.push(originalValue);
  26265. weights.push(scale);
  26266. }
  26267. else {
  26268. if (holder.animations.length === 2) { // Slerp as soon as we can
  26269. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26270. }
  26271. quaternions = [];
  26272. weights = [];
  26273. normalizer = holder.totalWeight;
  26274. }
  26275. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26276. var runtimeAnimation = holder.animations[animIndex];
  26277. quaternions.push(runtimeAnimation.currentValue);
  26278. weights.push(runtimeAnimation.weight / normalizer);
  26279. }
  26280. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26281. var cumulativeAmount = 0;
  26282. var cumulativeQuaternion = null;
  26283. for (var index = 0; index < quaternions.length;) {
  26284. if (!cumulativeQuaternion) {
  26285. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26286. cumulativeAmount = weights[index] + weights[index + 1];
  26287. index += 2;
  26288. continue;
  26289. }
  26290. cumulativeAmount += weights[index];
  26291. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26292. index++;
  26293. }
  26294. return cumulativeQuaternion;
  26295. };
  26296. Scene.prototype._processLateAnimationBindings = function () {
  26297. if (!this._registeredForLateAnimationBindings.length) {
  26298. return;
  26299. }
  26300. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26301. var target = this._registeredForLateAnimationBindings.data[index];
  26302. for (var path in target._lateAnimationHolders) {
  26303. var holder = target._lateAnimationHolders[path];
  26304. var originalAnimation = holder.animations[0];
  26305. var originalValue = holder.originalValue;
  26306. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26307. var finalValue = void 0;
  26308. if (matrixDecomposeMode) {
  26309. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26310. }
  26311. else {
  26312. var quaternionMode = originalValue.w !== undefined;
  26313. if (quaternionMode) {
  26314. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26315. }
  26316. else {
  26317. var startIndex = 0;
  26318. var normalizer = 1.0;
  26319. if (holder.totalWeight < 1.0) {
  26320. // We need to mix the original value in
  26321. if (originalValue.scale) {
  26322. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26323. }
  26324. else {
  26325. finalValue = originalValue * (1.0 - holder.totalWeight);
  26326. }
  26327. }
  26328. else {
  26329. // We need to normalize the weights
  26330. normalizer = holder.totalWeight;
  26331. var scale_1 = originalAnimation.weight / normalizer;
  26332. if (scale_1 !== 1) {
  26333. if (originalAnimation.currentValue.scale) {
  26334. finalValue = originalAnimation.currentValue.scale(scale_1);
  26335. }
  26336. else {
  26337. finalValue = originalAnimation.currentValue * scale_1;
  26338. }
  26339. }
  26340. else {
  26341. finalValue = originalAnimation.currentValue;
  26342. }
  26343. startIndex = 1;
  26344. }
  26345. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26346. var runtimeAnimation = holder.animations[animIndex];
  26347. var scale = runtimeAnimation.weight / normalizer;
  26348. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26349. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26350. }
  26351. else {
  26352. finalValue += runtimeAnimation.currentValue * scale;
  26353. }
  26354. }
  26355. }
  26356. }
  26357. target[path] = finalValue;
  26358. }
  26359. target._lateAnimationHolders = {};
  26360. }
  26361. this._registeredForLateAnimationBindings.reset();
  26362. };
  26363. // Matrix
  26364. /** @hidden */
  26365. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26366. this._useAlternateCameraConfiguration = active;
  26367. };
  26368. /**
  26369. * Gets the current view matrix
  26370. * @returns a Matrix
  26371. */
  26372. Scene.prototype.getViewMatrix = function () {
  26373. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26374. };
  26375. /**
  26376. * Gets the current projection matrix
  26377. * @returns a Matrix
  26378. */
  26379. Scene.prototype.getProjectionMatrix = function () {
  26380. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26381. };
  26382. /**
  26383. * Gets the current transform matrix
  26384. * @returns a Matrix made of View * Projection
  26385. */
  26386. Scene.prototype.getTransformMatrix = function () {
  26387. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26388. };
  26389. /**
  26390. * Sets the current transform matrix
  26391. * @param view defines the View matrix to use
  26392. * @param projection defines the Projection matrix to use
  26393. */
  26394. Scene.prototype.setTransformMatrix = function (view, projection) {
  26395. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26396. return;
  26397. }
  26398. this._viewUpdateFlag = view.updateFlag;
  26399. this._projectionUpdateFlag = projection.updateFlag;
  26400. this._viewMatrix = view;
  26401. this._projectionMatrix = projection;
  26402. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26403. // Update frustum
  26404. if (!this._frustumPlanes) {
  26405. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26406. }
  26407. else {
  26408. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26409. }
  26410. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26411. var otherCamera = this.activeCamera._alternateCamera;
  26412. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26413. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26414. }
  26415. if (this._sceneUbo.useUbo) {
  26416. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26417. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26418. this._sceneUbo.update();
  26419. }
  26420. };
  26421. /** @hidden */
  26422. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26423. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26424. return;
  26425. }
  26426. this._alternateViewUpdateFlag = view.updateFlag;
  26427. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26428. this._alternateViewMatrix = view;
  26429. this._alternateProjectionMatrix = projection;
  26430. if (!this._alternateTransformMatrix) {
  26431. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26432. }
  26433. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26434. if (!this._alternateSceneUbo) {
  26435. this._createAlternateUbo();
  26436. }
  26437. if (this._alternateSceneUbo.useUbo) {
  26438. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26439. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26440. this._alternateSceneUbo.update();
  26441. }
  26442. };
  26443. /**
  26444. * Gets the uniform buffer used to store scene data
  26445. * @returns a UniformBuffer
  26446. */
  26447. Scene.prototype.getSceneUniformBuffer = function () {
  26448. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26449. };
  26450. /**
  26451. * Gets an unique (relatively to the current scene) Id
  26452. * @returns an unique number for the scene
  26453. */
  26454. Scene.prototype.getUniqueId = function () {
  26455. var result = Scene._uniqueIdCounter;
  26456. Scene._uniqueIdCounter++;
  26457. return result;
  26458. };
  26459. /**
  26460. * Add a mesh to the list of scene's meshes
  26461. * @param newMesh defines the mesh to add
  26462. * @param recursive if all child meshes should also be added to the scene
  26463. */
  26464. Scene.prototype.addMesh = function (newMesh, recursive) {
  26465. var _this = this;
  26466. if (recursive === void 0) { recursive = false; }
  26467. this.meshes.push(newMesh);
  26468. //notify the collision coordinator
  26469. if (this.collisionCoordinator) {
  26470. this.collisionCoordinator.onMeshAdded(newMesh);
  26471. }
  26472. newMesh._resyncLightSources();
  26473. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26474. if (recursive) {
  26475. newMesh.getChildMeshes().forEach(function (m) {
  26476. _this.addMesh(m);
  26477. });
  26478. }
  26479. };
  26480. /**
  26481. * Remove a mesh for the list of scene's meshes
  26482. * @param toRemove defines the mesh to remove
  26483. * @param recursive if all child meshes should also be removed from the scene
  26484. * @returns the index where the mesh was in the mesh list
  26485. */
  26486. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26487. var _this = this;
  26488. if (recursive === void 0) { recursive = false; }
  26489. var index = this.meshes.indexOf(toRemove);
  26490. if (index !== -1) {
  26491. // Remove from the scene if mesh found
  26492. this.meshes.splice(index, 1);
  26493. }
  26494. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26495. if (recursive) {
  26496. toRemove.getChildMeshes().forEach(function (m) {
  26497. _this.removeMesh(m);
  26498. });
  26499. }
  26500. return index;
  26501. };
  26502. /**
  26503. * Add a transform node to the list of scene's transform nodes
  26504. * @param newTransformNode defines the transform node to add
  26505. */
  26506. Scene.prototype.addTransformNode = function (newTransformNode) {
  26507. this.transformNodes.push(newTransformNode);
  26508. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26509. };
  26510. /**
  26511. * Remove a transform node for the list of scene's transform nodes
  26512. * @param toRemove defines the transform node to remove
  26513. * @returns the index where the transform node was in the transform node list
  26514. */
  26515. Scene.prototype.removeTransformNode = function (toRemove) {
  26516. var index = this.transformNodes.indexOf(toRemove);
  26517. if (index !== -1) {
  26518. // Remove from the scene if found
  26519. this.transformNodes.splice(index, 1);
  26520. }
  26521. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26522. return index;
  26523. };
  26524. /**
  26525. * Remove a skeleton for the list of scene's skeletons
  26526. * @param toRemove defines the skeleton to remove
  26527. * @returns the index where the skeleton was in the skeleton list
  26528. */
  26529. Scene.prototype.removeSkeleton = function (toRemove) {
  26530. var index = this.skeletons.indexOf(toRemove);
  26531. if (index !== -1) {
  26532. // Remove from the scene if found
  26533. this.skeletons.splice(index, 1);
  26534. }
  26535. return index;
  26536. };
  26537. /**
  26538. * Remove a morph target for the list of scene's morph targets
  26539. * @param toRemove defines the morph target to remove
  26540. * @returns the index where the morph target was in the morph target list
  26541. */
  26542. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26543. var index = this.morphTargetManagers.indexOf(toRemove);
  26544. if (index !== -1) {
  26545. // Remove from the scene if found
  26546. this.morphTargetManagers.splice(index, 1);
  26547. }
  26548. return index;
  26549. };
  26550. /**
  26551. * Remove a light for the list of scene's lights
  26552. * @param toRemove defines the light to remove
  26553. * @returns the index where the light was in the light list
  26554. */
  26555. Scene.prototype.removeLight = function (toRemove) {
  26556. var index = this.lights.indexOf(toRemove);
  26557. if (index !== -1) {
  26558. // Remove from meshes
  26559. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26560. var mesh = _a[_i];
  26561. mesh._removeLightSource(toRemove);
  26562. }
  26563. // Remove from the scene if mesh found
  26564. this.lights.splice(index, 1);
  26565. this.sortLightsByPriority();
  26566. }
  26567. this.onLightRemovedObservable.notifyObservers(toRemove);
  26568. return index;
  26569. };
  26570. /**
  26571. * Remove a camera for the list of scene's cameras
  26572. * @param toRemove defines the camera to remove
  26573. * @returns the index where the camera was in the camera list
  26574. */
  26575. Scene.prototype.removeCamera = function (toRemove) {
  26576. var index = this.cameras.indexOf(toRemove);
  26577. if (index !== -1) {
  26578. // Remove from the scene if mesh found
  26579. this.cameras.splice(index, 1);
  26580. }
  26581. // Remove from activeCameras
  26582. var index2 = this.activeCameras.indexOf(toRemove);
  26583. if (index2 !== -1) {
  26584. // Remove from the scene if mesh found
  26585. this.activeCameras.splice(index2, 1);
  26586. }
  26587. // Reset the activeCamera
  26588. if (this.activeCamera === toRemove) {
  26589. if (this.cameras.length > 0) {
  26590. this.activeCamera = this.cameras[0];
  26591. }
  26592. else {
  26593. this.activeCamera = null;
  26594. }
  26595. }
  26596. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26597. return index;
  26598. };
  26599. /**
  26600. * Remove a particle system for the list of scene's particle systems
  26601. * @param toRemove defines the particle system to remove
  26602. * @returns the index where the particle system was in the particle system list
  26603. */
  26604. Scene.prototype.removeParticleSystem = function (toRemove) {
  26605. var index = this.particleSystems.indexOf(toRemove);
  26606. if (index !== -1) {
  26607. this.particleSystems.splice(index, 1);
  26608. }
  26609. return index;
  26610. };
  26611. /**
  26612. * Remove a animation for the list of scene's animations
  26613. * @param toRemove defines the animation to remove
  26614. * @returns the index where the animation was in the animation list
  26615. */
  26616. Scene.prototype.removeAnimation = function (toRemove) {
  26617. var index = this.animations.indexOf(toRemove);
  26618. if (index !== -1) {
  26619. this.animations.splice(index, 1);
  26620. }
  26621. return index;
  26622. };
  26623. /**
  26624. * Removes the given animation group from this scene.
  26625. * @param toRemove The animation group to remove
  26626. * @returns The index of the removed animation group
  26627. */
  26628. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26629. var index = this.animationGroups.indexOf(toRemove);
  26630. if (index !== -1) {
  26631. this.animationGroups.splice(index, 1);
  26632. }
  26633. return index;
  26634. };
  26635. /**
  26636. * Removes the given multi-material from this scene.
  26637. * @param toRemove The multi-material to remove
  26638. * @returns The index of the removed multi-material
  26639. */
  26640. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26641. var index = this.multiMaterials.indexOf(toRemove);
  26642. if (index !== -1) {
  26643. this.multiMaterials.splice(index, 1);
  26644. }
  26645. return index;
  26646. };
  26647. /**
  26648. * Removes the given material from this scene.
  26649. * @param toRemove The material to remove
  26650. * @returns The index of the removed material
  26651. */
  26652. Scene.prototype.removeMaterial = function (toRemove) {
  26653. var index = this.materials.indexOf(toRemove);
  26654. if (index !== -1) {
  26655. this.materials.splice(index, 1);
  26656. }
  26657. return index;
  26658. };
  26659. /**
  26660. * Removes the given lens flare system from this scene.
  26661. * @param toRemove The lens flare system to remove
  26662. * @returns The index of the removed lens flare system
  26663. */
  26664. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26665. var index = this.lensFlareSystems.indexOf(toRemove);
  26666. if (index !== -1) {
  26667. this.lensFlareSystems.splice(index, 1);
  26668. }
  26669. return index;
  26670. };
  26671. /**
  26672. * Removes the given action manager from this scene.
  26673. * @param toRemove The action manager to remove
  26674. * @returns The index of the removed action manager
  26675. */
  26676. Scene.prototype.removeActionManager = function (toRemove) {
  26677. var index = this._actionManagers.indexOf(toRemove);
  26678. if (index !== -1) {
  26679. this._actionManagers.splice(index, 1);
  26680. }
  26681. return index;
  26682. };
  26683. /**
  26684. * Removes the given effect layer from this scene.
  26685. * @param toRemove defines the effect layer to remove
  26686. * @returns the index of the removed effect layer
  26687. */
  26688. Scene.prototype.removeEffectLayer = function (toRemove) {
  26689. var index = this.effectLayers.indexOf(toRemove);
  26690. if (index !== -1) {
  26691. this.effectLayers.splice(index, 1);
  26692. }
  26693. return index;
  26694. };
  26695. /**
  26696. * Removes the given texture from this scene.
  26697. * @param toRemove The texture to remove
  26698. * @returns The index of the removed texture
  26699. */
  26700. Scene.prototype.removeTexture = function (toRemove) {
  26701. var index = this.textures.indexOf(toRemove);
  26702. if (index !== -1) {
  26703. this.textures.splice(index, 1);
  26704. }
  26705. return index;
  26706. };
  26707. /**
  26708. * Adds the given light to this scene
  26709. * @param newLight The light to add
  26710. */
  26711. Scene.prototype.addLight = function (newLight) {
  26712. this.lights.push(newLight);
  26713. this.sortLightsByPriority();
  26714. // Add light to all meshes (To support if the light is removed and then readded)
  26715. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26716. var mesh = _a[_i];
  26717. if (mesh._lightSources.indexOf(newLight) === -1) {
  26718. mesh._lightSources.push(newLight);
  26719. mesh._resyncLightSources();
  26720. }
  26721. }
  26722. this.onNewLightAddedObservable.notifyObservers(newLight);
  26723. };
  26724. /**
  26725. * Sorts the list list based on light priorities
  26726. */
  26727. Scene.prototype.sortLightsByPriority = function () {
  26728. if (this.requireLightSorting) {
  26729. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26730. }
  26731. };
  26732. /**
  26733. * Adds the given camera to this scene
  26734. * @param newCamera The camera to add
  26735. */
  26736. Scene.prototype.addCamera = function (newCamera) {
  26737. this.cameras.push(newCamera);
  26738. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26739. };
  26740. /**
  26741. * Adds the given skeleton to this scene
  26742. * @param newSkeleton The skeleton to add
  26743. */
  26744. Scene.prototype.addSkeleton = function (newSkeleton) {
  26745. this.skeletons.push(newSkeleton);
  26746. };
  26747. /**
  26748. * Adds the given particle system to this scene
  26749. * @param newParticleSystem The particle system to add
  26750. */
  26751. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26752. this.particleSystems.push(newParticleSystem);
  26753. };
  26754. /**
  26755. * Adds the given animation to this scene
  26756. * @param newAnimation The animation to add
  26757. */
  26758. Scene.prototype.addAnimation = function (newAnimation) {
  26759. this.animations.push(newAnimation);
  26760. };
  26761. /**
  26762. * Adds the given animation group to this scene.
  26763. * @param newAnimationGroup The animation group to add
  26764. */
  26765. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26766. this.animationGroups.push(newAnimationGroup);
  26767. };
  26768. /**
  26769. * Adds the given multi-material to this scene
  26770. * @param newMultiMaterial The multi-material to add
  26771. */
  26772. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26773. this.multiMaterials.push(newMultiMaterial);
  26774. };
  26775. /**
  26776. * Adds the given material to this scene
  26777. * @param newMaterial The material to add
  26778. */
  26779. Scene.prototype.addMaterial = function (newMaterial) {
  26780. this.materials.push(newMaterial);
  26781. };
  26782. /**
  26783. * Adds the given morph target to this scene
  26784. * @param newMorphTargetManager The morph target to add
  26785. */
  26786. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26787. this.morphTargetManagers.push(newMorphTargetManager);
  26788. };
  26789. /**
  26790. * Adds the given geometry to this scene
  26791. * @param newGeometry The geometry to add
  26792. */
  26793. Scene.prototype.addGeometry = function (newGeometry) {
  26794. this._geometries.push(newGeometry);
  26795. };
  26796. /**
  26797. * Adds the given lens flare system to this scene
  26798. * @param newLensFlareSystem The lens flare system to add
  26799. */
  26800. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26801. this.lensFlareSystems.push(newLensFlareSystem);
  26802. };
  26803. /**
  26804. * Adds the given effect layer to this scene
  26805. * @param newEffectLayer defines the effect layer to add
  26806. */
  26807. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26808. this.effectLayers.push(newEffectLayer);
  26809. };
  26810. /**
  26811. * Adds the given action manager to this scene
  26812. * @param newActionManager The action manager to add
  26813. */
  26814. Scene.prototype.addActionManager = function (newActionManager) {
  26815. this._actionManagers.push(newActionManager);
  26816. };
  26817. /**
  26818. * Adds the given texture to this scene.
  26819. * @param newTexture The texture to add
  26820. */
  26821. Scene.prototype.addTexture = function (newTexture) {
  26822. this.textures.push(newTexture);
  26823. };
  26824. /**
  26825. * Switch active camera
  26826. * @param newCamera defines the new active camera
  26827. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26828. */
  26829. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26830. if (attachControl === void 0) { attachControl = true; }
  26831. var canvas = this._engine.getRenderingCanvas();
  26832. if (!canvas) {
  26833. return;
  26834. }
  26835. if (this.activeCamera) {
  26836. this.activeCamera.detachControl(canvas);
  26837. }
  26838. this.activeCamera = newCamera;
  26839. if (attachControl) {
  26840. newCamera.attachControl(canvas);
  26841. }
  26842. };
  26843. /**
  26844. * sets the active camera of the scene using its ID
  26845. * @param id defines the camera's ID
  26846. * @return the new active camera or null if none found.
  26847. */
  26848. Scene.prototype.setActiveCameraByID = function (id) {
  26849. var camera = this.getCameraByID(id);
  26850. if (camera) {
  26851. this.activeCamera = camera;
  26852. return camera;
  26853. }
  26854. return null;
  26855. };
  26856. /**
  26857. * sets the active camera of the scene using its name
  26858. * @param name defines the camera's name
  26859. * @returns the new active camera or null if none found.
  26860. */
  26861. Scene.prototype.setActiveCameraByName = function (name) {
  26862. var camera = this.getCameraByName(name);
  26863. if (camera) {
  26864. this.activeCamera = camera;
  26865. return camera;
  26866. }
  26867. return null;
  26868. };
  26869. /**
  26870. * get an animation group using its name
  26871. * @param name defines the material's name
  26872. * @return the animation group or null if none found.
  26873. */
  26874. Scene.prototype.getAnimationGroupByName = function (name) {
  26875. for (var index = 0; index < this.animationGroups.length; index++) {
  26876. if (this.animationGroups[index].name === name) {
  26877. return this.animationGroups[index];
  26878. }
  26879. }
  26880. return null;
  26881. };
  26882. /**
  26883. * get a material using its id
  26884. * @param id defines the material's ID
  26885. * @return the material or null if none found.
  26886. */
  26887. Scene.prototype.getMaterialByID = function (id) {
  26888. for (var index = 0; index < this.materials.length; index++) {
  26889. if (this.materials[index].id === id) {
  26890. return this.materials[index];
  26891. }
  26892. }
  26893. return null;
  26894. };
  26895. /**
  26896. * Gets a material using its name
  26897. * @param name defines the material's name
  26898. * @return the material or null if none found.
  26899. */
  26900. Scene.prototype.getMaterialByName = function (name) {
  26901. for (var index = 0; index < this.materials.length; index++) {
  26902. if (this.materials[index].name === name) {
  26903. return this.materials[index];
  26904. }
  26905. }
  26906. return null;
  26907. };
  26908. /**
  26909. * Gets a lens flare system using its name
  26910. * @param name defines the name to look for
  26911. * @returns the lens flare system or null if not found
  26912. */
  26913. Scene.prototype.getLensFlareSystemByName = function (name) {
  26914. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26915. if (this.lensFlareSystems[index].name === name) {
  26916. return this.lensFlareSystems[index];
  26917. }
  26918. }
  26919. return null;
  26920. };
  26921. /**
  26922. * Gets a lens flare system using its id
  26923. * @param id defines the id to look for
  26924. * @returns the lens flare system or null if not found
  26925. */
  26926. Scene.prototype.getLensFlareSystemByID = function (id) {
  26927. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26928. if (this.lensFlareSystems[index].id === id) {
  26929. return this.lensFlareSystems[index];
  26930. }
  26931. }
  26932. return null;
  26933. };
  26934. /**
  26935. * Gets a camera using its id
  26936. * @param id defines the id to look for
  26937. * @returns the camera or null if not found
  26938. */
  26939. Scene.prototype.getCameraByID = function (id) {
  26940. for (var index = 0; index < this.cameras.length; index++) {
  26941. if (this.cameras[index].id === id) {
  26942. return this.cameras[index];
  26943. }
  26944. }
  26945. return null;
  26946. };
  26947. /**
  26948. * Gets a camera using its unique id
  26949. * @param uniqueId defines the unique id to look for
  26950. * @returns the camera or null if not found
  26951. */
  26952. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26953. for (var index = 0; index < this.cameras.length; index++) {
  26954. if (this.cameras[index].uniqueId === uniqueId) {
  26955. return this.cameras[index];
  26956. }
  26957. }
  26958. return null;
  26959. };
  26960. /**
  26961. * Gets a camera using its name
  26962. * @param name defines the camera's name
  26963. * @return the camera or null if none found.
  26964. */
  26965. Scene.prototype.getCameraByName = function (name) {
  26966. for (var index = 0; index < this.cameras.length; index++) {
  26967. if (this.cameras[index].name === name) {
  26968. return this.cameras[index];
  26969. }
  26970. }
  26971. return null;
  26972. };
  26973. /**
  26974. * Gets a bone using its id
  26975. * @param id defines the bone's id
  26976. * @return the bone or null if not found
  26977. */
  26978. Scene.prototype.getBoneByID = function (id) {
  26979. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26980. var skeleton = this.skeletons[skeletonIndex];
  26981. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26982. if (skeleton.bones[boneIndex].id === id) {
  26983. return skeleton.bones[boneIndex];
  26984. }
  26985. }
  26986. }
  26987. return null;
  26988. };
  26989. /**
  26990. * Gets a bone using its id
  26991. * @param name defines the bone's name
  26992. * @return the bone or null if not found
  26993. */
  26994. Scene.prototype.getBoneByName = function (name) {
  26995. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26996. var skeleton = this.skeletons[skeletonIndex];
  26997. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26998. if (skeleton.bones[boneIndex].name === name) {
  26999. return skeleton.bones[boneIndex];
  27000. }
  27001. }
  27002. }
  27003. return null;
  27004. };
  27005. /**
  27006. * Gets a light node using its name
  27007. * @param name defines the the light's name
  27008. * @return the light or null if none found.
  27009. */
  27010. Scene.prototype.getLightByName = function (name) {
  27011. for (var index = 0; index < this.lights.length; index++) {
  27012. if (this.lights[index].name === name) {
  27013. return this.lights[index];
  27014. }
  27015. }
  27016. return null;
  27017. };
  27018. /**
  27019. * Gets a light node using its id
  27020. * @param id defines the light's id
  27021. * @return the light or null if none found.
  27022. */
  27023. Scene.prototype.getLightByID = function (id) {
  27024. for (var index = 0; index < this.lights.length; index++) {
  27025. if (this.lights[index].id === id) {
  27026. return this.lights[index];
  27027. }
  27028. }
  27029. return null;
  27030. };
  27031. /**
  27032. * Gets a light node using its scene-generated unique ID
  27033. * @param uniqueId defines the light's unique id
  27034. * @return the light or null if none found.
  27035. */
  27036. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27037. for (var index = 0; index < this.lights.length; index++) {
  27038. if (this.lights[index].uniqueId === uniqueId) {
  27039. return this.lights[index];
  27040. }
  27041. }
  27042. return null;
  27043. };
  27044. /**
  27045. * Gets a particle system by id
  27046. * @param id defines the particle system id
  27047. * @return the corresponding system or null if none found
  27048. */
  27049. Scene.prototype.getParticleSystemByID = function (id) {
  27050. for (var index = 0; index < this.particleSystems.length; index++) {
  27051. if (this.particleSystems[index].id === id) {
  27052. return this.particleSystems[index];
  27053. }
  27054. }
  27055. return null;
  27056. };
  27057. /**
  27058. * Gets a geometry using its ID
  27059. * @param id defines the geometry's id
  27060. * @return the geometry or null if none found.
  27061. */
  27062. Scene.prototype.getGeometryByID = function (id) {
  27063. for (var index = 0; index < this._geometries.length; index++) {
  27064. if (this._geometries[index].id === id) {
  27065. return this._geometries[index];
  27066. }
  27067. }
  27068. return null;
  27069. };
  27070. /**
  27071. * Add a new geometry to this scene
  27072. * @param geometry defines the geometry to be added to the scene.
  27073. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27074. * @return a boolean defining if the geometry was added or not
  27075. */
  27076. Scene.prototype.pushGeometry = function (geometry, force) {
  27077. if (!force && this.getGeometryByID(geometry.id)) {
  27078. return false;
  27079. }
  27080. this._geometries.push(geometry);
  27081. //notify the collision coordinator
  27082. if (this.collisionCoordinator) {
  27083. this.collisionCoordinator.onGeometryAdded(geometry);
  27084. }
  27085. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27086. return true;
  27087. };
  27088. /**
  27089. * Removes an existing geometry
  27090. * @param geometry defines the geometry to be removed from the scene
  27091. * @return a boolean defining if the geometry was removed or not
  27092. */
  27093. Scene.prototype.removeGeometry = function (geometry) {
  27094. var index = this._geometries.indexOf(geometry);
  27095. if (index > -1) {
  27096. this._geometries.splice(index, 1);
  27097. //notify the collision coordinator
  27098. if (this.collisionCoordinator) {
  27099. this.collisionCoordinator.onGeometryDeleted(geometry);
  27100. }
  27101. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27102. return true;
  27103. }
  27104. return false;
  27105. };
  27106. /**
  27107. * Gets the list of geometries attached to the scene
  27108. * @returns an array of Geometry
  27109. */
  27110. Scene.prototype.getGeometries = function () {
  27111. return this._geometries;
  27112. };
  27113. /**
  27114. * Gets the first added mesh found of a given ID
  27115. * @param id defines the id to search for
  27116. * @return the mesh found or null if not found at all
  27117. */
  27118. Scene.prototype.getMeshByID = function (id) {
  27119. for (var index = 0; index < this.meshes.length; index++) {
  27120. if (this.meshes[index].id === id) {
  27121. return this.meshes[index];
  27122. }
  27123. }
  27124. return null;
  27125. };
  27126. /**
  27127. * Gets a list of meshes using their id
  27128. * @param id defines the id to search for
  27129. * @returns a list of meshes
  27130. */
  27131. Scene.prototype.getMeshesByID = function (id) {
  27132. return this.meshes.filter(function (m) {
  27133. return m.id === id;
  27134. });
  27135. };
  27136. /**
  27137. * Gets the first added transform node found of a given ID
  27138. * @param id defines the id to search for
  27139. * @return the found transform node or null if not found at all.
  27140. */
  27141. Scene.prototype.getTransformNodeByID = function (id) {
  27142. for (var index = 0; index < this.transformNodes.length; index++) {
  27143. if (this.transformNodes[index].id === id) {
  27144. return this.transformNodes[index];
  27145. }
  27146. }
  27147. return null;
  27148. };
  27149. /**
  27150. * Gets a list of transform nodes using their id
  27151. * @param id defines the id to search for
  27152. * @returns a list of transform nodes
  27153. */
  27154. Scene.prototype.getTransformNodesByID = function (id) {
  27155. return this.transformNodes.filter(function (m) {
  27156. return m.id === id;
  27157. });
  27158. };
  27159. /**
  27160. * Gets a mesh with its auto-generated unique id
  27161. * @param uniqueId defines the unique id to search for
  27162. * @return the found mesh or null if not found at all.
  27163. */
  27164. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27165. for (var index = 0; index < this.meshes.length; index++) {
  27166. if (this.meshes[index].uniqueId === uniqueId) {
  27167. return this.meshes[index];
  27168. }
  27169. }
  27170. return null;
  27171. };
  27172. /**
  27173. * Gets a the last added mesh using a given id
  27174. * @param id defines the id to search for
  27175. * @return the found mesh or null if not found at all.
  27176. */
  27177. Scene.prototype.getLastMeshByID = function (id) {
  27178. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27179. if (this.meshes[index].id === id) {
  27180. return this.meshes[index];
  27181. }
  27182. }
  27183. return null;
  27184. };
  27185. /**
  27186. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27187. * @param id defines the id to search for
  27188. * @return the found node or null if not found at all
  27189. */
  27190. Scene.prototype.getLastEntryByID = function (id) {
  27191. var index;
  27192. for (index = this.meshes.length - 1; index >= 0; index--) {
  27193. if (this.meshes[index].id === id) {
  27194. return this.meshes[index];
  27195. }
  27196. }
  27197. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27198. if (this.transformNodes[index].id === id) {
  27199. return this.transformNodes[index];
  27200. }
  27201. }
  27202. for (index = this.cameras.length - 1; index >= 0; index--) {
  27203. if (this.cameras[index].id === id) {
  27204. return this.cameras[index];
  27205. }
  27206. }
  27207. for (index = this.lights.length - 1; index >= 0; index--) {
  27208. if (this.lights[index].id === id) {
  27209. return this.lights[index];
  27210. }
  27211. }
  27212. return null;
  27213. };
  27214. /**
  27215. * Gets a node (Mesh, Camera, Light) using a given id
  27216. * @param id defines the id to search for
  27217. * @return the found node or null if not found at all
  27218. */
  27219. Scene.prototype.getNodeByID = function (id) {
  27220. var mesh = this.getMeshByID(id);
  27221. if (mesh) {
  27222. return mesh;
  27223. }
  27224. var light = this.getLightByID(id);
  27225. if (light) {
  27226. return light;
  27227. }
  27228. var camera = this.getCameraByID(id);
  27229. if (camera) {
  27230. return camera;
  27231. }
  27232. var bone = this.getBoneByID(id);
  27233. return bone;
  27234. };
  27235. /**
  27236. * Gets a node (Mesh, Camera, Light) using a given name
  27237. * @param name defines the name to search for
  27238. * @return the found node or null if not found at all.
  27239. */
  27240. Scene.prototype.getNodeByName = function (name) {
  27241. var mesh = this.getMeshByName(name);
  27242. if (mesh) {
  27243. return mesh;
  27244. }
  27245. var light = this.getLightByName(name);
  27246. if (light) {
  27247. return light;
  27248. }
  27249. var camera = this.getCameraByName(name);
  27250. if (camera) {
  27251. return camera;
  27252. }
  27253. var bone = this.getBoneByName(name);
  27254. return bone;
  27255. };
  27256. /**
  27257. * Gets a mesh using a given name
  27258. * @param name defines the name to search for
  27259. * @return the found mesh or null if not found at all.
  27260. */
  27261. Scene.prototype.getMeshByName = function (name) {
  27262. for (var index = 0; index < this.meshes.length; index++) {
  27263. if (this.meshes[index].name === name) {
  27264. return this.meshes[index];
  27265. }
  27266. }
  27267. return null;
  27268. };
  27269. /**
  27270. * Gets a transform node using a given name
  27271. * @param name defines the name to search for
  27272. * @return the found transform node or null if not found at all.
  27273. */
  27274. Scene.prototype.getTransformNodeByName = function (name) {
  27275. for (var index = 0; index < this.transformNodes.length; index++) {
  27276. if (this.transformNodes[index].name === name) {
  27277. return this.transformNodes[index];
  27278. }
  27279. }
  27280. return null;
  27281. };
  27282. /**
  27283. * Gets a sound using a given name
  27284. * @param name defines the name to search for
  27285. * @return the found sound or null if not found at all.
  27286. */
  27287. Scene.prototype.getSoundByName = function (name) {
  27288. var index;
  27289. if (BABYLON.AudioEngine) {
  27290. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27291. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27292. return this.mainSoundTrack.soundCollection[index];
  27293. }
  27294. }
  27295. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27296. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27297. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27298. return this.soundTracks[sdIndex].soundCollection[index];
  27299. }
  27300. }
  27301. }
  27302. }
  27303. return null;
  27304. };
  27305. /**
  27306. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27307. * @param id defines the id to search for
  27308. * @return the found skeleton or null if not found at all.
  27309. */
  27310. Scene.prototype.getLastSkeletonByID = function (id) {
  27311. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27312. if (this.skeletons[index].id === id) {
  27313. return this.skeletons[index];
  27314. }
  27315. }
  27316. return null;
  27317. };
  27318. /**
  27319. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27320. * @param id defines the id to search for
  27321. * @return the found skeleton or null if not found at all.
  27322. */
  27323. Scene.prototype.getSkeletonById = function (id) {
  27324. for (var index = 0; index < this.skeletons.length; index++) {
  27325. if (this.skeletons[index].id === id) {
  27326. return this.skeletons[index];
  27327. }
  27328. }
  27329. return null;
  27330. };
  27331. /**
  27332. * Gets a skeleton using a given name
  27333. * @param name defines the name to search for
  27334. * @return the found skeleton or null if not found at all.
  27335. */
  27336. Scene.prototype.getSkeletonByName = function (name) {
  27337. for (var index = 0; index < this.skeletons.length; index++) {
  27338. if (this.skeletons[index].name === name) {
  27339. return this.skeletons[index];
  27340. }
  27341. }
  27342. return null;
  27343. };
  27344. /**
  27345. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27346. * @param id defines the id to search for
  27347. * @return the found morph target manager or null if not found at all.
  27348. */
  27349. Scene.prototype.getMorphTargetManagerById = function (id) {
  27350. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27351. if (this.morphTargetManagers[index].uniqueId === id) {
  27352. return this.morphTargetManagers[index];
  27353. }
  27354. }
  27355. return null;
  27356. };
  27357. /**
  27358. * Gets a boolean indicating if the given mesh is active
  27359. * @param mesh defines the mesh to look for
  27360. * @returns true if the mesh is in the active list
  27361. */
  27362. Scene.prototype.isActiveMesh = function (mesh) {
  27363. return (this._activeMeshes.indexOf(mesh) !== -1);
  27364. };
  27365. /**
  27366. * Return a the first highlight layer of the scene with a given name.
  27367. * @param name The name of the highlight layer to look for.
  27368. * @return The highlight layer if found otherwise null.
  27369. */
  27370. Scene.prototype.getHighlightLayerByName = function (name) {
  27371. for (var index = 0; index < this.effectLayers.length; index++) {
  27372. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27373. return this.effectLayers[index];
  27374. }
  27375. }
  27376. return null;
  27377. };
  27378. /**
  27379. * Return a the first highlight layer of the scene with a given name.
  27380. * @param name The name of the highlight layer to look for.
  27381. * @return The highlight layer if found otherwise null.
  27382. */
  27383. Scene.prototype.getGlowLayerByName = function (name) {
  27384. for (var index = 0; index < this.effectLayers.length; index++) {
  27385. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27386. return this.effectLayers[index];
  27387. }
  27388. }
  27389. return null;
  27390. };
  27391. Object.defineProperty(Scene.prototype, "uid", {
  27392. /**
  27393. * Return a unique id as a string which can serve as an identifier for the scene
  27394. */
  27395. get: function () {
  27396. if (!this._uid) {
  27397. this._uid = BABYLON.Tools.RandomId();
  27398. }
  27399. return this._uid;
  27400. },
  27401. enumerable: true,
  27402. configurable: true
  27403. });
  27404. /**
  27405. * Add an externaly attached data from its key.
  27406. * This method call will fail and return false, if such key already exists.
  27407. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27408. * @param key the unique key that identifies the data
  27409. * @param data the data object to associate to the key for this Engine instance
  27410. * @return true if no such key were already present and the data was added successfully, false otherwise
  27411. */
  27412. Scene.prototype.addExternalData = function (key, data) {
  27413. if (!this._externalData) {
  27414. this._externalData = new BABYLON.StringDictionary();
  27415. }
  27416. return this._externalData.add(key, data);
  27417. };
  27418. /**
  27419. * Get an externaly attached data from its key
  27420. * @param key the unique key that identifies the data
  27421. * @return the associated data, if present (can be null), or undefined if not present
  27422. */
  27423. Scene.prototype.getExternalData = function (key) {
  27424. if (!this._externalData) {
  27425. return null;
  27426. }
  27427. return this._externalData.get(key);
  27428. };
  27429. /**
  27430. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27431. * @param key the unique key that identifies the data
  27432. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27433. * @return the associated data, can be null if the factory returned null.
  27434. */
  27435. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27436. if (!this._externalData) {
  27437. this._externalData = new BABYLON.StringDictionary();
  27438. }
  27439. return this._externalData.getOrAddWithFactory(key, factory);
  27440. };
  27441. /**
  27442. * Remove an externaly attached data from the Engine instance
  27443. * @param key the unique key that identifies the data
  27444. * @return true if the data was successfully removed, false if it doesn't exist
  27445. */
  27446. Scene.prototype.removeExternalData = function (key) {
  27447. return this._externalData.remove(key);
  27448. };
  27449. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27450. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27451. if (mesh.showSubMeshesBoundingBox) {
  27452. var boundingInfo = subMesh.getBoundingInfo();
  27453. if (boundingInfo !== null && boundingInfo !== undefined) {
  27454. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27455. }
  27456. }
  27457. var material = subMesh.getMaterial();
  27458. if (material !== null && material !== undefined) {
  27459. // Render targets
  27460. if (material.getRenderTargetTextures !== undefined) {
  27461. if (this._processedMaterials.indexOf(material) === -1) {
  27462. this._processedMaterials.push(material);
  27463. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27464. }
  27465. }
  27466. // Dispatch
  27467. this._activeIndices.addCount(subMesh.indexCount, false);
  27468. this._renderingManager.dispatch(subMesh, mesh, material);
  27469. }
  27470. }
  27471. };
  27472. /**
  27473. * Clear the processed materials smart array preventing retention point in material dispose.
  27474. */
  27475. Scene.prototype.freeProcessedMaterials = function () {
  27476. this._processedMaterials.dispose();
  27477. };
  27478. /**
  27479. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27480. */
  27481. Scene.prototype.freeActiveMeshes = function () {
  27482. this._activeMeshes.dispose();
  27483. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27484. this.activeCamera._activeMeshes.dispose();
  27485. }
  27486. if (this.activeCameras) {
  27487. for (var i = 0; i < this.activeCameras.length; i++) {
  27488. var activeCamera = this.activeCameras[i];
  27489. if (activeCamera && activeCamera._activeMeshes) {
  27490. activeCamera._activeMeshes.dispose();
  27491. }
  27492. }
  27493. }
  27494. };
  27495. /**
  27496. * Clear the info related to rendering groups preventing retention points during dispose.
  27497. */
  27498. Scene.prototype.freeRenderingGroups = function () {
  27499. if (this._renderingManager) {
  27500. this._renderingManager.freeRenderingGroups();
  27501. }
  27502. if (this.textures) {
  27503. for (var i = 0; i < this.textures.length; i++) {
  27504. var texture = this.textures[i];
  27505. if (texture && texture.renderList) {
  27506. texture.freeRenderingGroups();
  27507. }
  27508. }
  27509. }
  27510. };
  27511. /** @hidden */
  27512. Scene.prototype._isInIntermediateRendering = function () {
  27513. return this._intermediateRendering;
  27514. };
  27515. /**
  27516. * Defines the current active mesh candidate provider
  27517. * @param provider defines the provider to use
  27518. */
  27519. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27520. this._activeMeshCandidateProvider = provider;
  27521. };
  27522. /**
  27523. * Gets the current active mesh candidate provider
  27524. * @returns the current active mesh candidate provider
  27525. */
  27526. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27527. return this._activeMeshCandidateProvider;
  27528. };
  27529. /**
  27530. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27531. * @returns the current scene
  27532. */
  27533. Scene.prototype.freezeActiveMeshes = function () {
  27534. if (!this.activeCamera) {
  27535. return this;
  27536. }
  27537. if (!this._frustumPlanes) {
  27538. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27539. }
  27540. this._evaluateActiveMeshes();
  27541. this._activeMeshesFrozen = true;
  27542. return this;
  27543. };
  27544. /**
  27545. * Use this function to restart evaluating active meshes on every frame
  27546. * @returns the current scene
  27547. */
  27548. Scene.prototype.unfreezeActiveMeshes = function () {
  27549. this._activeMeshesFrozen = false;
  27550. return this;
  27551. };
  27552. Scene.prototype._evaluateActiveMeshes = function () {
  27553. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27554. return;
  27555. }
  27556. if (!this.activeCamera) {
  27557. return;
  27558. }
  27559. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27560. this.activeCamera._activeMeshes.reset();
  27561. this._activeMeshes.reset();
  27562. this._renderingManager.reset();
  27563. this._processedMaterials.reset();
  27564. this._activeParticleSystems.reset();
  27565. this._activeSkeletons.reset();
  27566. this._softwareSkinnedMeshes.reset();
  27567. if (this._boundingBoxRenderer) {
  27568. this._boundingBoxRenderer.reset();
  27569. }
  27570. // Meshes
  27571. var meshes;
  27572. var len;
  27573. var checkIsEnabled = true;
  27574. // Determine mesh candidates
  27575. if (this._activeMeshCandidateProvider !== undefined) {
  27576. // Use _activeMeshCandidateProvider
  27577. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27578. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27579. if (meshes !== undefined) {
  27580. len = meshes.length;
  27581. }
  27582. else {
  27583. len = 0;
  27584. }
  27585. }
  27586. else if (this._selectionOctree !== undefined) {
  27587. // Octree
  27588. var selection = this._selectionOctree.select(this._frustumPlanes);
  27589. meshes = selection.data;
  27590. len = selection.length;
  27591. }
  27592. else {
  27593. // Full scene traversal
  27594. len = this.meshes.length;
  27595. meshes = this.meshes;
  27596. }
  27597. // Check each mesh
  27598. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27599. mesh = meshes[meshIndex];
  27600. if (mesh.isBlocked) {
  27601. continue;
  27602. }
  27603. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27604. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27605. continue;
  27606. }
  27607. mesh.computeWorldMatrix();
  27608. // Intersections
  27609. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27610. this._meshesForIntersections.pushNoDuplicate(mesh);
  27611. }
  27612. // Switch to current LOD
  27613. meshLOD = mesh.getLOD(this.activeCamera);
  27614. if (meshLOD === undefined || meshLOD === null) {
  27615. continue;
  27616. }
  27617. mesh._preActivate();
  27618. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27619. this._activeMeshes.push(mesh);
  27620. this.activeCamera._activeMeshes.push(mesh);
  27621. mesh._activate(this._renderId);
  27622. if (meshLOD !== mesh) {
  27623. meshLOD._activate(this._renderId);
  27624. }
  27625. this._activeMesh(mesh, meshLOD);
  27626. }
  27627. }
  27628. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27629. // Particle systems
  27630. if (this.particlesEnabled) {
  27631. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27632. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27633. var particleSystem = this.particleSystems[particleIndex];
  27634. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27635. continue;
  27636. }
  27637. var emitter = particleSystem.emitter;
  27638. if (!emitter.position || emitter.isEnabled()) {
  27639. this._activeParticleSystems.push(particleSystem);
  27640. particleSystem.animate();
  27641. this._renderingManager.dispatchParticles(particleSystem);
  27642. }
  27643. }
  27644. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27645. }
  27646. };
  27647. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27648. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27649. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27650. mesh.skeleton.prepare();
  27651. }
  27652. if (!mesh.computeBonesUsingShaders) {
  27653. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27654. }
  27655. }
  27656. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27657. var boundingInfo = sourceMesh.getBoundingInfo();
  27658. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27659. }
  27660. if (mesh !== undefined && mesh !== null
  27661. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27662. // Submeshes Octrees
  27663. var len;
  27664. var subMeshes;
  27665. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27666. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27667. len = intersections.length;
  27668. subMeshes = intersections.data;
  27669. }
  27670. else {
  27671. subMeshes = mesh.subMeshes;
  27672. len = subMeshes.length;
  27673. }
  27674. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27675. subMesh = subMeshes[subIndex];
  27676. this._evaluateSubMesh(subMesh, mesh);
  27677. }
  27678. }
  27679. };
  27680. /**
  27681. * Update the transform matrix to update from the current active camera
  27682. * @param force defines a boolean used to force the update even if cache is up to date
  27683. */
  27684. Scene.prototype.updateTransformMatrix = function (force) {
  27685. if (!this.activeCamera) {
  27686. return;
  27687. }
  27688. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27689. };
  27690. /**
  27691. * 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)
  27692. * @param alternateCamera defines the camera to use
  27693. */
  27694. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27695. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27696. };
  27697. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27698. if (camera && camera._skipRendering) {
  27699. return;
  27700. }
  27701. var engine = this._engine;
  27702. this.activeCamera = camera;
  27703. if (!this.activeCamera)
  27704. throw new Error("Active camera not set");
  27705. // Viewport
  27706. engine.setViewport(this.activeCamera.viewport);
  27707. // Camera
  27708. this.resetCachedMaterial();
  27709. this._renderId++;
  27710. this.updateTransformMatrix();
  27711. if (camera._alternateCamera) {
  27712. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27713. this._alternateRendering = true;
  27714. }
  27715. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27716. // Meshes
  27717. this._evaluateActiveMeshes();
  27718. // Software skinning
  27719. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27720. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27721. mesh.applySkeleton(mesh.skeleton);
  27722. }
  27723. // Render targets
  27724. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27725. var needsRestoreFrameBuffer = false;
  27726. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27727. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27728. }
  27729. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27730. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27731. }
  27732. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27733. this._intermediateRendering = true;
  27734. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27735. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27736. var renderTarget = this._renderTargets.data[renderIndex];
  27737. if (renderTarget._shouldRender()) {
  27738. this._renderId++;
  27739. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27740. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27741. }
  27742. }
  27743. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27744. this._intermediateRendering = false;
  27745. this._renderId++;
  27746. needsRestoreFrameBuffer = true; // Restore back buffer
  27747. }
  27748. // Render EffectLayer Texture
  27749. var stencilState = this._engine.getStencilBuffer();
  27750. var renderEffects = false;
  27751. var needStencil = false;
  27752. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27753. this._intermediateRendering = true;
  27754. for (var i = 0; i < this.effectLayers.length; i++) {
  27755. var effectLayer = this.effectLayers[i];
  27756. if (effectLayer.shouldRender() &&
  27757. (!effectLayer.camera ||
  27758. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27759. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27760. renderEffects = true;
  27761. needStencil = needStencil || effectLayer.needStencil();
  27762. var renderTarget = effectLayer._mainTexture;
  27763. if (renderTarget._shouldRender()) {
  27764. this._renderId++;
  27765. renderTarget.render(false, false);
  27766. needsRestoreFrameBuffer = true;
  27767. }
  27768. }
  27769. }
  27770. this._intermediateRendering = false;
  27771. this._renderId++;
  27772. }
  27773. if (needsRestoreFrameBuffer) {
  27774. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27775. }
  27776. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27777. // Prepare Frame
  27778. if (this.postProcessManager) {
  27779. this.postProcessManager._prepareFrame();
  27780. }
  27781. // Backgrounds
  27782. var layerIndex;
  27783. var layer;
  27784. if (this.layers.length) {
  27785. engine.setDepthBuffer(false);
  27786. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27787. layer = this.layers[layerIndex];
  27788. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27789. layer.render();
  27790. }
  27791. }
  27792. engine.setDepthBuffer(true);
  27793. }
  27794. // Activate effect Layer stencil
  27795. if (needStencil) {
  27796. this._engine.setStencilBuffer(true);
  27797. }
  27798. // Render
  27799. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27800. this._renderingManager.render(null, null, true, true);
  27801. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27802. // Restore effect Layer stencil
  27803. if (needStencil) {
  27804. this._engine.setStencilBuffer(stencilState);
  27805. }
  27806. // Bounding boxes
  27807. if (this._boundingBoxRenderer) {
  27808. this._boundingBoxRenderer.render();
  27809. }
  27810. // Lens flares
  27811. if (this.lensFlaresEnabled) {
  27812. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27813. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27814. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27815. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27816. lensFlareSystem.render();
  27817. }
  27818. }
  27819. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27820. }
  27821. // Effect Layer
  27822. if (renderEffects) {
  27823. engine.setDepthBuffer(false);
  27824. for (var i = 0; i < this.effectLayers.length; i++) {
  27825. if (this.effectLayers[i].shouldRender()) {
  27826. this.effectLayers[i].render();
  27827. }
  27828. }
  27829. engine.setDepthBuffer(true);
  27830. }
  27831. // Foregrounds
  27832. if (this.layers.length) {
  27833. engine.setDepthBuffer(false);
  27834. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27835. layer = this.layers[layerIndex];
  27836. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27837. layer.render();
  27838. }
  27839. }
  27840. engine.setDepthBuffer(true);
  27841. }
  27842. // Finalize frame
  27843. if (this.postProcessManager) {
  27844. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27845. }
  27846. // Reset some special arrays
  27847. this._renderTargets.reset();
  27848. this._alternateRendering = false;
  27849. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27850. };
  27851. Scene.prototype._processSubCameras = function (camera) {
  27852. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27853. this._renderForCamera(camera);
  27854. return;
  27855. }
  27856. // rig cameras
  27857. for (var index = 0; index < camera._rigCameras.length; index++) {
  27858. this._renderForCamera(camera._rigCameras[index], camera);
  27859. }
  27860. this.activeCamera = camera;
  27861. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27862. };
  27863. Scene.prototype._checkIntersections = function () {
  27864. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27865. var sourceMesh = this._meshesForIntersections.data[index];
  27866. if (!sourceMesh.actionManager) {
  27867. continue;
  27868. }
  27869. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27870. var action = sourceMesh.actionManager.actions[actionIndex];
  27871. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27872. var parameters = action.getTriggerParameter();
  27873. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27874. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27875. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27876. if (areIntersecting && currentIntersectionInProgress === -1) {
  27877. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27878. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27879. sourceMesh._intersectionsInProgress.push(otherMesh);
  27880. }
  27881. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27882. sourceMesh._intersectionsInProgress.push(otherMesh);
  27883. }
  27884. }
  27885. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27886. //They intersected, and now they don't.
  27887. //is this trigger an exit trigger? execute an event.
  27888. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27889. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27890. }
  27891. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27892. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27893. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27894. return otherMesh === parameterMesh;
  27895. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27896. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27897. }
  27898. }
  27899. }
  27900. }
  27901. }
  27902. };
  27903. /**
  27904. * Render the scene
  27905. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  27906. */
  27907. Scene.prototype.render = function (updateCameras) {
  27908. if (updateCameras === void 0) { updateCameras = true; }
  27909. if (this.isDisposed) {
  27910. return;
  27911. }
  27912. this._activeParticles.fetchNewFrame();
  27913. this._totalVertices.fetchNewFrame();
  27914. this._activeIndices.fetchNewFrame();
  27915. this._activeBones.fetchNewFrame();
  27916. this._meshesForIntersections.reset();
  27917. this.resetCachedMaterial();
  27918. this.onBeforeAnimationsObservable.notifyObservers(this);
  27919. // Actions
  27920. if (this.actionManager) {
  27921. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27922. }
  27923. //Simplification Queue
  27924. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27925. this.simplificationQueue.executeNext();
  27926. }
  27927. if (this._engine.isDeterministicLockStep()) {
  27928. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27929. var defaultFPS = (60.0 / 1000.0);
  27930. var defaultFrameTime = 1000 / 60; // frame time in MS
  27931. if (this._physicsEngine) {
  27932. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27933. }
  27934. var stepsTaken = 0;
  27935. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27936. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27937. internalSteps = Math.min(internalSteps, maxSubSteps);
  27938. do {
  27939. this.onBeforeStepObservable.notifyObservers(this);
  27940. // Animations
  27941. this._animationRatio = defaultFrameTime * defaultFPS;
  27942. this._animate();
  27943. this.onAfterAnimationsObservable.notifyObservers(this);
  27944. // Physics
  27945. if (this._physicsEngine) {
  27946. this.onBeforePhysicsObservable.notifyObservers(this);
  27947. this._physicsEngine._step(defaultFrameTime / 1000);
  27948. this.onAfterPhysicsObservable.notifyObservers(this);
  27949. }
  27950. this.onAfterStepObservable.notifyObservers(this);
  27951. this._currentStepId++;
  27952. stepsTaken++;
  27953. deltaTime -= defaultFrameTime;
  27954. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27955. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27956. }
  27957. else {
  27958. // Animations
  27959. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27960. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27961. this._animate();
  27962. this.onAfterAnimationsObservable.notifyObservers(this);
  27963. // Physics
  27964. if (this._physicsEngine) {
  27965. this.onBeforePhysicsObservable.notifyObservers(this);
  27966. this._physicsEngine._step(deltaTime / 1000.0);
  27967. this.onAfterPhysicsObservable.notifyObservers(this);
  27968. }
  27969. }
  27970. // update gamepad manager
  27971. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27972. this._gamepadManager._checkGamepadsStatus();
  27973. }
  27974. // Update Cameras
  27975. if (updateCameras) {
  27976. if (this.activeCameras.length > 0) {
  27977. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27978. var camera = this.activeCameras[cameraIndex];
  27979. camera.update();
  27980. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27981. // rig cameras
  27982. for (var index = 0; index < camera._rigCameras.length; index++) {
  27983. camera._rigCameras[index].update();
  27984. }
  27985. }
  27986. }
  27987. }
  27988. else if (this.activeCamera) {
  27989. this.activeCamera.update();
  27990. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27991. // rig cameras
  27992. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27993. this.activeCamera._rigCameras[index].update();
  27994. }
  27995. }
  27996. }
  27997. }
  27998. // Before render
  27999. this.onBeforeRenderObservable.notifyObservers(this);
  28000. // Customs render targets
  28001. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28002. var engine = this.getEngine();
  28003. var currentActiveCamera = this.activeCamera;
  28004. if (this.renderTargetsEnabled) {
  28005. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28006. this._intermediateRendering = true;
  28007. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28008. var renderTarget = this.customRenderTargets[customIndex];
  28009. if (renderTarget._shouldRender()) {
  28010. this._renderId++;
  28011. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28012. if (!this.activeCamera)
  28013. throw new Error("Active camera not set");
  28014. // Viewport
  28015. engine.setViewport(this.activeCamera.viewport);
  28016. // Camera
  28017. this.updateTransformMatrix();
  28018. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28019. }
  28020. }
  28021. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28022. this._intermediateRendering = false;
  28023. this._renderId++;
  28024. }
  28025. // Restore back buffer
  28026. if (this.customRenderTargets.length > 0) {
  28027. engine.restoreDefaultFramebuffer();
  28028. }
  28029. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28030. this.activeCamera = currentActiveCamera;
  28031. // Procedural textures
  28032. if (this.proceduralTexturesEnabled) {
  28033. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28034. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28035. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28036. if (proceduralTexture._shouldRender()) {
  28037. proceduralTexture.render();
  28038. }
  28039. }
  28040. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28041. }
  28042. // Clear
  28043. if (this.autoClearDepthAndStencil || this.autoClear) {
  28044. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28045. }
  28046. // Shadows
  28047. if (this.shadowsEnabled) {
  28048. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28049. var light = this.lights[lightIndex];
  28050. var shadowGenerator = light.getShadowGenerator();
  28051. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28052. var shadowMap = (shadowGenerator.getShadowMap());
  28053. if (this.textures.indexOf(shadowMap) !== -1) {
  28054. this._renderTargets.push(shadowMap);
  28055. }
  28056. }
  28057. }
  28058. }
  28059. // Depth renderer
  28060. for (var key in this._depthRenderer) {
  28061. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28062. }
  28063. // Geometry renderer
  28064. if (this._geometryBufferRenderer) {
  28065. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28066. }
  28067. // RenderPipeline
  28068. if (this._postProcessRenderPipelineManager) {
  28069. this._postProcessRenderPipelineManager.update();
  28070. }
  28071. // Multi-cameras?
  28072. if (this.activeCameras.length > 0) {
  28073. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28074. if (cameraIndex > 0) {
  28075. this._engine.clear(null, false, true, true);
  28076. }
  28077. this._processSubCameras(this.activeCameras[cameraIndex]);
  28078. }
  28079. }
  28080. else {
  28081. if (!this.activeCamera) {
  28082. throw new Error("No camera defined");
  28083. }
  28084. this._processSubCameras(this.activeCamera);
  28085. }
  28086. // Intersection checks
  28087. this._checkIntersections();
  28088. // Update the audio listener attached to the camera
  28089. if (BABYLON.AudioEngine) {
  28090. this._updateAudioParameters();
  28091. }
  28092. // After render
  28093. if (this.afterRender) {
  28094. this.afterRender();
  28095. }
  28096. this.onAfterRenderObservable.notifyObservers(this);
  28097. // Cleaning
  28098. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28099. var data = this._toBeDisposed.data[index];
  28100. if (data) {
  28101. data.dispose();
  28102. }
  28103. this._toBeDisposed[index] = null;
  28104. }
  28105. this._toBeDisposed.reset();
  28106. if (this.dumpNextRenderTargets) {
  28107. this.dumpNextRenderTargets = false;
  28108. }
  28109. this._activeBones.addCount(0, true);
  28110. this._activeIndices.addCount(0, true);
  28111. this._activeParticles.addCount(0, true);
  28112. };
  28113. Scene.prototype._updateAudioParameters = function () {
  28114. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28115. return;
  28116. }
  28117. var listeningCamera;
  28118. var audioEngine = BABYLON.Engine.audioEngine;
  28119. if (this.activeCameras.length > 0) {
  28120. listeningCamera = this.activeCameras[0];
  28121. }
  28122. else {
  28123. listeningCamera = this.activeCamera;
  28124. }
  28125. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28126. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28127. // for VR cameras
  28128. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28129. listeningCamera = listeningCamera.rigCameras[0];
  28130. }
  28131. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28132. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28133. cameraDirection.normalize();
  28134. // To avoid some errors on GearVR
  28135. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28136. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28137. }
  28138. var i;
  28139. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28140. var sound = this.mainSoundTrack.soundCollection[i];
  28141. if (sound.useCustomAttenuation) {
  28142. sound.updateDistanceFromListener();
  28143. }
  28144. }
  28145. for (i = 0; i < this.soundTracks.length; i++) {
  28146. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28147. sound = this.soundTracks[i].soundCollection[j];
  28148. if (sound.useCustomAttenuation) {
  28149. sound.updateDistanceFromListener();
  28150. }
  28151. }
  28152. }
  28153. }
  28154. };
  28155. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28156. // Audio
  28157. /**
  28158. * Gets or sets if audio support is enabled
  28159. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28160. */
  28161. get: function () {
  28162. return this._audioEnabled;
  28163. },
  28164. set: function (value) {
  28165. this._audioEnabled = value;
  28166. if (BABYLON.AudioEngine) {
  28167. if (this._audioEnabled) {
  28168. this._enableAudio();
  28169. }
  28170. else {
  28171. this._disableAudio();
  28172. }
  28173. }
  28174. },
  28175. enumerable: true,
  28176. configurable: true
  28177. });
  28178. Scene.prototype._disableAudio = function () {
  28179. var i;
  28180. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28181. this.mainSoundTrack.soundCollection[i].pause();
  28182. }
  28183. for (i = 0; i < this.soundTracks.length; i++) {
  28184. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28185. this.soundTracks[i].soundCollection[j].pause();
  28186. }
  28187. }
  28188. };
  28189. Scene.prototype._enableAudio = function () {
  28190. var i;
  28191. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28192. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28193. this.mainSoundTrack.soundCollection[i].play();
  28194. }
  28195. }
  28196. for (i = 0; i < this.soundTracks.length; i++) {
  28197. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28198. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28199. this.soundTracks[i].soundCollection[j].play();
  28200. }
  28201. }
  28202. }
  28203. };
  28204. Object.defineProperty(Scene.prototype, "headphone", {
  28205. /**
  28206. * Gets or sets if audio will be output to headphones
  28207. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28208. */
  28209. get: function () {
  28210. return this._headphone;
  28211. },
  28212. set: function (value) {
  28213. this._headphone = value;
  28214. if (BABYLON.AudioEngine) {
  28215. if (this._headphone) {
  28216. this._switchAudioModeForHeadphones();
  28217. }
  28218. else {
  28219. this._switchAudioModeForNormalSpeakers();
  28220. }
  28221. }
  28222. },
  28223. enumerable: true,
  28224. configurable: true
  28225. });
  28226. Scene.prototype._switchAudioModeForHeadphones = function () {
  28227. this.mainSoundTrack.switchPanningModelToHRTF();
  28228. for (var i = 0; i < this.soundTracks.length; i++) {
  28229. this.soundTracks[i].switchPanningModelToHRTF();
  28230. }
  28231. };
  28232. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28233. this.mainSoundTrack.switchPanningModelToEqualPower();
  28234. for (var i = 0; i < this.soundTracks.length; i++) {
  28235. this.soundTracks[i].switchPanningModelToEqualPower();
  28236. }
  28237. };
  28238. /**
  28239. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28240. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28241. * @returns the created depth renderer
  28242. */
  28243. Scene.prototype.enableDepthRenderer = function (camera) {
  28244. camera = camera || this.activeCamera;
  28245. if (!camera) {
  28246. throw "No camera available to enable depth renderer";
  28247. }
  28248. if (!this._depthRenderer[camera.id]) {
  28249. var textureType = 0;
  28250. if (this._engine.getCaps().textureHalfFloatRender) {
  28251. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28252. }
  28253. else if (this._engine.getCaps().textureFloatRender) {
  28254. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28255. }
  28256. else {
  28257. throw "Depth renderer does not support int texture type";
  28258. }
  28259. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28260. }
  28261. return this._depthRenderer[camera.id];
  28262. };
  28263. /**
  28264. * Disables a depth renderer for a given camera
  28265. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28266. */
  28267. Scene.prototype.disableDepthRenderer = function (camera) {
  28268. camera = camera || this.activeCamera;
  28269. if (!camera || !this._depthRenderer[camera.id]) {
  28270. return;
  28271. }
  28272. this._depthRenderer[camera.id].dispose();
  28273. delete this._depthRenderer[camera.id];
  28274. };
  28275. /**
  28276. * Enables a GeometryBufferRender and associates it with the scene
  28277. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28278. * @returns the GeometryBufferRenderer
  28279. */
  28280. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28281. if (ratio === void 0) { ratio = 1; }
  28282. if (this._geometryBufferRenderer) {
  28283. return this._geometryBufferRenderer;
  28284. }
  28285. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28286. if (!this._geometryBufferRenderer.isSupported) {
  28287. this._geometryBufferRenderer = null;
  28288. }
  28289. return this._geometryBufferRenderer;
  28290. };
  28291. /**
  28292. * Disables the GeometryBufferRender associated with the scene
  28293. */
  28294. Scene.prototype.disableGeometryBufferRenderer = function () {
  28295. if (!this._geometryBufferRenderer) {
  28296. return;
  28297. }
  28298. this._geometryBufferRenderer.dispose();
  28299. this._geometryBufferRenderer = null;
  28300. };
  28301. /**
  28302. * Freeze all materials
  28303. * A frozen material will not be updatable but should be faster to render
  28304. */
  28305. Scene.prototype.freezeMaterials = function () {
  28306. for (var i = 0; i < this.materials.length; i++) {
  28307. this.materials[i].freeze();
  28308. }
  28309. };
  28310. /**
  28311. * Unfreeze all materials
  28312. * A frozen material will not be updatable but should be faster to render
  28313. */
  28314. Scene.prototype.unfreezeMaterials = function () {
  28315. for (var i = 0; i < this.materials.length; i++) {
  28316. this.materials[i].unfreeze();
  28317. }
  28318. };
  28319. /**
  28320. * Releases all held ressources
  28321. */
  28322. Scene.prototype.dispose = function () {
  28323. this.beforeRender = null;
  28324. this.afterRender = null;
  28325. this.skeletons = [];
  28326. this.morphTargetManagers = [];
  28327. this.importedMeshesFiles = new Array();
  28328. this.stopAllAnimations();
  28329. this.resetCachedMaterial();
  28330. for (var key in this._depthRenderer) {
  28331. this._depthRenderer[key].dispose();
  28332. }
  28333. if (this._gamepadManager) {
  28334. this._gamepadManager.dispose();
  28335. this._gamepadManager = null;
  28336. }
  28337. // Smart arrays
  28338. if (this.activeCamera) {
  28339. this.activeCamera._activeMeshes.dispose();
  28340. this.activeCamera = null;
  28341. }
  28342. this._activeMeshes.dispose();
  28343. this._renderingManager.dispose();
  28344. this._processedMaterials.dispose();
  28345. this._activeParticleSystems.dispose();
  28346. this._activeSkeletons.dispose();
  28347. this._softwareSkinnedMeshes.dispose();
  28348. this._renderTargets.dispose();
  28349. this._registeredForLateAnimationBindings.dispose();
  28350. if (this._boundingBoxRenderer) {
  28351. this._boundingBoxRenderer.dispose();
  28352. }
  28353. this._meshesForIntersections.dispose();
  28354. this._toBeDisposed.dispose();
  28355. // Abort active requests
  28356. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28357. var request = _a[_i];
  28358. request.abort();
  28359. }
  28360. // Debug layer
  28361. if (this._debugLayer) {
  28362. this._debugLayer.hide();
  28363. }
  28364. // Events
  28365. this.onDisposeObservable.notifyObservers(this);
  28366. this.onDisposeObservable.clear();
  28367. this.onBeforeRenderObservable.clear();
  28368. this.onAfterRenderObservable.clear();
  28369. this.onBeforeRenderTargetsRenderObservable.clear();
  28370. this.onAfterRenderTargetsRenderObservable.clear();
  28371. this.onAfterStepObservable.clear();
  28372. this.onBeforeStepObservable.clear();
  28373. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28374. this.onAfterActiveMeshesEvaluationObservable.clear();
  28375. this.onBeforeParticlesRenderingObservable.clear();
  28376. this.onAfterParticlesRenderingObservable.clear();
  28377. this.onBeforeSpritesRenderingObservable.clear();
  28378. this.onAfterSpritesRenderingObservable.clear();
  28379. this.onBeforeDrawPhaseObservable.clear();
  28380. this.onAfterDrawPhaseObservable.clear();
  28381. this.onBeforePhysicsObservable.clear();
  28382. this.onAfterPhysicsObservable.clear();
  28383. this.onBeforeAnimationsObservable.clear();
  28384. this.onAfterAnimationsObservable.clear();
  28385. this.onDataLoadedObservable.clear();
  28386. this.detachControl();
  28387. // Release sounds & sounds tracks
  28388. if (BABYLON.AudioEngine) {
  28389. this.disposeSounds();
  28390. }
  28391. // VR Helper
  28392. if (this.VRHelper) {
  28393. this.VRHelper.dispose();
  28394. }
  28395. // Detach cameras
  28396. var canvas = this._engine.getRenderingCanvas();
  28397. if (canvas) {
  28398. var index;
  28399. for (index = 0; index < this.cameras.length; index++) {
  28400. this.cameras[index].detachControl(canvas);
  28401. }
  28402. }
  28403. // Release animation groups
  28404. while (this.animationGroups.length) {
  28405. this.animationGroups[0].dispose();
  28406. }
  28407. // Release lights
  28408. while (this.lights.length) {
  28409. this.lights[0].dispose();
  28410. }
  28411. // Release meshes
  28412. while (this.meshes.length) {
  28413. this.meshes[0].dispose(true);
  28414. }
  28415. while (this.transformNodes.length) {
  28416. this.removeTransformNode(this.transformNodes[0]);
  28417. }
  28418. // Release cameras
  28419. while (this.cameras.length) {
  28420. this.cameras[0].dispose();
  28421. }
  28422. // Release materials
  28423. if (this.defaultMaterial) {
  28424. this.defaultMaterial.dispose();
  28425. }
  28426. while (this.multiMaterials.length) {
  28427. this.multiMaterials[0].dispose();
  28428. }
  28429. while (this.materials.length) {
  28430. this.materials[0].dispose();
  28431. }
  28432. // Release particles
  28433. while (this.particleSystems.length) {
  28434. this.particleSystems[0].dispose();
  28435. }
  28436. // Release sprites
  28437. while (this.spriteManagers.length) {
  28438. this.spriteManagers[0].dispose();
  28439. }
  28440. // Release postProcesses
  28441. while (this.postProcesses.length) {
  28442. this.postProcesses[0].dispose();
  28443. }
  28444. // Release layers
  28445. while (this.layers.length) {
  28446. this.layers[0].dispose();
  28447. }
  28448. while (this.effectLayers.length) {
  28449. this.effectLayers[0].dispose();
  28450. }
  28451. // Release textures
  28452. while (this.textures.length) {
  28453. this.textures[0].dispose();
  28454. }
  28455. // Release UBO
  28456. this._sceneUbo.dispose();
  28457. if (this._alternateSceneUbo) {
  28458. this._alternateSceneUbo.dispose();
  28459. }
  28460. // Post-processes
  28461. this.postProcessManager.dispose();
  28462. if (this._postProcessRenderPipelineManager) {
  28463. this._postProcessRenderPipelineManager.dispose();
  28464. }
  28465. // Physics
  28466. if (this._physicsEngine) {
  28467. this.disablePhysicsEngine();
  28468. }
  28469. // Remove from engine
  28470. index = this._engine.scenes.indexOf(this);
  28471. if (index > -1) {
  28472. this._engine.scenes.splice(index, 1);
  28473. }
  28474. this._engine.wipeCaches(true);
  28475. this._isDisposed = true;
  28476. };
  28477. Object.defineProperty(Scene.prototype, "isDisposed", {
  28478. /**
  28479. * Gets if the scene is already disposed
  28480. */
  28481. get: function () {
  28482. return this._isDisposed;
  28483. },
  28484. enumerable: true,
  28485. configurable: true
  28486. });
  28487. /**
  28488. * Releases sounds & soundtracks
  28489. */
  28490. Scene.prototype.disposeSounds = function () {
  28491. if (!this._mainSoundTrack) {
  28492. return;
  28493. }
  28494. this.mainSoundTrack.dispose();
  28495. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28496. this.soundTracks[scIndex].dispose();
  28497. }
  28498. };
  28499. /**
  28500. * Call this function to reduce memory footprint of the scene.
  28501. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28502. */
  28503. Scene.prototype.clearCachedVertexData = function () {
  28504. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28505. var mesh = this.meshes[meshIndex];
  28506. var geometry = mesh.geometry;
  28507. if (geometry) {
  28508. geometry._indices = [];
  28509. for (var vbName in geometry._vertexBuffers) {
  28510. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28511. continue;
  28512. }
  28513. geometry._vertexBuffers[vbName]._buffer._data = null;
  28514. }
  28515. }
  28516. }
  28517. };
  28518. /**
  28519. * This function will remove the local cached buffer data from texture.
  28520. * It will save memory but will prevent the texture from being rebuilt
  28521. */
  28522. Scene.prototype.cleanCachedTextureBuffer = function () {
  28523. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28524. var baseTexture = _a[_i];
  28525. var buffer = baseTexture._buffer;
  28526. if (buffer) {
  28527. baseTexture._buffer = null;
  28528. }
  28529. }
  28530. };
  28531. // Octrees
  28532. /**
  28533. * Get the world extend vectors with an optional filter
  28534. *
  28535. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28536. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28537. */
  28538. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28539. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28540. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28541. filterPredicate = filterPredicate || (function () { return true; });
  28542. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28543. mesh.computeWorldMatrix(true);
  28544. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28545. return;
  28546. }
  28547. var boundingInfo = mesh.getBoundingInfo();
  28548. var minBox = boundingInfo.boundingBox.minimumWorld;
  28549. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28550. BABYLON.Tools.CheckExtends(minBox, min, max);
  28551. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28552. });
  28553. return {
  28554. min: min,
  28555. max: max
  28556. };
  28557. };
  28558. /**
  28559. * Creates or updates the octree used to boost selection (picking)
  28560. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28561. * @param maxCapacity defines the maximum capacity per leaf
  28562. * @param maxDepth defines the maximum depth of the octree
  28563. * @returns an octree of AbstractMesh
  28564. */
  28565. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28566. if (maxCapacity === void 0) { maxCapacity = 64; }
  28567. if (maxDepth === void 0) { maxDepth = 2; }
  28568. if (!this._selectionOctree) {
  28569. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28570. }
  28571. var worldExtends = this.getWorldExtends();
  28572. // Update octree
  28573. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28574. return this._selectionOctree;
  28575. };
  28576. // Picking
  28577. /**
  28578. * Creates a ray that can be used to pick in the scene
  28579. * @param x defines the x coordinate of the origin (on-screen)
  28580. * @param y defines the y coordinate of the origin (on-screen)
  28581. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28582. * @param camera defines the camera to use for the picking
  28583. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28584. * @returns a Ray
  28585. */
  28586. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28587. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28588. var result = BABYLON.Ray.Zero();
  28589. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28590. return result;
  28591. };
  28592. /**
  28593. * Creates a ray that can be used to pick in the scene
  28594. * @param x defines the x coordinate of the origin (on-screen)
  28595. * @param y defines the y coordinate of the origin (on-screen)
  28596. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28597. * @param result defines the ray where to store the picking ray
  28598. * @param camera defines the camera to use for the picking
  28599. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28600. * @returns the current scene
  28601. */
  28602. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28603. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28604. var engine = this._engine;
  28605. if (!camera) {
  28606. if (!this.activeCamera)
  28607. throw new Error("Active camera not set");
  28608. camera = this.activeCamera;
  28609. }
  28610. var cameraViewport = camera.viewport;
  28611. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28612. // Moving coordinates to local viewport world
  28613. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28614. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28615. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28616. return this;
  28617. };
  28618. /**
  28619. * Creates a ray that can be used to pick in the scene
  28620. * @param x defines the x coordinate of the origin (on-screen)
  28621. * @param y defines the y coordinate of the origin (on-screen)
  28622. * @param camera defines the camera to use for the picking
  28623. * @returns a Ray
  28624. */
  28625. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28626. var result = BABYLON.Ray.Zero();
  28627. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28628. return result;
  28629. };
  28630. /**
  28631. * Creates a ray that can be used to pick in the scene
  28632. * @param x defines the x coordinate of the origin (on-screen)
  28633. * @param y defines the y coordinate of the origin (on-screen)
  28634. * @param result defines the ray where to store the picking ray
  28635. * @param camera defines the camera to use for the picking
  28636. * @returns the current scene
  28637. */
  28638. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28639. if (!BABYLON.PickingInfo) {
  28640. return this;
  28641. }
  28642. var engine = this._engine;
  28643. if (!camera) {
  28644. if (!this.activeCamera)
  28645. throw new Error("Active camera not set");
  28646. camera = this.activeCamera;
  28647. }
  28648. var cameraViewport = camera.viewport;
  28649. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28650. var identity = BABYLON.Matrix.Identity();
  28651. // Moving coordinates to local viewport world
  28652. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28653. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28654. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28655. return this;
  28656. };
  28657. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28658. if (!BABYLON.PickingInfo) {
  28659. return null;
  28660. }
  28661. var pickingInfo = null;
  28662. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28663. var mesh = this.meshes[meshIndex];
  28664. if (predicate) {
  28665. if (!predicate(mesh)) {
  28666. continue;
  28667. }
  28668. }
  28669. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28670. continue;
  28671. }
  28672. var world = mesh.getWorldMatrix();
  28673. var ray = rayFunction(world);
  28674. var result = mesh.intersects(ray, fastCheck);
  28675. if (!result || !result.hit)
  28676. continue;
  28677. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28678. continue;
  28679. pickingInfo = result;
  28680. if (fastCheck) {
  28681. break;
  28682. }
  28683. }
  28684. return pickingInfo || new BABYLON.PickingInfo();
  28685. };
  28686. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28687. if (!BABYLON.PickingInfo) {
  28688. return null;
  28689. }
  28690. var pickingInfos = new Array();
  28691. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28692. var mesh = this.meshes[meshIndex];
  28693. if (predicate) {
  28694. if (!predicate(mesh)) {
  28695. continue;
  28696. }
  28697. }
  28698. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28699. continue;
  28700. }
  28701. var world = mesh.getWorldMatrix();
  28702. var ray = rayFunction(world);
  28703. var result = mesh.intersects(ray, false);
  28704. if (!result || !result.hit)
  28705. continue;
  28706. pickingInfos.push(result);
  28707. }
  28708. return pickingInfos;
  28709. };
  28710. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28711. if (!BABYLON.PickingInfo) {
  28712. return null;
  28713. }
  28714. var pickingInfo = null;
  28715. if (!camera) {
  28716. if (!this.activeCamera) {
  28717. return null;
  28718. }
  28719. camera = this.activeCamera;
  28720. }
  28721. if (this.spriteManagers.length > 0) {
  28722. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28723. var spriteManager = this.spriteManagers[spriteIndex];
  28724. if (!spriteManager.isPickable) {
  28725. continue;
  28726. }
  28727. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28728. if (!result || !result.hit)
  28729. continue;
  28730. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28731. continue;
  28732. pickingInfo = result;
  28733. if (fastCheck) {
  28734. break;
  28735. }
  28736. }
  28737. }
  28738. return pickingInfo || new BABYLON.PickingInfo();
  28739. };
  28740. /** Launch a ray to try to pick a mesh in the scene
  28741. * @param x position on screen
  28742. * @param y position on screen
  28743. * @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
  28744. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28745. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28746. * @returns a PickingInfo
  28747. */
  28748. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28749. var _this = this;
  28750. if (!BABYLON.PickingInfo) {
  28751. return null;
  28752. }
  28753. var result = this._internalPick(function (world) {
  28754. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28755. return _this._tempPickingRay;
  28756. }, predicate, fastCheck);
  28757. if (result) {
  28758. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28759. }
  28760. return result;
  28761. };
  28762. /** Launch a ray to try to pick a sprite in the scene
  28763. * @param x position on screen
  28764. * @param y position on screen
  28765. * @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
  28766. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28767. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28768. * @returns a PickingInfo
  28769. */
  28770. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28771. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28772. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28773. };
  28774. /** Use the given ray to pick a mesh in the scene
  28775. * @param ray The ray to use to pick meshes
  28776. * @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
  28777. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28778. * @returns a PickingInfo
  28779. */
  28780. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28781. var _this = this;
  28782. var result = this._internalPick(function (world) {
  28783. if (!_this._pickWithRayInverseMatrix) {
  28784. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28785. }
  28786. world.invertToRef(_this._pickWithRayInverseMatrix);
  28787. if (!_this._cachedRayForTransform) {
  28788. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28789. }
  28790. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28791. return _this._cachedRayForTransform;
  28792. }, predicate, fastCheck);
  28793. if (result) {
  28794. result.ray = ray;
  28795. }
  28796. return result;
  28797. };
  28798. /**
  28799. * Launch a ray to try to pick a mesh in the scene
  28800. * @param x X position on screen
  28801. * @param y Y position on screen
  28802. * @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
  28803. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28804. * @returns an array of PickingInfo
  28805. */
  28806. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28807. var _this = this;
  28808. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28809. };
  28810. /**
  28811. * Launch a ray to try to pick a mesh in the scene
  28812. * @param ray Ray to use
  28813. * @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
  28814. * @returns an array of PickingInfo
  28815. */
  28816. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28817. var _this = this;
  28818. return this._internalMultiPick(function (world) {
  28819. if (!_this._pickWithRayInverseMatrix) {
  28820. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28821. }
  28822. world.invertToRef(_this._pickWithRayInverseMatrix);
  28823. if (!_this._cachedRayForTransform) {
  28824. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28825. }
  28826. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28827. return _this._cachedRayForTransform;
  28828. }, predicate);
  28829. };
  28830. /**
  28831. * Force the value of meshUnderPointer
  28832. * @param mesh defines the mesh to use
  28833. */
  28834. Scene.prototype.setPointerOverMesh = function (mesh) {
  28835. if (this._pointerOverMesh === mesh) {
  28836. return;
  28837. }
  28838. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28839. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28840. }
  28841. this._pointerOverMesh = mesh;
  28842. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28843. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28844. }
  28845. };
  28846. /**
  28847. * Gets the mesh under the pointer
  28848. * @returns a Mesh or null if no mesh is under the pointer
  28849. */
  28850. Scene.prototype.getPointerOverMesh = function () {
  28851. return this._pointerOverMesh;
  28852. };
  28853. /**
  28854. * Force the sprite under the pointer
  28855. * @param sprite defines the sprite to use
  28856. */
  28857. Scene.prototype.setPointerOverSprite = function (sprite) {
  28858. if (this._pointerOverSprite === sprite) {
  28859. return;
  28860. }
  28861. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28862. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28863. }
  28864. this._pointerOverSprite = sprite;
  28865. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28866. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28867. }
  28868. };
  28869. /**
  28870. * Gets the sprite under the pointer
  28871. * @returns a Sprite or null if no sprite is under the pointer
  28872. */
  28873. Scene.prototype.getPointerOverSprite = function () {
  28874. return this._pointerOverSprite;
  28875. };
  28876. // Physics
  28877. /**
  28878. * Gets the current physics engine
  28879. * @returns a PhysicsEngine or null if none attached
  28880. */
  28881. Scene.prototype.getPhysicsEngine = function () {
  28882. return this._physicsEngine;
  28883. };
  28884. /**
  28885. * Enables physics to the current scene
  28886. * @param gravity defines the scene's gravity for the physics engine
  28887. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28888. * @return a boolean indicating if the physics engine was initialized
  28889. */
  28890. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28891. if (gravity === void 0) { gravity = null; }
  28892. if (this._physicsEngine) {
  28893. return true;
  28894. }
  28895. try {
  28896. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28897. return true;
  28898. }
  28899. catch (e) {
  28900. BABYLON.Tools.Error(e.message);
  28901. return false;
  28902. }
  28903. };
  28904. /**
  28905. * Disables and disposes the physics engine associated with the scene
  28906. */
  28907. Scene.prototype.disablePhysicsEngine = function () {
  28908. if (!this._physicsEngine) {
  28909. return;
  28910. }
  28911. this._physicsEngine.dispose();
  28912. this._physicsEngine = null;
  28913. };
  28914. /**
  28915. * Gets a boolean indicating if there is an active physics engine
  28916. * @returns a boolean indicating if there is an active physics engine
  28917. */
  28918. Scene.prototype.isPhysicsEnabled = function () {
  28919. return this._physicsEngine !== undefined;
  28920. };
  28921. /**
  28922. * Deletes a physics compound impostor
  28923. * @param compound defines the compound to delete
  28924. */
  28925. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28926. var mesh = compound.parts[0].mesh;
  28927. if (mesh.physicsImpostor) {
  28928. mesh.physicsImpostor.dispose( /*true*/);
  28929. mesh.physicsImpostor = null;
  28930. }
  28931. };
  28932. // Misc.
  28933. /** @hidden */
  28934. Scene.prototype._rebuildGeometries = function () {
  28935. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28936. var geometry = _a[_i];
  28937. geometry._rebuild();
  28938. }
  28939. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28940. var mesh = _c[_b];
  28941. mesh._rebuild();
  28942. }
  28943. if (this.postProcessManager) {
  28944. this.postProcessManager._rebuild();
  28945. }
  28946. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28947. var layer = _e[_d];
  28948. layer._rebuild();
  28949. }
  28950. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28951. var effectLayer = _g[_f];
  28952. effectLayer._rebuild();
  28953. }
  28954. if (this._boundingBoxRenderer) {
  28955. this._boundingBoxRenderer._rebuild();
  28956. }
  28957. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28958. var system = _j[_h];
  28959. system.rebuild();
  28960. }
  28961. if (this._postProcessRenderPipelineManager) {
  28962. this._postProcessRenderPipelineManager._rebuild();
  28963. }
  28964. };
  28965. /** @hidden */
  28966. Scene.prototype._rebuildTextures = function () {
  28967. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28968. var texture = _a[_i];
  28969. texture._rebuild();
  28970. }
  28971. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28972. };
  28973. /**
  28974. * Creates a default light for the scene.
  28975. * @param replace Whether to replace the existing lights in the scene.
  28976. */
  28977. Scene.prototype.createDefaultLight = function (replace) {
  28978. if (replace === void 0) { replace = false; }
  28979. // Dispose existing light in replace mode.
  28980. if (replace) {
  28981. if (this.lights) {
  28982. for (var i = 0; i < this.lights.length; i++) {
  28983. this.lights[i].dispose();
  28984. }
  28985. }
  28986. }
  28987. // Light
  28988. if (this.lights.length === 0) {
  28989. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28990. }
  28991. };
  28992. /**
  28993. * Creates a default camera for the scene.
  28994. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28995. * @param replace Whether to replace the existing active camera in the scene.
  28996. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28997. */
  28998. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28999. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29000. if (replace === void 0) { replace = false; }
  29001. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29002. // Dispose existing camera in replace mode.
  29003. if (replace) {
  29004. if (this.activeCamera) {
  29005. this.activeCamera.dispose();
  29006. this.activeCamera = null;
  29007. }
  29008. }
  29009. // Camera
  29010. if (!this.activeCamera) {
  29011. var worldExtends = this.getWorldExtends();
  29012. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29013. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29014. var camera;
  29015. var radius = worldSize.length() * 1.5;
  29016. // empty scene scenario!
  29017. if (!isFinite(radius)) {
  29018. radius = 1;
  29019. worldCenter.copyFromFloats(0, 0, 0);
  29020. }
  29021. if (createArcRotateCamera) {
  29022. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29023. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29024. arcRotateCamera.wheelPrecision = 100 / radius;
  29025. camera = arcRotateCamera;
  29026. }
  29027. else {
  29028. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29029. freeCamera.setTarget(worldCenter);
  29030. camera = freeCamera;
  29031. }
  29032. camera.minZ = radius * 0.01;
  29033. camera.maxZ = radius * 1000;
  29034. camera.speed = radius * 0.2;
  29035. this.activeCamera = camera;
  29036. var canvas = this.getEngine().getRenderingCanvas();
  29037. if (attachCameraControls && canvas) {
  29038. camera.attachControl(canvas);
  29039. }
  29040. }
  29041. };
  29042. /**
  29043. * Creates a default camera and a default light
  29044. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29045. * @param replace defines if the camera and/or light will replace the existing ones
  29046. * @param attachCameraControls defines if attachControl will be called on the new camera
  29047. */
  29048. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29049. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29050. if (replace === void 0) { replace = false; }
  29051. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29052. this.createDefaultLight(replace);
  29053. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29054. };
  29055. /**
  29056. * Creates a new sky box
  29057. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29058. * @param environmentTexture defines the texture to use as environment texture
  29059. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29060. * @param scale defines the overall scale of the skybox
  29061. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29062. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29063. * @returns a new mesh holding the sky box
  29064. */
  29065. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29066. if (pbr === void 0) { pbr = false; }
  29067. if (scale === void 0) { scale = 1000; }
  29068. if (blur === void 0) { blur = 0; }
  29069. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29070. if (!environmentTexture) {
  29071. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29072. return null;
  29073. }
  29074. if (setGlobalEnvTexture) {
  29075. if (environmentTexture) {
  29076. this.environmentTexture = environmentTexture;
  29077. }
  29078. }
  29079. // Skybox
  29080. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29081. if (pbr) {
  29082. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29083. hdrSkyboxMaterial.backFaceCulling = false;
  29084. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29085. if (hdrSkyboxMaterial.reflectionTexture) {
  29086. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29087. }
  29088. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29089. hdrSkyboxMaterial.disableLighting = true;
  29090. hdrSkyboxMaterial.twoSidedLighting = true;
  29091. hdrSkybox.infiniteDistance = true;
  29092. hdrSkybox.material = hdrSkyboxMaterial;
  29093. }
  29094. else {
  29095. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29096. skyboxMaterial.backFaceCulling = false;
  29097. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29098. if (skyboxMaterial.reflectionTexture) {
  29099. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29100. }
  29101. skyboxMaterial.disableLighting = true;
  29102. hdrSkybox.infiniteDistance = true;
  29103. hdrSkybox.material = skyboxMaterial;
  29104. }
  29105. return hdrSkybox;
  29106. };
  29107. /**
  29108. * Creates a new environment
  29109. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29110. * @param options defines the options you can use to configure the environment
  29111. * @returns the new EnvironmentHelper
  29112. */
  29113. Scene.prototype.createDefaultEnvironment = function (options) {
  29114. if (BABYLON.EnvironmentHelper) {
  29115. return new BABYLON.EnvironmentHelper(options, this);
  29116. }
  29117. return null;
  29118. };
  29119. /**
  29120. * Creates a new VREXperienceHelper
  29121. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29122. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29123. * @returns a new VREXperienceHelper
  29124. */
  29125. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29126. if (webVROptions === void 0) { webVROptions = {}; }
  29127. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29128. };
  29129. // Tags
  29130. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29131. if (tagsQuery === undefined) {
  29132. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29133. return list;
  29134. }
  29135. var listByTags = [];
  29136. forEach = forEach || (function (item) { return; });
  29137. for (var i in list) {
  29138. var item = list[i];
  29139. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29140. listByTags.push(item);
  29141. forEach(item);
  29142. }
  29143. }
  29144. return listByTags;
  29145. };
  29146. /**
  29147. * Get a list of meshes by tags
  29148. * @param tagsQuery defines the tags query to use
  29149. * @param forEach defines a predicate used to filter results
  29150. * @returns an array of Mesh
  29151. */
  29152. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29153. return this._getByTags(this.meshes, tagsQuery, forEach);
  29154. };
  29155. /**
  29156. * Get a list of cameras by tags
  29157. * @param tagsQuery defines the tags query to use
  29158. * @param forEach defines a predicate used to filter results
  29159. * @returns an array of Camera
  29160. */
  29161. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29162. return this._getByTags(this.cameras, tagsQuery, forEach);
  29163. };
  29164. /**
  29165. * Get a list of lights by tags
  29166. * @param tagsQuery defines the tags query to use
  29167. * @param forEach defines a predicate used to filter results
  29168. * @returns an array of Light
  29169. */
  29170. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29171. return this._getByTags(this.lights, tagsQuery, forEach);
  29172. };
  29173. /**
  29174. * Get a list of materials by tags
  29175. * @param tagsQuery defines the tags query to use
  29176. * @param forEach defines a predicate used to filter results
  29177. * @returns an array of Material
  29178. */
  29179. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29180. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29181. };
  29182. /**
  29183. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29184. * This allowed control for front to back rendering or reversly depending of the special needs.
  29185. *
  29186. * @param renderingGroupId The rendering group id corresponding to its index
  29187. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29188. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29189. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29190. */
  29191. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29192. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29193. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29194. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29195. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29196. };
  29197. /**
  29198. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29199. *
  29200. * @param renderingGroupId The rendering group id corresponding to its index
  29201. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29202. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29203. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29204. */
  29205. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29206. if (depth === void 0) { depth = true; }
  29207. if (stencil === void 0) { stencil = true; }
  29208. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29209. };
  29210. /**
  29211. * Will flag all materials as dirty to trigger new shader compilation
  29212. * @param flag defines the flag used to specify which material part must be marked as dirty
  29213. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29214. */
  29215. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29216. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29217. var material = _a[_i];
  29218. if (predicate && !predicate(material)) {
  29219. continue;
  29220. }
  29221. material.markAsDirty(flag);
  29222. }
  29223. };
  29224. /** @hidden */
  29225. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29226. var _this = this;
  29227. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29228. this._activeRequests.push(request);
  29229. request.onCompleteObservable.add(function (request) {
  29230. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29231. });
  29232. return request;
  29233. };
  29234. /** @hidden */
  29235. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29236. var _this = this;
  29237. return new Promise(function (resolve, reject) {
  29238. _this._loadFile(url, function (data) {
  29239. resolve(data);
  29240. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29241. reject(exception);
  29242. });
  29243. });
  29244. };
  29245. // Statics
  29246. Scene._FOGMODE_NONE = 0;
  29247. Scene._FOGMODE_EXP = 1;
  29248. Scene._FOGMODE_EXP2 = 2;
  29249. Scene._FOGMODE_LINEAR = 3;
  29250. Scene._uniqueIdCounter = 0;
  29251. /**
  29252. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29253. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29254. */
  29255. Scene.MinDeltaTime = 1.0;
  29256. /**
  29257. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29258. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29259. */
  29260. Scene.MaxDeltaTime = 1000.0;
  29261. /** The distance in pixel that you have to move to prevent some events */
  29262. Scene.DragMovementThreshold = 10; // in pixels
  29263. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29264. Scene.LongPressDelay = 500; // in milliseconds
  29265. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29266. Scene.DoubleClickDelay = 300; // in milliseconds
  29267. /** If you need to check double click without raising a single click at first click, enable this flag */
  29268. Scene.ExclusiveDoubleClickMode = false;
  29269. return Scene;
  29270. }());
  29271. BABYLON.Scene = Scene;
  29272. })(BABYLON || (BABYLON = {}));
  29273. //# sourceMappingURL=babylon.scene.js.map
  29274. var BABYLON;
  29275. (function (BABYLON) {
  29276. /**
  29277. * Set of assets to keep when moving a scene into an asset container.
  29278. */
  29279. var KeepAssets = /** @class */ (function () {
  29280. function KeepAssets() {
  29281. /**
  29282. * Cameras to keep.
  29283. */
  29284. this.cameras = new Array();
  29285. /**
  29286. * Lights to keep.
  29287. */
  29288. this.lights = new Array();
  29289. /**
  29290. * Meshes to keep.
  29291. */
  29292. this.meshes = new Array();
  29293. /**
  29294. * Skeletons to keep.
  29295. */
  29296. this.skeletons = new Array();
  29297. /**
  29298. * ParticleSystems to keep.
  29299. */
  29300. this.particleSystems = new Array();
  29301. /**
  29302. * Animations to keep.
  29303. */
  29304. this.animations = new Array();
  29305. /**
  29306. * AnimationGroups to keep.
  29307. */
  29308. this.animationGroups = new Array();
  29309. /**
  29310. * MultiMaterials to keep.
  29311. */
  29312. this.multiMaterials = new Array();
  29313. /**
  29314. * Materials to keep.
  29315. */
  29316. this.materials = new Array();
  29317. /**
  29318. * MorphTargetManagers to keep.
  29319. */
  29320. this.morphTargetManagers = new Array();
  29321. /**
  29322. * Geometries to keep.
  29323. */
  29324. this.geometries = new Array();
  29325. /**
  29326. * TransformNodes to keep.
  29327. */
  29328. this.transformNodes = new Array();
  29329. /**
  29330. * LensFlareSystems to keep.
  29331. */
  29332. this.lensFlareSystems = new Array();
  29333. /**
  29334. * ShadowGenerators to keep.
  29335. */
  29336. this.shadowGenerators = new Array();
  29337. /**
  29338. * ActionManagers to keep.
  29339. */
  29340. this.actionManagers = new Array();
  29341. /**
  29342. * Sounds to keep.
  29343. */
  29344. this.sounds = new Array();
  29345. /**
  29346. * Textures to keep.
  29347. */
  29348. this.textures = new Array();
  29349. /**
  29350. * Effect layers to keep.
  29351. */
  29352. this.effectLayers = new Array();
  29353. }
  29354. return KeepAssets;
  29355. }());
  29356. BABYLON.KeepAssets = KeepAssets;
  29357. /**
  29358. * Container with a set of assets that can be added or removed from a scene.
  29359. */
  29360. var AssetContainer = /** @class */ (function () {
  29361. /**
  29362. * Instantiates an AssetContainer.
  29363. * @param scene The scene the AssetContainer belongs to.
  29364. */
  29365. function AssetContainer(scene) {
  29366. // Objects
  29367. /**
  29368. * Cameras populated in the container.
  29369. */
  29370. this.cameras = new Array();
  29371. /**
  29372. * Lights populated in the container.
  29373. */
  29374. this.lights = new Array();
  29375. /**
  29376. * Meshes populated in the container.
  29377. */
  29378. this.meshes = new Array();
  29379. /**
  29380. * Skeletons populated in the container.
  29381. */
  29382. this.skeletons = new Array();
  29383. /**
  29384. * ParticleSystems populated in the container.
  29385. */
  29386. this.particleSystems = new Array();
  29387. /**
  29388. * Animations populated in the container.
  29389. */
  29390. this.animations = new Array();
  29391. /**
  29392. * AnimationGroups populated in the container.
  29393. */
  29394. this.animationGroups = new Array();
  29395. /**
  29396. * MultiMaterials populated in the container.
  29397. */
  29398. this.multiMaterials = new Array();
  29399. /**
  29400. * Materials populated in the container.
  29401. */
  29402. this.materials = new Array();
  29403. /**
  29404. * MorphTargetManagers populated in the container.
  29405. */
  29406. this.morphTargetManagers = new Array();
  29407. /**
  29408. * Geometries populated in the container.
  29409. */
  29410. this.geometries = new Array();
  29411. /**
  29412. * TransformNodes populated in the container.
  29413. */
  29414. this.transformNodes = new Array();
  29415. /**
  29416. * LensFlareSystems populated in the container.
  29417. */
  29418. this.lensFlareSystems = new Array();
  29419. /**
  29420. * ShadowGenerators populated in the container.
  29421. */
  29422. this.shadowGenerators = new Array();
  29423. /**
  29424. * ActionManagers populated in the container.
  29425. */
  29426. this.actionManagers = new Array();
  29427. /**
  29428. * Sounds populated in the container.
  29429. */
  29430. this.sounds = new Array();
  29431. /**
  29432. * Textures populated in the container.
  29433. */
  29434. this.textures = new Array();
  29435. /**
  29436. * Effect layers populated in the container.
  29437. */
  29438. this.effectLayers = new Array();
  29439. this.scene = scene;
  29440. }
  29441. /**
  29442. * Adds all the assets from the container to the scene.
  29443. */
  29444. AssetContainer.prototype.addAllToScene = function () {
  29445. var _this = this;
  29446. this.cameras.forEach(function (o) {
  29447. _this.scene.addCamera(o);
  29448. });
  29449. this.lights.forEach(function (o) {
  29450. _this.scene.addLight(o);
  29451. });
  29452. this.meshes.forEach(function (o) {
  29453. _this.scene.addMesh(o);
  29454. });
  29455. this.skeletons.forEach(function (o) {
  29456. _this.scene.addSkeleton(o);
  29457. });
  29458. this.particleSystems.forEach(function (o) {
  29459. _this.scene.addParticleSystem(o);
  29460. });
  29461. this.animations.forEach(function (o) {
  29462. _this.scene.addAnimation(o);
  29463. });
  29464. this.animationGroups.forEach(function (o) {
  29465. _this.scene.addAnimationGroup(o);
  29466. });
  29467. this.multiMaterials.forEach(function (o) {
  29468. _this.scene.addMultiMaterial(o);
  29469. });
  29470. this.materials.forEach(function (o) {
  29471. _this.scene.addMaterial(o);
  29472. });
  29473. this.morphTargetManagers.forEach(function (o) {
  29474. _this.scene.addMorphTargetManager(o);
  29475. });
  29476. this.geometries.forEach(function (o) {
  29477. _this.scene.addGeometry(o);
  29478. });
  29479. this.transformNodes.forEach(function (o) {
  29480. _this.scene.addTransformNode(o);
  29481. });
  29482. this.lensFlareSystems.forEach(function (o) {
  29483. _this.scene.addLensFlareSystem(o);
  29484. });
  29485. this.actionManagers.forEach(function (o) {
  29486. _this.scene.addActionManager(o);
  29487. });
  29488. this.sounds.forEach(function (o) {
  29489. o.play();
  29490. o.autoplay = true;
  29491. _this.scene.mainSoundTrack.AddSound(o);
  29492. });
  29493. this.textures.forEach(function (o) {
  29494. _this.scene.addTexture(o);
  29495. });
  29496. this.effectLayers.forEach(function (o) {
  29497. _this.scene.addEffectLayer(o);
  29498. });
  29499. };
  29500. /**
  29501. * Removes all the assets in the container from the scene
  29502. */
  29503. AssetContainer.prototype.removeAllFromScene = function () {
  29504. var _this = this;
  29505. this.cameras.forEach(function (o) {
  29506. _this.scene.removeCamera(o);
  29507. });
  29508. this.lights.forEach(function (o) {
  29509. _this.scene.removeLight(o);
  29510. });
  29511. this.meshes.forEach(function (o) {
  29512. _this.scene.removeMesh(o);
  29513. });
  29514. this.skeletons.forEach(function (o) {
  29515. _this.scene.removeSkeleton(o);
  29516. });
  29517. this.particleSystems.forEach(function (o) {
  29518. _this.scene.removeParticleSystem(o);
  29519. });
  29520. this.animations.forEach(function (o) {
  29521. _this.scene.removeAnimation(o);
  29522. });
  29523. this.animationGroups.forEach(function (o) {
  29524. _this.scene.removeAnimationGroup(o);
  29525. });
  29526. this.multiMaterials.forEach(function (o) {
  29527. _this.scene.removeMultiMaterial(o);
  29528. });
  29529. this.materials.forEach(function (o) {
  29530. _this.scene.removeMaterial(o);
  29531. });
  29532. this.morphTargetManagers.forEach(function (o) {
  29533. _this.scene.removeMorphTargetManager(o);
  29534. });
  29535. this.geometries.forEach(function (o) {
  29536. _this.scene.removeGeometry(o);
  29537. });
  29538. this.transformNodes.forEach(function (o) {
  29539. _this.scene.removeTransformNode(o);
  29540. });
  29541. this.lensFlareSystems.forEach(function (o) {
  29542. _this.scene.removeLensFlareSystem(o);
  29543. });
  29544. this.actionManagers.forEach(function (o) {
  29545. _this.scene.removeActionManager(o);
  29546. });
  29547. this.sounds.forEach(function (o) {
  29548. o.stop();
  29549. o.autoplay = false;
  29550. _this.scene.mainSoundTrack.RemoveSound(o);
  29551. });
  29552. this.textures.forEach(function (o) {
  29553. _this.scene.removeTexture(o);
  29554. });
  29555. this.effectLayers.forEach(function (o) {
  29556. _this.scene.removeEffectLayer(o);
  29557. });
  29558. };
  29559. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29560. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29561. var asset = sourceAssets_1[_i];
  29562. var move = true;
  29563. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29564. var keepAsset = keepAssets_1[_a];
  29565. if (asset === keepAsset) {
  29566. move = false;
  29567. break;
  29568. }
  29569. }
  29570. if (move) {
  29571. targetAssets.push(asset);
  29572. }
  29573. }
  29574. };
  29575. /**
  29576. * Removes all the assets contained in the scene and adds them to the container.
  29577. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29578. */
  29579. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29580. if (keepAssets === undefined) {
  29581. keepAssets = new KeepAssets();
  29582. }
  29583. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29584. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29585. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29586. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29587. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29588. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29589. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29590. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29591. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29592. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29593. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29594. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29595. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29596. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29597. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29598. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29599. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29600. this.removeAllFromScene();
  29601. };
  29602. /**
  29603. * 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.
  29604. * @returns the root mesh
  29605. */
  29606. AssetContainer.prototype.createRootMesh = function () {
  29607. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29608. this.meshes.forEach(function (m) {
  29609. if (!m.parent) {
  29610. rootMesh.addChild(m);
  29611. }
  29612. });
  29613. this.meshes.unshift(rootMesh);
  29614. return rootMesh;
  29615. };
  29616. return AssetContainer;
  29617. }());
  29618. BABYLON.AssetContainer = AssetContainer;
  29619. })(BABYLON || (BABYLON = {}));
  29620. //# sourceMappingURL=babylon.assetContainer.js.map
  29621. var BABYLON;
  29622. (function (BABYLON) {
  29623. var Buffer = /** @class */ (function () {
  29624. /**
  29625. * Constructor
  29626. * @param engine the engine
  29627. * @param data the data to use for this buffer
  29628. * @param updatable whether the data is updatable
  29629. * @param stride the stride (optional)
  29630. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29631. * @param instanced whether the buffer is instanced (optional)
  29632. * @param useBytes set to true if the stride in in bytes (optional)
  29633. */
  29634. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29635. if (stride === void 0) { stride = 0; }
  29636. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29637. if (instanced === void 0) { instanced = false; }
  29638. if (useBytes === void 0) { useBytes = false; }
  29639. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29640. this._engine = engine.getScene().getEngine();
  29641. }
  29642. else {
  29643. this._engine = engine;
  29644. }
  29645. this._updatable = updatable;
  29646. this._instanced = instanced;
  29647. this._data = data;
  29648. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29649. if (!postponeInternalCreation) { // by default
  29650. this.create();
  29651. }
  29652. }
  29653. /**
  29654. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29655. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29656. * @param offset defines offset in the buffer (0 by default)
  29657. * @param size defines the size in floats of attributes (position is 3 for instance)
  29658. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29659. * @param instanced defines if the vertex buffer contains indexed data
  29660. * @param useBytes defines if the offset and stride are in bytes
  29661. * @returns the new vertex buffer
  29662. */
  29663. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29664. if (useBytes === void 0) { useBytes = false; }
  29665. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29666. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29667. // a lot of these parameters are ignored as they are overriden by the buffer
  29668. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29669. };
  29670. // Properties
  29671. Buffer.prototype.isUpdatable = function () {
  29672. return this._updatable;
  29673. };
  29674. Buffer.prototype.getData = function () {
  29675. return this._data;
  29676. };
  29677. Buffer.prototype.getBuffer = function () {
  29678. return this._buffer;
  29679. };
  29680. /**
  29681. * Gets the stride in float32 units (i.e. byte stride / 4).
  29682. * May not be an integer if the byte stride is not divisible by 4.
  29683. * DEPRECATED. Use byteStride instead.
  29684. * @returns the stride in float32 units
  29685. */
  29686. Buffer.prototype.getStrideSize = function () {
  29687. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29688. };
  29689. // Methods
  29690. Buffer.prototype.create = function (data) {
  29691. if (data === void 0) { data = null; }
  29692. if (!data && this._buffer) {
  29693. return; // nothing to do
  29694. }
  29695. data = data || this._data;
  29696. if (!data) {
  29697. return;
  29698. }
  29699. if (!this._buffer) { // create buffer
  29700. if (this._updatable) {
  29701. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29702. this._data = data;
  29703. }
  29704. else {
  29705. this._buffer = this._engine.createVertexBuffer(data);
  29706. }
  29707. }
  29708. else if (this._updatable) { // update buffer
  29709. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29710. this._data = data;
  29711. }
  29712. };
  29713. Buffer.prototype._rebuild = function () {
  29714. this._buffer = null;
  29715. this.create(this._data);
  29716. };
  29717. Buffer.prototype.update = function (data) {
  29718. this.create(data);
  29719. };
  29720. /**
  29721. * Updates the data directly.
  29722. * @param data the new data
  29723. * @param offset the new offset
  29724. * @param vertexCount the vertex count (optional)
  29725. * @param useBytes set to true if the offset is in bytes
  29726. */
  29727. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29728. if (useBytes === void 0) { useBytes = false; }
  29729. if (!this._buffer) {
  29730. return;
  29731. }
  29732. if (this._updatable) { // update buffer
  29733. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29734. this._data = null;
  29735. }
  29736. };
  29737. Buffer.prototype.dispose = function () {
  29738. if (!this._buffer) {
  29739. return;
  29740. }
  29741. if (this._engine._releaseBuffer(this._buffer)) {
  29742. this._buffer = null;
  29743. }
  29744. };
  29745. return Buffer;
  29746. }());
  29747. BABYLON.Buffer = Buffer;
  29748. })(BABYLON || (BABYLON = {}));
  29749. //# sourceMappingURL=babylon.buffer.js.map
  29750. var BABYLON;
  29751. (function (BABYLON) {
  29752. var VertexBuffer = /** @class */ (function () {
  29753. /**
  29754. * Constructor
  29755. * @param engine the engine
  29756. * @param data the data to use for this vertex buffer
  29757. * @param kind the vertex buffer kind
  29758. * @param updatable whether the data is updatable
  29759. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29760. * @param stride the stride (optional)
  29761. * @param instanced whether the buffer is instanced (optional)
  29762. * @param offset the offset of the data (optional)
  29763. * @param size the number of components (optional)
  29764. * @param type the type of the component (optional)
  29765. * @param normalized whether the data contains normalized data (optional)
  29766. * @param useBytes set to true if stride and offset are in bytes (optional)
  29767. */
  29768. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29769. if (normalized === void 0) { normalized = false; }
  29770. if (useBytes === void 0) { useBytes = false; }
  29771. if (data instanceof BABYLON.Buffer) {
  29772. this._buffer = data;
  29773. this._ownsBuffer = false;
  29774. }
  29775. else {
  29776. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29777. this._ownsBuffer = true;
  29778. }
  29779. this._kind = kind;
  29780. if (type == undefined) {
  29781. var data_1 = this.getData();
  29782. this.type = VertexBuffer.FLOAT;
  29783. if (data_1 instanceof Int8Array)
  29784. this.type = VertexBuffer.BYTE;
  29785. else if (data_1 instanceof Uint8Array)
  29786. this.type = VertexBuffer.UNSIGNED_BYTE;
  29787. else if (data_1 instanceof Int16Array)
  29788. this.type = VertexBuffer.SHORT;
  29789. else if (data_1 instanceof Uint16Array)
  29790. this.type = VertexBuffer.UNSIGNED_SHORT;
  29791. else if (data_1 instanceof Int32Array)
  29792. this.type = VertexBuffer.INT;
  29793. else if (data_1 instanceof Uint32Array)
  29794. this.type = VertexBuffer.UNSIGNED_INT;
  29795. }
  29796. else {
  29797. this.type = type;
  29798. }
  29799. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29800. if (useBytes) {
  29801. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29802. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29803. this.byteOffset = offset || 0;
  29804. }
  29805. else {
  29806. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29807. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29808. this.byteOffset = (offset || 0) * typeByteLength;
  29809. }
  29810. this.normalized = normalized;
  29811. this._instanced = instanced !== undefined ? instanced : false;
  29812. this._instanceDivisor = instanced ? 1 : 0;
  29813. }
  29814. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29815. /**
  29816. * Gets or sets the instance divisor when in instanced mode
  29817. */
  29818. get: function () {
  29819. return this._instanceDivisor;
  29820. },
  29821. set: function (value) {
  29822. this._instanceDivisor = value;
  29823. if (value == 0) {
  29824. this._instanced = false;
  29825. }
  29826. else {
  29827. this._instanced = true;
  29828. }
  29829. },
  29830. enumerable: true,
  29831. configurable: true
  29832. });
  29833. VertexBuffer.prototype._rebuild = function () {
  29834. if (!this._buffer) {
  29835. return;
  29836. }
  29837. this._buffer._rebuild();
  29838. };
  29839. /**
  29840. * Returns the kind of the VertexBuffer (string).
  29841. */
  29842. VertexBuffer.prototype.getKind = function () {
  29843. return this._kind;
  29844. };
  29845. // Properties
  29846. /**
  29847. * Boolean : is the VertexBuffer updatable ?
  29848. */
  29849. VertexBuffer.prototype.isUpdatable = function () {
  29850. return this._buffer.isUpdatable();
  29851. };
  29852. /**
  29853. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29854. */
  29855. VertexBuffer.prototype.getData = function () {
  29856. return this._buffer.getData();
  29857. };
  29858. /**
  29859. * Returns the WebGLBuffer associated to the VertexBuffer.
  29860. */
  29861. VertexBuffer.prototype.getBuffer = function () {
  29862. return this._buffer.getBuffer();
  29863. };
  29864. /**
  29865. * Returns the stride as a multiple of the type byte length.
  29866. * DEPRECATED. Use byteStride instead.
  29867. */
  29868. VertexBuffer.prototype.getStrideSize = function () {
  29869. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29870. };
  29871. /**
  29872. * Returns the offset as a multiple of the type byte length.
  29873. * DEPRECATED. Use byteOffset instead.
  29874. */
  29875. VertexBuffer.prototype.getOffset = function () {
  29876. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29877. };
  29878. /**
  29879. * Returns the number of components per vertex attribute (integer).
  29880. */
  29881. VertexBuffer.prototype.getSize = function () {
  29882. return this._size;
  29883. };
  29884. /**
  29885. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29886. */
  29887. VertexBuffer.prototype.getIsInstanced = function () {
  29888. return this._instanced;
  29889. };
  29890. /**
  29891. * Returns the instancing divisor, zero for non-instanced (integer).
  29892. */
  29893. VertexBuffer.prototype.getInstanceDivisor = function () {
  29894. return this._instanceDivisor;
  29895. };
  29896. // Methods
  29897. /**
  29898. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29899. * Returns the created WebGLBuffer.
  29900. */
  29901. VertexBuffer.prototype.create = function (data) {
  29902. return this._buffer.create(data);
  29903. };
  29904. /**
  29905. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29906. * This function will create a new buffer if the current one is not updatable
  29907. * Returns the updated WebGLBuffer.
  29908. */
  29909. VertexBuffer.prototype.update = function (data) {
  29910. return this._buffer.update(data);
  29911. };
  29912. /**
  29913. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29914. * Returns the directly updated WebGLBuffer.
  29915. * @param data the new data
  29916. * @param offset the new offset
  29917. * @param useBytes set to true if the offset is in bytes
  29918. */
  29919. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29920. if (useBytes === void 0) { useBytes = false; }
  29921. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29922. };
  29923. /**
  29924. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29925. */
  29926. VertexBuffer.prototype.dispose = function () {
  29927. if (this._ownsBuffer) {
  29928. this._buffer.dispose();
  29929. }
  29930. };
  29931. /**
  29932. * Enumerates each value of this vertex buffer as numbers.
  29933. * @param count the number of values to enumerate
  29934. * @param callback the callback function called for each value
  29935. */
  29936. VertexBuffer.prototype.forEach = function (count, callback) {
  29937. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29938. };
  29939. Object.defineProperty(VertexBuffer, "PositionKind", {
  29940. get: function () {
  29941. return VertexBuffer._PositionKind;
  29942. },
  29943. enumerable: true,
  29944. configurable: true
  29945. });
  29946. Object.defineProperty(VertexBuffer, "NormalKind", {
  29947. get: function () {
  29948. return VertexBuffer._NormalKind;
  29949. },
  29950. enumerable: true,
  29951. configurable: true
  29952. });
  29953. Object.defineProperty(VertexBuffer, "TangentKind", {
  29954. get: function () {
  29955. return VertexBuffer._TangentKind;
  29956. },
  29957. enumerable: true,
  29958. configurable: true
  29959. });
  29960. Object.defineProperty(VertexBuffer, "UVKind", {
  29961. get: function () {
  29962. return VertexBuffer._UVKind;
  29963. },
  29964. enumerable: true,
  29965. configurable: true
  29966. });
  29967. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29968. get: function () {
  29969. return VertexBuffer._UV2Kind;
  29970. },
  29971. enumerable: true,
  29972. configurable: true
  29973. });
  29974. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29975. get: function () {
  29976. return VertexBuffer._UV3Kind;
  29977. },
  29978. enumerable: true,
  29979. configurable: true
  29980. });
  29981. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29982. get: function () {
  29983. return VertexBuffer._UV4Kind;
  29984. },
  29985. enumerable: true,
  29986. configurable: true
  29987. });
  29988. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29989. get: function () {
  29990. return VertexBuffer._UV5Kind;
  29991. },
  29992. enumerable: true,
  29993. configurable: true
  29994. });
  29995. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29996. get: function () {
  29997. return VertexBuffer._UV6Kind;
  29998. },
  29999. enumerable: true,
  30000. configurable: true
  30001. });
  30002. Object.defineProperty(VertexBuffer, "ColorKind", {
  30003. get: function () {
  30004. return VertexBuffer._ColorKind;
  30005. },
  30006. enumerable: true,
  30007. configurable: true
  30008. });
  30009. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  30010. get: function () {
  30011. return VertexBuffer._MatricesIndicesKind;
  30012. },
  30013. enumerable: true,
  30014. configurable: true
  30015. });
  30016. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  30017. get: function () {
  30018. return VertexBuffer._MatricesWeightsKind;
  30019. },
  30020. enumerable: true,
  30021. configurable: true
  30022. });
  30023. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  30024. get: function () {
  30025. return VertexBuffer._MatricesIndicesExtraKind;
  30026. },
  30027. enumerable: true,
  30028. configurable: true
  30029. });
  30030. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  30031. get: function () {
  30032. return VertexBuffer._MatricesWeightsExtraKind;
  30033. },
  30034. enumerable: true,
  30035. configurable: true
  30036. });
  30037. /**
  30038. * Deduces the stride given a kind.
  30039. * @param kind The kind string to deduce
  30040. * @returns The deduced stride
  30041. */
  30042. VertexBuffer.DeduceStride = function (kind) {
  30043. switch (kind) {
  30044. case VertexBuffer.UVKind:
  30045. case VertexBuffer.UV2Kind:
  30046. case VertexBuffer.UV3Kind:
  30047. case VertexBuffer.UV4Kind:
  30048. case VertexBuffer.UV5Kind:
  30049. case VertexBuffer.UV6Kind:
  30050. return 2;
  30051. case VertexBuffer.NormalKind:
  30052. case VertexBuffer.PositionKind:
  30053. return 3;
  30054. case VertexBuffer.ColorKind:
  30055. case VertexBuffer.MatricesIndicesKind:
  30056. case VertexBuffer.MatricesIndicesExtraKind:
  30057. case VertexBuffer.MatricesWeightsKind:
  30058. case VertexBuffer.MatricesWeightsExtraKind:
  30059. case VertexBuffer.TangentKind:
  30060. return 4;
  30061. default:
  30062. throw new Error("Invalid kind '" + kind + "'");
  30063. }
  30064. };
  30065. /**
  30066. * Gets the byte length of the given type.
  30067. * @param type the type
  30068. * @returns the number of bytes
  30069. */
  30070. VertexBuffer.GetTypeByteLength = function (type) {
  30071. switch (type) {
  30072. case VertexBuffer.BYTE:
  30073. case VertexBuffer.UNSIGNED_BYTE:
  30074. return 1;
  30075. case VertexBuffer.SHORT:
  30076. case VertexBuffer.UNSIGNED_SHORT:
  30077. return 2;
  30078. case VertexBuffer.INT:
  30079. case VertexBuffer.FLOAT:
  30080. return 4;
  30081. default:
  30082. throw new Error("Invalid type '" + type + "'");
  30083. }
  30084. };
  30085. /**
  30086. * Enumerates each value of the given parameters as numbers.
  30087. * @param data the data to enumerate
  30088. * @param byteOffset the byte offset of the data
  30089. * @param byteStride the byte stride of the data
  30090. * @param componentCount the number of components per element
  30091. * @param componentType the type of the component
  30092. * @param count the total number of components
  30093. * @param normalized whether the data is normalized
  30094. * @param callback the callback function called for each value
  30095. */
  30096. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30097. if (data instanceof Array) {
  30098. var offset = byteOffset / 4;
  30099. var stride = byteStride / 4;
  30100. for (var index = 0; index < count; index += componentCount) {
  30101. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30102. callback(data[offset + componentIndex], index + componentIndex);
  30103. }
  30104. offset += stride;
  30105. }
  30106. }
  30107. else {
  30108. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30109. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30110. for (var index = 0; index < count; index += componentCount) {
  30111. var componentByteOffset = byteOffset;
  30112. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30113. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30114. callback(value, index + componentIndex);
  30115. componentByteOffset += componentByteLength;
  30116. }
  30117. byteOffset += byteStride;
  30118. }
  30119. }
  30120. };
  30121. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30122. switch (type) {
  30123. case VertexBuffer.BYTE: {
  30124. var value = dataView.getInt8(byteOffset);
  30125. if (normalized) {
  30126. value = Math.max(value / 127, -1);
  30127. }
  30128. return value;
  30129. }
  30130. case VertexBuffer.UNSIGNED_BYTE: {
  30131. var value = dataView.getUint8(byteOffset);
  30132. if (normalized) {
  30133. value = value / 255;
  30134. }
  30135. return value;
  30136. }
  30137. case VertexBuffer.SHORT: {
  30138. var value = dataView.getInt16(byteOffset, true);
  30139. if (normalized) {
  30140. value = Math.max(value / 16383, -1);
  30141. }
  30142. return value;
  30143. }
  30144. case VertexBuffer.UNSIGNED_SHORT: {
  30145. var value = dataView.getUint16(byteOffset, true);
  30146. if (normalized) {
  30147. value = value / 65535;
  30148. }
  30149. return value;
  30150. }
  30151. case VertexBuffer.FLOAT: {
  30152. return dataView.getFloat32(byteOffset, true);
  30153. }
  30154. default: {
  30155. throw new Error("Invalid component type " + type);
  30156. }
  30157. }
  30158. };
  30159. /**
  30160. * The byte type.
  30161. */
  30162. VertexBuffer.BYTE = 5120;
  30163. /**
  30164. * The unsigned byte type.
  30165. */
  30166. VertexBuffer.UNSIGNED_BYTE = 5121;
  30167. /**
  30168. * The short type.
  30169. */
  30170. VertexBuffer.SHORT = 5122;
  30171. /**
  30172. * The unsigned short type.
  30173. */
  30174. VertexBuffer.UNSIGNED_SHORT = 5123;
  30175. /**
  30176. * The integer type.
  30177. */
  30178. VertexBuffer.INT = 5124;
  30179. /**
  30180. * The unsigned integer type.
  30181. */
  30182. VertexBuffer.UNSIGNED_INT = 5125;
  30183. /**
  30184. * The float type.
  30185. */
  30186. VertexBuffer.FLOAT = 5126;
  30187. // Enums
  30188. VertexBuffer._PositionKind = "position";
  30189. VertexBuffer._NormalKind = "normal";
  30190. VertexBuffer._TangentKind = "tangent";
  30191. VertexBuffer._UVKind = "uv";
  30192. VertexBuffer._UV2Kind = "uv2";
  30193. VertexBuffer._UV3Kind = "uv3";
  30194. VertexBuffer._UV4Kind = "uv4";
  30195. VertexBuffer._UV5Kind = "uv5";
  30196. VertexBuffer._UV6Kind = "uv6";
  30197. VertexBuffer._ColorKind = "color";
  30198. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30199. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30200. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30201. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30202. return VertexBuffer;
  30203. }());
  30204. BABYLON.VertexBuffer = VertexBuffer;
  30205. })(BABYLON || (BABYLON = {}));
  30206. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30207. var BABYLON;
  30208. (function (BABYLON) {
  30209. /**
  30210. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30211. */
  30212. var DummyInternalTextureTracker = /** @class */ (function () {
  30213. function DummyInternalTextureTracker() {
  30214. /**
  30215. * Gets or set the previous tracker in the list
  30216. */
  30217. this.previous = null;
  30218. /**
  30219. * Gets or set the next tracker in the list
  30220. */
  30221. this.next = null;
  30222. }
  30223. return DummyInternalTextureTracker;
  30224. }());
  30225. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30226. })(BABYLON || (BABYLON = {}));
  30227. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30228. var BABYLON;
  30229. (function (BABYLON) {
  30230. /**
  30231. * Class used to store data associated with WebGL texture data for the engine
  30232. * This class should not be used directly
  30233. */
  30234. var InternalTexture = /** @class */ (function () {
  30235. /**
  30236. * Creates a new InternalTexture
  30237. * @param engine defines the engine to use
  30238. * @param dataSource defines the type of data that will be used
  30239. */
  30240. function InternalTexture(engine, dataSource) {
  30241. /**
  30242. * Observable called when the texture is loaded
  30243. */
  30244. this.onLoadedObservable = new BABYLON.Observable();
  30245. /**
  30246. * Gets or set the previous tracker in the list
  30247. */
  30248. this.previous = null;
  30249. /**
  30250. * Gets or set the next tracker in the list
  30251. */
  30252. this.next = null;
  30253. // Private
  30254. /** @hidden */
  30255. this._initialSlot = -1;
  30256. /** @hidden */
  30257. this._designatedSlot = -1;
  30258. /** @hidden */
  30259. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30260. /** @hidden */
  30261. this._comparisonFunction = 0;
  30262. /** @hidden */
  30263. this._lodGenerationScale = 0;
  30264. /** @hidden */
  30265. this._lodGenerationOffset = 0;
  30266. /** @hidden */
  30267. this._isRGBD = false;
  30268. /** @hidden */
  30269. this._references = 1;
  30270. this._engine = engine;
  30271. this._dataSource = dataSource;
  30272. this._webGLTexture = engine._createTexture();
  30273. }
  30274. /**
  30275. * Gets the Engine the texture belongs to.
  30276. * @returns The babylon engine
  30277. */
  30278. InternalTexture.prototype.getEngine = function () {
  30279. return this._engine;
  30280. };
  30281. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30282. /**
  30283. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30284. */
  30285. get: function () {
  30286. return this._dataSource;
  30287. },
  30288. enumerable: true,
  30289. configurable: true
  30290. });
  30291. /**
  30292. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30293. */
  30294. InternalTexture.prototype.incrementReferences = function () {
  30295. this._references++;
  30296. };
  30297. /**
  30298. * Change the size of the texture (not the size of the content)
  30299. * @param width defines the new width
  30300. * @param height defines the new height
  30301. * @param depth defines the new depth (1 by default)
  30302. */
  30303. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30304. if (depth === void 0) { depth = 1; }
  30305. this.width = width;
  30306. this.height = height;
  30307. this.depth = depth;
  30308. this.baseWidth = width;
  30309. this.baseHeight = height;
  30310. this.baseDepth = depth;
  30311. this._size = width * height * depth;
  30312. };
  30313. /** @hidden */
  30314. InternalTexture.prototype._rebuild = function () {
  30315. var _this = this;
  30316. var proxy;
  30317. this.isReady = false;
  30318. this._cachedCoordinatesMode = null;
  30319. this._cachedWrapU = null;
  30320. this._cachedWrapV = null;
  30321. this._cachedAnisotropicFilteringLevel = null;
  30322. switch (this._dataSource) {
  30323. case InternalTexture.DATASOURCE_TEMP:
  30324. return;
  30325. case InternalTexture.DATASOURCE_URL:
  30326. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30327. _this.isReady = true;
  30328. }, null, this._buffer, undefined, this.format);
  30329. proxy._swapAndDie(this);
  30330. return;
  30331. case InternalTexture.DATASOURCE_RAW:
  30332. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30333. proxy._swapAndDie(this);
  30334. this.isReady = true;
  30335. return;
  30336. case InternalTexture.DATASOURCE_RAW3D:
  30337. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30338. proxy._swapAndDie(this);
  30339. this.isReady = true;
  30340. return;
  30341. case InternalTexture.DATASOURCE_DYNAMIC:
  30342. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30343. proxy._swapAndDie(this);
  30344. // The engine will make sure to update content so no need to flag it as isReady = true
  30345. return;
  30346. case InternalTexture.DATASOURCE_RENDERTARGET:
  30347. var options = new BABYLON.RenderTargetCreationOptions();
  30348. options.generateDepthBuffer = this._generateDepthBuffer;
  30349. options.generateMipMaps = this.generateMipMaps;
  30350. options.generateStencilBuffer = this._generateStencilBuffer;
  30351. options.samplingMode = this.samplingMode;
  30352. options.type = this.type;
  30353. if (this.isCube) {
  30354. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30355. }
  30356. else {
  30357. var size = {
  30358. width: this.width,
  30359. height: this.height
  30360. };
  30361. proxy = this._engine.createRenderTargetTexture(size, options);
  30362. }
  30363. proxy._swapAndDie(this);
  30364. this.isReady = true;
  30365. return;
  30366. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30367. var depthTextureOptions = {
  30368. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30369. comparisonFunction: this._comparisonFunction,
  30370. generateStencil: this._generateStencilBuffer,
  30371. isCube: this.isCube
  30372. };
  30373. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30374. proxy._swapAndDie(this);
  30375. this.isReady = true;
  30376. return;
  30377. case InternalTexture.DATASOURCE_CUBE:
  30378. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30379. _this.isReady = true;
  30380. }, null, this.format, this._extension);
  30381. proxy._swapAndDie(this);
  30382. return;
  30383. case InternalTexture.DATASOURCE_CUBERAW:
  30384. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30385. proxy._swapAndDie(this);
  30386. this.isReady = true;
  30387. return;
  30388. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30389. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30390. if (proxy) {
  30391. proxy._swapAndDie(_this);
  30392. }
  30393. _this.isReady = true;
  30394. }, null, this.format, this._extension);
  30395. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30396. return;
  30397. }
  30398. };
  30399. InternalTexture.prototype._swapAndDie = function (target) {
  30400. target._webGLTexture = this._webGLTexture;
  30401. if (this._framebuffer) {
  30402. target._framebuffer = this._framebuffer;
  30403. }
  30404. if (this._depthStencilBuffer) {
  30405. target._depthStencilBuffer = this._depthStencilBuffer;
  30406. }
  30407. if (this._lodTextureHigh) {
  30408. if (target._lodTextureHigh) {
  30409. target._lodTextureHigh.dispose();
  30410. }
  30411. target._lodTextureHigh = this._lodTextureHigh;
  30412. }
  30413. if (this._lodTextureMid) {
  30414. if (target._lodTextureMid) {
  30415. target._lodTextureMid.dispose();
  30416. }
  30417. target._lodTextureMid = this._lodTextureMid;
  30418. }
  30419. if (this._lodTextureLow) {
  30420. if (target._lodTextureLow) {
  30421. target._lodTextureLow.dispose();
  30422. }
  30423. target._lodTextureLow = this._lodTextureLow;
  30424. }
  30425. var cache = this._engine.getLoadedTexturesCache();
  30426. var index = cache.indexOf(this);
  30427. if (index !== -1) {
  30428. cache.splice(index, 1);
  30429. }
  30430. };
  30431. /**
  30432. * Dispose the current allocated resources
  30433. */
  30434. InternalTexture.prototype.dispose = function () {
  30435. if (!this._webGLTexture) {
  30436. return;
  30437. }
  30438. this._references--;
  30439. if (this._references === 0) {
  30440. this._engine._releaseTexture(this);
  30441. this._webGLTexture = null;
  30442. this.previous = null;
  30443. this.next = null;
  30444. }
  30445. };
  30446. /**
  30447. * The source of the texture data is unknown
  30448. */
  30449. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30450. /**
  30451. * Texture data comes from an URL
  30452. */
  30453. InternalTexture.DATASOURCE_URL = 1;
  30454. /**
  30455. * Texture data is only used for temporary storage
  30456. */
  30457. InternalTexture.DATASOURCE_TEMP = 2;
  30458. /**
  30459. * Texture data comes from raw data (ArrayBuffer)
  30460. */
  30461. InternalTexture.DATASOURCE_RAW = 3;
  30462. /**
  30463. * Texture content is dynamic (video or dynamic texture)
  30464. */
  30465. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30466. /**
  30467. * Texture content is generated by rendering to it
  30468. */
  30469. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30470. /**
  30471. * Texture content is part of a multi render target process
  30472. */
  30473. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30474. /**
  30475. * Texture data comes from a cube data file
  30476. */
  30477. InternalTexture.DATASOURCE_CUBE = 7;
  30478. /**
  30479. * Texture data comes from a raw cube data
  30480. */
  30481. InternalTexture.DATASOURCE_CUBERAW = 8;
  30482. /**
  30483. * Texture data come from a prefiltered cube data file
  30484. */
  30485. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30486. /**
  30487. * Texture content is raw 3D data
  30488. */
  30489. InternalTexture.DATASOURCE_RAW3D = 10;
  30490. /**
  30491. * Texture content is a depth texture
  30492. */
  30493. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30494. return InternalTexture;
  30495. }());
  30496. BABYLON.InternalTexture = InternalTexture;
  30497. })(BABYLON || (BABYLON = {}));
  30498. //# sourceMappingURL=babylon.internalTexture.js.map
  30499. var BABYLON;
  30500. (function (BABYLON) {
  30501. var BaseTexture = /** @class */ (function () {
  30502. function BaseTexture(scene) {
  30503. this._hasAlpha = false;
  30504. this.getAlphaFromRGB = false;
  30505. this.level = 1;
  30506. this.coordinatesIndex = 0;
  30507. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30508. /**
  30509. * | Value | Type | Description |
  30510. * | ----- | ------------------ | ----------- |
  30511. * | 0 | CLAMP_ADDRESSMODE | |
  30512. * | 1 | WRAP_ADDRESSMODE | |
  30513. * | 2 | MIRROR_ADDRESSMODE | |
  30514. */
  30515. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30516. /**
  30517. * | Value | Type | Description |
  30518. * | ----- | ------------------ | ----------- |
  30519. * | 0 | CLAMP_ADDRESSMODE | |
  30520. * | 1 | WRAP_ADDRESSMODE | |
  30521. * | 2 | MIRROR_ADDRESSMODE | |
  30522. */
  30523. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30524. /**
  30525. * | Value | Type | Description |
  30526. * | ----- | ------------------ | ----------- |
  30527. * | 0 | CLAMP_ADDRESSMODE | |
  30528. * | 1 | WRAP_ADDRESSMODE | |
  30529. * | 2 | MIRROR_ADDRESSMODE | |
  30530. */
  30531. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30532. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30533. this.isCube = false;
  30534. this.is3D = false;
  30535. this.gammaSpace = true;
  30536. this.invertZ = false;
  30537. this.lodLevelInAlpha = false;
  30538. this.isRenderTarget = false;
  30539. this.animations = new Array();
  30540. /**
  30541. * An event triggered when the texture is disposed.
  30542. */
  30543. this.onDisposeObservable = new BABYLON.Observable();
  30544. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30545. this._cachedSize = BABYLON.Size.Zero();
  30546. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30547. if (this._scene) {
  30548. this._scene.textures.push(this);
  30549. }
  30550. this._uid = null;
  30551. }
  30552. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30553. get: function () {
  30554. return this._hasAlpha;
  30555. },
  30556. set: function (value) {
  30557. if (this._hasAlpha === value) {
  30558. return;
  30559. }
  30560. this._hasAlpha = value;
  30561. if (this._scene) {
  30562. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30563. }
  30564. },
  30565. enumerable: true,
  30566. configurable: true
  30567. });
  30568. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30569. get: function () {
  30570. return this._coordinatesMode;
  30571. },
  30572. /**
  30573. * How a texture is mapped.
  30574. *
  30575. * | Value | Type | Description |
  30576. * | ----- | ----------------------------------- | ----------- |
  30577. * | 0 | EXPLICIT_MODE | |
  30578. * | 1 | SPHERICAL_MODE | |
  30579. * | 2 | PLANAR_MODE | |
  30580. * | 3 | CUBIC_MODE | |
  30581. * | 4 | PROJECTION_MODE | |
  30582. * | 5 | SKYBOX_MODE | |
  30583. * | 6 | INVCUBIC_MODE | |
  30584. * | 7 | EQUIRECTANGULAR_MODE | |
  30585. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30586. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30587. */
  30588. set: function (value) {
  30589. if (this._coordinatesMode === value) {
  30590. return;
  30591. }
  30592. this._coordinatesMode = value;
  30593. if (this._scene) {
  30594. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30595. }
  30596. },
  30597. enumerable: true,
  30598. configurable: true
  30599. });
  30600. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30601. /**
  30602. * Gets whether or not the texture contains RGBD data.
  30603. */
  30604. get: function () {
  30605. return this._texture != null && this._texture._isRGBD;
  30606. },
  30607. enumerable: true,
  30608. configurable: true
  30609. });
  30610. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30611. get: function () {
  30612. if (this._texture)
  30613. return this._texture._lodGenerationOffset;
  30614. return 0.0;
  30615. },
  30616. set: function (value) {
  30617. if (this._texture)
  30618. this._texture._lodGenerationOffset = value;
  30619. },
  30620. enumerable: true,
  30621. configurable: true
  30622. });
  30623. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30624. get: function () {
  30625. if (this._texture)
  30626. return this._texture._lodGenerationScale;
  30627. return 0.0;
  30628. },
  30629. set: function (value) {
  30630. if (this._texture)
  30631. this._texture._lodGenerationScale = value;
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. Object.defineProperty(BaseTexture.prototype, "uid", {
  30637. get: function () {
  30638. if (!this._uid) {
  30639. this._uid = BABYLON.Tools.RandomId();
  30640. }
  30641. return this._uid;
  30642. },
  30643. enumerable: true,
  30644. configurable: true
  30645. });
  30646. BaseTexture.prototype.toString = function () {
  30647. return this.name;
  30648. };
  30649. BaseTexture.prototype.getClassName = function () {
  30650. return "BaseTexture";
  30651. };
  30652. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30653. set: function (callback) {
  30654. if (this._onDisposeObserver) {
  30655. this.onDisposeObservable.remove(this._onDisposeObserver);
  30656. }
  30657. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30658. },
  30659. enumerable: true,
  30660. configurable: true
  30661. });
  30662. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30663. get: function () {
  30664. return true;
  30665. },
  30666. enumerable: true,
  30667. configurable: true
  30668. });
  30669. BaseTexture.prototype.getScene = function () {
  30670. return this._scene;
  30671. };
  30672. BaseTexture.prototype.getTextureMatrix = function () {
  30673. return BABYLON.Matrix.IdentityReadOnly;
  30674. };
  30675. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30676. return BABYLON.Matrix.IdentityReadOnly;
  30677. };
  30678. BaseTexture.prototype.getInternalTexture = function () {
  30679. return this._texture;
  30680. };
  30681. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30682. return !this.isBlocking || this.isReady();
  30683. };
  30684. BaseTexture.prototype.isReady = function () {
  30685. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30686. this.delayLoad();
  30687. return false;
  30688. }
  30689. if (this._texture) {
  30690. return this._texture.isReady;
  30691. }
  30692. return false;
  30693. };
  30694. BaseTexture.prototype.getSize = function () {
  30695. if (this._texture) {
  30696. if (this._texture.width) {
  30697. this._cachedSize.width = this._texture.width;
  30698. this._cachedSize.height = this._texture.height;
  30699. return this._cachedSize;
  30700. }
  30701. if (this._texture._size) {
  30702. this._cachedSize.width = this._texture._size;
  30703. this._cachedSize.height = this._texture._size;
  30704. return this._cachedSize;
  30705. }
  30706. }
  30707. return this._cachedSize;
  30708. };
  30709. BaseTexture.prototype.getBaseSize = function () {
  30710. if (!this.isReady() || !this._texture)
  30711. return BABYLON.Size.Zero();
  30712. if (this._texture._size) {
  30713. return new BABYLON.Size(this._texture._size, this._texture._size);
  30714. }
  30715. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30716. };
  30717. BaseTexture.prototype.scale = function (ratio) {
  30718. };
  30719. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30720. get: function () {
  30721. return false;
  30722. },
  30723. enumerable: true,
  30724. configurable: true
  30725. });
  30726. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30727. if (!this._scene) {
  30728. return null;
  30729. }
  30730. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30731. for (var index = 0; index < texturesCache.length; index++) {
  30732. var texturesCacheEntry = texturesCache[index];
  30733. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30734. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30735. texturesCacheEntry.incrementReferences();
  30736. return texturesCacheEntry;
  30737. }
  30738. }
  30739. }
  30740. return null;
  30741. };
  30742. BaseTexture.prototype._rebuild = function () {
  30743. };
  30744. BaseTexture.prototype.delayLoad = function () {
  30745. };
  30746. BaseTexture.prototype.clone = function () {
  30747. return null;
  30748. };
  30749. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30750. get: function () {
  30751. if (!this._texture) {
  30752. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30753. }
  30754. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30755. },
  30756. enumerable: true,
  30757. configurable: true
  30758. });
  30759. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30760. get: function () {
  30761. if (!this._texture) {
  30762. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30763. }
  30764. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30765. },
  30766. enumerable: true,
  30767. configurable: true
  30768. });
  30769. /**
  30770. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30771. * This will returns an RGBA array buffer containing either in values (0-255) or
  30772. * float values (0-1) depending of the underlying buffer type.
  30773. * @param faceIndex The face of the texture to read (in case of cube texture)
  30774. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30775. * @returns The Array buffer containing the pixels data.
  30776. */
  30777. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30778. if (faceIndex === void 0) { faceIndex = 0; }
  30779. if (level === void 0) { level = 0; }
  30780. if (!this._texture) {
  30781. return null;
  30782. }
  30783. var size = this.getSize();
  30784. var width = size.width;
  30785. var height = size.height;
  30786. var scene = this.getScene();
  30787. if (!scene) {
  30788. return null;
  30789. }
  30790. var engine = scene.getEngine();
  30791. if (level != 0) {
  30792. width = width / Math.pow(2, level);
  30793. height = height / Math.pow(2, level);
  30794. width = Math.round(width);
  30795. height = Math.round(height);
  30796. }
  30797. if (this._texture.isCube) {
  30798. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30799. }
  30800. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30801. };
  30802. BaseTexture.prototype.releaseInternalTexture = function () {
  30803. if (this._texture) {
  30804. this._texture.dispose();
  30805. this._texture = null;
  30806. }
  30807. };
  30808. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30809. get: function () {
  30810. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30811. return null;
  30812. }
  30813. if (!this._texture._sphericalPolynomial) {
  30814. this._texture._sphericalPolynomial =
  30815. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30816. }
  30817. return this._texture._sphericalPolynomial;
  30818. },
  30819. set: function (value) {
  30820. if (this._texture) {
  30821. this._texture._sphericalPolynomial = value;
  30822. }
  30823. },
  30824. enumerable: true,
  30825. configurable: true
  30826. });
  30827. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30828. get: function () {
  30829. if (this._texture) {
  30830. return this._texture._lodTextureHigh;
  30831. }
  30832. return null;
  30833. },
  30834. enumerable: true,
  30835. configurable: true
  30836. });
  30837. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30838. get: function () {
  30839. if (this._texture) {
  30840. return this._texture._lodTextureMid;
  30841. }
  30842. return null;
  30843. },
  30844. enumerable: true,
  30845. configurable: true
  30846. });
  30847. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30848. get: function () {
  30849. if (this._texture) {
  30850. return this._texture._lodTextureLow;
  30851. }
  30852. return null;
  30853. },
  30854. enumerable: true,
  30855. configurable: true
  30856. });
  30857. BaseTexture.prototype.dispose = function () {
  30858. if (!this._scene) {
  30859. return;
  30860. }
  30861. // Animations
  30862. this._scene.stopAnimation(this);
  30863. // Remove from scene
  30864. this._scene._removePendingData(this);
  30865. var index = this._scene.textures.indexOf(this);
  30866. if (index >= 0) {
  30867. this._scene.textures.splice(index, 1);
  30868. }
  30869. if (this._texture === undefined) {
  30870. return;
  30871. }
  30872. // Release
  30873. this.releaseInternalTexture();
  30874. // Callback
  30875. this.onDisposeObservable.notifyObservers(this);
  30876. this.onDisposeObservable.clear();
  30877. };
  30878. BaseTexture.prototype.serialize = function () {
  30879. if (!this.name) {
  30880. return null;
  30881. }
  30882. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30883. // Animations
  30884. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30885. return serializationObject;
  30886. };
  30887. BaseTexture.WhenAllReady = function (textures, callback) {
  30888. var numRemaining = textures.length;
  30889. if (numRemaining === 0) {
  30890. callback();
  30891. return;
  30892. }
  30893. var _loop_1 = function () {
  30894. texture = textures[i];
  30895. if (texture.isReady()) {
  30896. if (--numRemaining === 0) {
  30897. callback();
  30898. }
  30899. }
  30900. else {
  30901. onLoadObservable = texture.onLoadObservable;
  30902. var onLoadCallback_1 = function () {
  30903. onLoadObservable.removeCallback(onLoadCallback_1);
  30904. if (--numRemaining === 0) {
  30905. callback();
  30906. }
  30907. };
  30908. onLoadObservable.add(onLoadCallback_1);
  30909. }
  30910. };
  30911. var texture, onLoadObservable;
  30912. for (var i = 0; i < textures.length; i++) {
  30913. _loop_1();
  30914. }
  30915. };
  30916. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30917. __decorate([
  30918. BABYLON.serialize()
  30919. ], BaseTexture.prototype, "name", void 0);
  30920. __decorate([
  30921. BABYLON.serialize("hasAlpha")
  30922. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30923. __decorate([
  30924. BABYLON.serialize()
  30925. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30926. __decorate([
  30927. BABYLON.serialize()
  30928. ], BaseTexture.prototype, "level", void 0);
  30929. __decorate([
  30930. BABYLON.serialize()
  30931. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30932. __decorate([
  30933. BABYLON.serialize("coordinatesMode")
  30934. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30935. __decorate([
  30936. BABYLON.serialize()
  30937. ], BaseTexture.prototype, "wrapU", void 0);
  30938. __decorate([
  30939. BABYLON.serialize()
  30940. ], BaseTexture.prototype, "wrapV", void 0);
  30941. __decorate([
  30942. BABYLON.serialize()
  30943. ], BaseTexture.prototype, "wrapR", void 0);
  30944. __decorate([
  30945. BABYLON.serialize()
  30946. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30947. __decorate([
  30948. BABYLON.serialize()
  30949. ], BaseTexture.prototype, "isCube", void 0);
  30950. __decorate([
  30951. BABYLON.serialize()
  30952. ], BaseTexture.prototype, "is3D", void 0);
  30953. __decorate([
  30954. BABYLON.serialize()
  30955. ], BaseTexture.prototype, "gammaSpace", void 0);
  30956. __decorate([
  30957. BABYLON.serialize()
  30958. ], BaseTexture.prototype, "invertZ", void 0);
  30959. __decorate([
  30960. BABYLON.serialize()
  30961. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30962. __decorate([
  30963. BABYLON.serialize()
  30964. ], BaseTexture.prototype, "lodGenerationOffset", null);
  30965. __decorate([
  30966. BABYLON.serialize()
  30967. ], BaseTexture.prototype, "lodGenerationScale", null);
  30968. __decorate([
  30969. BABYLON.serialize()
  30970. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30971. return BaseTexture;
  30972. }());
  30973. BABYLON.BaseTexture = BaseTexture;
  30974. })(BABYLON || (BABYLON = {}));
  30975. //# sourceMappingURL=babylon.baseTexture.js.map
  30976. var BABYLON;
  30977. (function (BABYLON) {
  30978. var Texture = /** @class */ (function (_super) {
  30979. __extends(Texture, _super);
  30980. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30981. if (noMipmap === void 0) { noMipmap = false; }
  30982. if (invertY === void 0) { invertY = true; }
  30983. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30984. if (onLoad === void 0) { onLoad = null; }
  30985. if (onError === void 0) { onError = null; }
  30986. if (buffer === void 0) { buffer = null; }
  30987. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30988. var _this = _super.call(this, scene) || this;
  30989. _this.uOffset = 0;
  30990. _this.vOffset = 0;
  30991. _this.uScale = 1.0;
  30992. _this.vScale = 1.0;
  30993. _this.uAng = 0;
  30994. _this.vAng = 0;
  30995. _this.wAng = 0;
  30996. /**
  30997. * Defines the center of rotation (U)
  30998. */
  30999. _this.uRotationCenter = 0.5;
  31000. /**
  31001. * Defines the center of rotation (V)
  31002. */
  31003. _this.vRotationCenter = 0.5;
  31004. /**
  31005. * Defines the center of rotation (W)
  31006. */
  31007. _this.wRotationCenter = 0.5;
  31008. _this._isBlocking = true;
  31009. _this.name = url || "";
  31010. _this.url = url;
  31011. _this._noMipmap = noMipmap;
  31012. _this._invertY = invertY;
  31013. _this._samplingMode = samplingMode;
  31014. _this._buffer = buffer;
  31015. _this._deleteBuffer = deleteBuffer;
  31016. if (format) {
  31017. _this._format = format;
  31018. }
  31019. scene = _this.getScene();
  31020. if (!scene) {
  31021. return _this;
  31022. }
  31023. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31024. var load = function () {
  31025. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31026. _this.onLoadObservable.notifyObservers(_this);
  31027. }
  31028. if (onLoad) {
  31029. onLoad();
  31030. }
  31031. if (!_this.isBlocking && scene) {
  31032. scene.resetCachedMaterial();
  31033. }
  31034. };
  31035. if (!_this.url) {
  31036. _this._delayedOnLoad = load;
  31037. _this._delayedOnError = onError;
  31038. return _this;
  31039. }
  31040. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31041. if (!_this._texture) {
  31042. if (!scene.useDelayedTextureLoading) {
  31043. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31044. if (deleteBuffer) {
  31045. delete _this._buffer;
  31046. }
  31047. }
  31048. else {
  31049. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31050. _this._delayedOnLoad = load;
  31051. _this._delayedOnError = onError;
  31052. }
  31053. }
  31054. else {
  31055. if (_this._texture.isReady) {
  31056. BABYLON.Tools.SetImmediate(function () { return load(); });
  31057. }
  31058. else {
  31059. _this._texture.onLoadedObservable.add(load);
  31060. }
  31061. }
  31062. return _this;
  31063. }
  31064. Object.defineProperty(Texture.prototype, "noMipmap", {
  31065. get: function () {
  31066. return this._noMipmap;
  31067. },
  31068. enumerable: true,
  31069. configurable: true
  31070. });
  31071. Object.defineProperty(Texture.prototype, "isBlocking", {
  31072. get: function () {
  31073. return this._isBlocking;
  31074. },
  31075. set: function (value) {
  31076. this._isBlocking = value;
  31077. },
  31078. enumerable: true,
  31079. configurable: true
  31080. });
  31081. Object.defineProperty(Texture.prototype, "samplingMode", {
  31082. get: function () {
  31083. return this._samplingMode;
  31084. },
  31085. enumerable: true,
  31086. configurable: true
  31087. });
  31088. /**
  31089. * Update the url (and optional buffer) of this texture if url was null during construction.
  31090. * @param url the url of the texture
  31091. * @param buffer the buffer of the texture (defaults to null)
  31092. */
  31093. Texture.prototype.updateURL = function (url, buffer) {
  31094. if (buffer === void 0) { buffer = null; }
  31095. if (this.url) {
  31096. throw new Error("URL is already set");
  31097. }
  31098. this.url = url;
  31099. this._buffer = buffer;
  31100. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31101. this.delayLoad();
  31102. };
  31103. Texture.prototype.delayLoad = function () {
  31104. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31105. return;
  31106. }
  31107. var scene = this.getScene();
  31108. if (!scene) {
  31109. return;
  31110. }
  31111. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31112. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31113. if (!this._texture) {
  31114. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31115. if (this._deleteBuffer) {
  31116. delete this._buffer;
  31117. }
  31118. }
  31119. else {
  31120. if (this._delayedOnLoad) {
  31121. if (this._texture.isReady) {
  31122. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31123. }
  31124. else {
  31125. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31126. }
  31127. }
  31128. }
  31129. this._delayedOnLoad = null;
  31130. this._delayedOnError = null;
  31131. };
  31132. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31133. if (!this._texture) {
  31134. return;
  31135. }
  31136. var scene = this.getScene();
  31137. if (!scene) {
  31138. return;
  31139. }
  31140. this._samplingMode = samplingMode;
  31141. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31142. };
  31143. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31144. x *= this.uScale;
  31145. y *= this.vScale;
  31146. x -= this.uRotationCenter * this.uScale;
  31147. y -= this.vRotationCenter * this.vScale;
  31148. z -= this.wRotationCenter;
  31149. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31150. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31151. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31152. t.z += this.wRotationCenter;
  31153. };
  31154. Texture.prototype.getTextureMatrix = function () {
  31155. var _this = this;
  31156. if (this.uOffset === this._cachedUOffset &&
  31157. this.vOffset === this._cachedVOffset &&
  31158. this.uScale === this._cachedUScale &&
  31159. this.vScale === this._cachedVScale &&
  31160. this.uAng === this._cachedUAng &&
  31161. this.vAng === this._cachedVAng &&
  31162. this.wAng === this._cachedWAng) {
  31163. return this._cachedTextureMatrix;
  31164. }
  31165. this._cachedUOffset = this.uOffset;
  31166. this._cachedVOffset = this.vOffset;
  31167. this._cachedUScale = this.uScale;
  31168. this._cachedVScale = this.vScale;
  31169. this._cachedUAng = this.uAng;
  31170. this._cachedVAng = this.vAng;
  31171. this._cachedWAng = this.wAng;
  31172. if (!this._cachedTextureMatrix) {
  31173. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31174. this._rowGenerationMatrix = new BABYLON.Matrix();
  31175. this._t0 = BABYLON.Vector3.Zero();
  31176. this._t1 = BABYLON.Vector3.Zero();
  31177. this._t2 = BABYLON.Vector3.Zero();
  31178. }
  31179. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31180. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31181. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31182. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31183. this._t1.subtractInPlace(this._t0);
  31184. this._t2.subtractInPlace(this._t0);
  31185. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31186. this._cachedTextureMatrix.m[0] = this._t1.x;
  31187. this._cachedTextureMatrix.m[1] = this._t1.y;
  31188. this._cachedTextureMatrix.m[2] = this._t1.z;
  31189. this._cachedTextureMatrix.m[4] = this._t2.x;
  31190. this._cachedTextureMatrix.m[5] = this._t2.y;
  31191. this._cachedTextureMatrix.m[6] = this._t2.z;
  31192. this._cachedTextureMatrix.m[8] = this._t0.x;
  31193. this._cachedTextureMatrix.m[9] = this._t0.y;
  31194. this._cachedTextureMatrix.m[10] = this._t0.z;
  31195. var scene = this.getScene();
  31196. if (!scene) {
  31197. return this._cachedTextureMatrix;
  31198. }
  31199. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31200. return mat.hasTexture(_this);
  31201. });
  31202. return this._cachedTextureMatrix;
  31203. };
  31204. Texture.prototype.getReflectionTextureMatrix = function () {
  31205. var _this = this;
  31206. var scene = this.getScene();
  31207. if (!scene) {
  31208. return this._cachedTextureMatrix;
  31209. }
  31210. if (this.uOffset === this._cachedUOffset &&
  31211. this.vOffset === this._cachedVOffset &&
  31212. this.uScale === this._cachedUScale &&
  31213. this.vScale === this._cachedVScale &&
  31214. this.coordinatesMode === this._cachedCoordinatesMode) {
  31215. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31216. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31217. return this._cachedTextureMatrix;
  31218. }
  31219. }
  31220. else {
  31221. return this._cachedTextureMatrix;
  31222. }
  31223. }
  31224. if (!this._cachedTextureMatrix) {
  31225. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31226. }
  31227. if (!this._projectionModeMatrix) {
  31228. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31229. }
  31230. this._cachedUOffset = this.uOffset;
  31231. this._cachedVOffset = this.vOffset;
  31232. this._cachedUScale = this.uScale;
  31233. this._cachedVScale = this.vScale;
  31234. this._cachedCoordinatesMode = this.coordinatesMode;
  31235. switch (this.coordinatesMode) {
  31236. case Texture.PLANAR_MODE:
  31237. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31238. this._cachedTextureMatrix[0] = this.uScale;
  31239. this._cachedTextureMatrix[5] = this.vScale;
  31240. this._cachedTextureMatrix[12] = this.uOffset;
  31241. this._cachedTextureMatrix[13] = this.vOffset;
  31242. break;
  31243. case Texture.PROJECTION_MODE:
  31244. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31245. this._projectionModeMatrix.m[0] = 0.5;
  31246. this._projectionModeMatrix.m[5] = -0.5;
  31247. this._projectionModeMatrix.m[10] = 0.0;
  31248. this._projectionModeMatrix.m[12] = 0.5;
  31249. this._projectionModeMatrix.m[13] = 0.5;
  31250. this._projectionModeMatrix.m[14] = 1.0;
  31251. this._projectionModeMatrix.m[15] = 1.0;
  31252. var projectionMatrix = scene.getProjectionMatrix();
  31253. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31254. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31255. break;
  31256. default:
  31257. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31258. break;
  31259. }
  31260. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31261. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31262. });
  31263. return this._cachedTextureMatrix;
  31264. };
  31265. Texture.prototype.clone = function () {
  31266. var _this = this;
  31267. return BABYLON.SerializationHelper.Clone(function () {
  31268. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31269. }, this);
  31270. };
  31271. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31272. get: function () {
  31273. if (!this._onLoadObservable) {
  31274. this._onLoadObservable = new BABYLON.Observable();
  31275. }
  31276. return this._onLoadObservable;
  31277. },
  31278. enumerable: true,
  31279. configurable: true
  31280. });
  31281. Texture.prototype.serialize = function () {
  31282. var serializationObject = _super.prototype.serialize.call(this);
  31283. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31284. serializationObject.base64String = this._buffer;
  31285. serializationObject.name = serializationObject.name.replace("data:", "");
  31286. }
  31287. serializationObject.invertY = this._invertY;
  31288. serializationObject.samplingMode = this.samplingMode;
  31289. return serializationObject;
  31290. };
  31291. Texture.prototype.getClassName = function () {
  31292. return "Texture";
  31293. };
  31294. Texture.prototype.dispose = function () {
  31295. _super.prototype.dispose.call(this);
  31296. if (this._onLoadObservable) {
  31297. this._onLoadObservable.clear();
  31298. this._onLoadObservable = null;
  31299. }
  31300. this._delayedOnLoad = null;
  31301. this._delayedOnError = null;
  31302. };
  31303. // Statics
  31304. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31305. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31306. if (onLoad === void 0) { onLoad = null; }
  31307. if (onError === void 0) { onError = null; }
  31308. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31309. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31310. };
  31311. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31312. if (parsedTexture.customType) {
  31313. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31314. // Update Sampling Mode
  31315. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31316. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31317. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31318. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31319. }
  31320. }
  31321. return parsedCustomTexture;
  31322. }
  31323. if (parsedTexture.isCube) {
  31324. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31325. }
  31326. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31327. return null;
  31328. }
  31329. var texture = BABYLON.SerializationHelper.Parse(function () {
  31330. var generateMipMaps = true;
  31331. if (parsedTexture.noMipmap) {
  31332. generateMipMaps = false;
  31333. }
  31334. if (parsedTexture.mirrorPlane) {
  31335. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31336. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31337. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31338. return mirrorTexture;
  31339. }
  31340. else if (parsedTexture.isRenderTarget) {
  31341. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31342. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31343. return renderTargetTexture;
  31344. }
  31345. else {
  31346. var texture;
  31347. if (parsedTexture.base64String) {
  31348. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31349. }
  31350. else {
  31351. var url = rootUrl + parsedTexture.name;
  31352. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31353. url = parsedTexture.url;
  31354. }
  31355. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31356. }
  31357. return texture;
  31358. }
  31359. }, parsedTexture, scene);
  31360. // Update Sampling Mode
  31361. if (parsedTexture.samplingMode) {
  31362. var sampling = parsedTexture.samplingMode;
  31363. if (texture._samplingMode !== sampling) {
  31364. texture.updateSamplingMode(sampling);
  31365. }
  31366. }
  31367. // Animations
  31368. if (parsedTexture.animations) {
  31369. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31370. var parsedAnimation = parsedTexture.animations[animationIndex];
  31371. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31372. }
  31373. }
  31374. return texture;
  31375. };
  31376. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31377. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31378. if (noMipmap === void 0) { noMipmap = false; }
  31379. if (invertY === void 0) { invertY = true; }
  31380. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31381. if (onLoad === void 0) { onLoad = null; }
  31382. if (onError === void 0) { onError = null; }
  31383. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31384. if (name.substr(0, 5) !== "data:") {
  31385. name = "data:" + name;
  31386. }
  31387. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31388. };
  31389. // Constants
  31390. Texture.NEAREST_SAMPLINGMODE = 1;
  31391. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31392. Texture.BILINEAR_SAMPLINGMODE = 2;
  31393. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31394. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31395. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31396. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31397. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31398. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31399. Texture.NEAREST_LINEAR = 7;
  31400. Texture.NEAREST_NEAREST = 8;
  31401. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31402. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31403. Texture.LINEAR_LINEAR = 11;
  31404. Texture.LINEAR_NEAREST = 12;
  31405. Texture.EXPLICIT_MODE = 0;
  31406. Texture.SPHERICAL_MODE = 1;
  31407. Texture.PLANAR_MODE = 2;
  31408. Texture.CUBIC_MODE = 3;
  31409. Texture.PROJECTION_MODE = 4;
  31410. Texture.SKYBOX_MODE = 5;
  31411. Texture.INVCUBIC_MODE = 6;
  31412. Texture.EQUIRECTANGULAR_MODE = 7;
  31413. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31414. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31415. Texture.CLAMP_ADDRESSMODE = 0;
  31416. Texture.WRAP_ADDRESSMODE = 1;
  31417. Texture.MIRROR_ADDRESSMODE = 2;
  31418. /**
  31419. * 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
  31420. */
  31421. Texture.UseSerializedUrlIfAny = false;
  31422. __decorate([
  31423. BABYLON.serialize()
  31424. ], Texture.prototype, "url", void 0);
  31425. __decorate([
  31426. BABYLON.serialize()
  31427. ], Texture.prototype, "uOffset", void 0);
  31428. __decorate([
  31429. BABYLON.serialize()
  31430. ], Texture.prototype, "vOffset", void 0);
  31431. __decorate([
  31432. BABYLON.serialize()
  31433. ], Texture.prototype, "uScale", void 0);
  31434. __decorate([
  31435. BABYLON.serialize()
  31436. ], Texture.prototype, "vScale", void 0);
  31437. __decorate([
  31438. BABYLON.serialize()
  31439. ], Texture.prototype, "uAng", void 0);
  31440. __decorate([
  31441. BABYLON.serialize()
  31442. ], Texture.prototype, "vAng", void 0);
  31443. __decorate([
  31444. BABYLON.serialize()
  31445. ], Texture.prototype, "wAng", void 0);
  31446. __decorate([
  31447. BABYLON.serialize()
  31448. ], Texture.prototype, "uRotationCenter", void 0);
  31449. __decorate([
  31450. BABYLON.serialize()
  31451. ], Texture.prototype, "vRotationCenter", void 0);
  31452. __decorate([
  31453. BABYLON.serialize()
  31454. ], Texture.prototype, "wRotationCenter", void 0);
  31455. __decorate([
  31456. BABYLON.serialize()
  31457. ], Texture.prototype, "isBlocking", null);
  31458. return Texture;
  31459. }(BABYLON.BaseTexture));
  31460. BABYLON.Texture = Texture;
  31461. })(BABYLON || (BABYLON = {}));
  31462. //# sourceMappingURL=babylon.texture.js.map
  31463. var BABYLON;
  31464. (function (BABYLON) {
  31465. /**
  31466. * @hidden
  31467. **/
  31468. var _InstancesBatch = /** @class */ (function () {
  31469. function _InstancesBatch() {
  31470. this.mustReturn = false;
  31471. this.visibleInstances = new Array();
  31472. this.renderSelf = new Array();
  31473. }
  31474. return _InstancesBatch;
  31475. }());
  31476. BABYLON._InstancesBatch = _InstancesBatch;
  31477. var Mesh = /** @class */ (function (_super) {
  31478. __extends(Mesh, _super);
  31479. /**
  31480. * @constructor
  31481. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31482. * @param {Scene} scene The scene to add this mesh to.
  31483. * @param {Node} parent The parent of this mesh, if it has one
  31484. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31485. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31486. * When false, achieved by calling a clone(), also passing False.
  31487. * This will make creation of children, recursive.
  31488. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31489. */
  31490. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31491. if (scene === void 0) { scene = null; }
  31492. if (parent === void 0) { parent = null; }
  31493. if (source === void 0) { source = null; }
  31494. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31495. var _this = _super.call(this, name, scene) || this;
  31496. // Events
  31497. /**
  31498. * An event triggered before rendering the mesh
  31499. */
  31500. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31501. /**
  31502. * An event triggered after rendering the mesh
  31503. */
  31504. _this.onAfterRenderObservable = new BABYLON.Observable();
  31505. /**
  31506. * An event triggered before drawing the mesh
  31507. */
  31508. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31509. // Members
  31510. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31511. _this.instances = new Array();
  31512. _this._LODLevels = new Array();
  31513. _this._visibleInstances = {};
  31514. _this._renderIdForInstances = new Array();
  31515. _this._batchCache = new _InstancesBatch();
  31516. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31517. // Use by builder only to know what orientation were the mesh build in.
  31518. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31519. _this.overrideMaterialSideOrientation = null;
  31520. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31521. // Will be used to save a source mesh reference, If any
  31522. _this._source = null;
  31523. scene = _this.getScene();
  31524. if (source) {
  31525. // Geometry
  31526. if (source._geometry) {
  31527. source._geometry.applyToMesh(_this);
  31528. }
  31529. // Deep copy
  31530. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31531. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31532. // Source mesh
  31533. _this._source = source;
  31534. // Metadata
  31535. if (source.metadata && source.metadata.clone) {
  31536. _this.metadata = source.metadata.clone();
  31537. }
  31538. else {
  31539. _this.metadata = source.metadata;
  31540. }
  31541. // Tags
  31542. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31543. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31544. }
  31545. // Parent
  31546. _this.parent = source.parent;
  31547. // Pivot
  31548. _this.setPivotMatrix(source.getPivotMatrix());
  31549. _this.id = name + "." + source.id;
  31550. // Material
  31551. _this.material = source.material;
  31552. var index;
  31553. if (!doNotCloneChildren) {
  31554. // Children
  31555. var directDescendants = source.getDescendants(true);
  31556. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31557. var child = directDescendants[index_1];
  31558. if (child.clone) {
  31559. child.clone(name + "." + child.name, _this);
  31560. }
  31561. }
  31562. }
  31563. // Physics clone
  31564. var physicsEngine = _this.getScene().getPhysicsEngine();
  31565. if (clonePhysicsImpostor && physicsEngine) {
  31566. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31567. if (impostor) {
  31568. _this.physicsImpostor = impostor.clone(_this);
  31569. }
  31570. }
  31571. // Particles
  31572. for (index = 0; index < scene.particleSystems.length; index++) {
  31573. var system = scene.particleSystems[index];
  31574. if (system.emitter === source) {
  31575. system.clone(system.name, _this);
  31576. }
  31577. }
  31578. _this.refreshBoundingInfo();
  31579. _this.computeWorldMatrix(true);
  31580. }
  31581. // Parent
  31582. if (parent !== null) {
  31583. _this.parent = parent;
  31584. }
  31585. return _this;
  31586. }
  31587. Object.defineProperty(Mesh, "FRONTSIDE", {
  31588. /**
  31589. * Mesh side orientation : usually the external or front surface
  31590. */
  31591. get: function () {
  31592. return Mesh._FRONTSIDE;
  31593. },
  31594. enumerable: true,
  31595. configurable: true
  31596. });
  31597. Object.defineProperty(Mesh, "BACKSIDE", {
  31598. /**
  31599. * Mesh side orientation : usually the internal or back surface
  31600. */
  31601. get: function () {
  31602. return Mesh._BACKSIDE;
  31603. },
  31604. enumerable: true,
  31605. configurable: true
  31606. });
  31607. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31608. /**
  31609. * Mesh side orientation : both internal and external or front and back surfaces
  31610. */
  31611. get: function () {
  31612. return Mesh._DOUBLESIDE;
  31613. },
  31614. enumerable: true,
  31615. configurable: true
  31616. });
  31617. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31618. /**
  31619. * Mesh side orientation : by default, `FRONTSIDE`
  31620. */
  31621. get: function () {
  31622. return Mesh._DEFAULTSIDE;
  31623. },
  31624. enumerable: true,
  31625. configurable: true
  31626. });
  31627. Object.defineProperty(Mesh, "NO_CAP", {
  31628. /**
  31629. * Mesh cap setting : no cap
  31630. */
  31631. get: function () {
  31632. return Mesh._NO_CAP;
  31633. },
  31634. enumerable: true,
  31635. configurable: true
  31636. });
  31637. Object.defineProperty(Mesh, "CAP_START", {
  31638. /**
  31639. * Mesh cap setting : one cap at the beginning of the mesh
  31640. */
  31641. get: function () {
  31642. return Mesh._CAP_START;
  31643. },
  31644. enumerable: true,
  31645. configurable: true
  31646. });
  31647. Object.defineProperty(Mesh, "CAP_END", {
  31648. /**
  31649. * Mesh cap setting : one cap at the end of the mesh
  31650. */
  31651. get: function () {
  31652. return Mesh._CAP_END;
  31653. },
  31654. enumerable: true,
  31655. configurable: true
  31656. });
  31657. Object.defineProperty(Mesh, "CAP_ALL", {
  31658. /**
  31659. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31660. */
  31661. get: function () {
  31662. return Mesh._CAP_ALL;
  31663. },
  31664. enumerable: true,
  31665. configurable: true
  31666. });
  31667. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31668. set: function (callback) {
  31669. if (this._onBeforeDrawObserver) {
  31670. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31671. }
  31672. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31673. },
  31674. enumerable: true,
  31675. configurable: true
  31676. });
  31677. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31678. get: function () {
  31679. return this._morphTargetManager;
  31680. },
  31681. set: function (value) {
  31682. if (this._morphTargetManager === value) {
  31683. return;
  31684. }
  31685. this._morphTargetManager = value;
  31686. this._syncGeometryWithMorphTargetManager();
  31687. },
  31688. enumerable: true,
  31689. configurable: true
  31690. });
  31691. Object.defineProperty(Mesh.prototype, "source", {
  31692. get: function () {
  31693. return this._source;
  31694. },
  31695. enumerable: true,
  31696. configurable: true
  31697. });
  31698. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31699. get: function () {
  31700. return this._unIndexed;
  31701. },
  31702. set: function (value) {
  31703. if (this._unIndexed !== value) {
  31704. this._unIndexed = value;
  31705. this._markSubMeshesAsAttributesDirty();
  31706. }
  31707. },
  31708. enumerable: true,
  31709. configurable: true
  31710. });
  31711. // Methods
  31712. /**
  31713. * Returns the string "Mesh".
  31714. */
  31715. Mesh.prototype.getClassName = function () {
  31716. return "Mesh";
  31717. };
  31718. /**
  31719. * Returns a string.
  31720. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31721. */
  31722. Mesh.prototype.toString = function (fullDetails) {
  31723. var ret = _super.prototype.toString.call(this, fullDetails);
  31724. ret += ", n vertices: " + this.getTotalVertices();
  31725. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31726. if (this.animations) {
  31727. for (var i = 0; i < this.animations.length; i++) {
  31728. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31729. }
  31730. }
  31731. if (fullDetails) {
  31732. if (this._geometry) {
  31733. var ib = this.getIndices();
  31734. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31735. if (vb && ib) {
  31736. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31737. }
  31738. }
  31739. else {
  31740. ret += ", flat shading: UNKNOWN";
  31741. }
  31742. }
  31743. return ret;
  31744. };
  31745. Mesh.prototype._unBindEffect = function () {
  31746. _super.prototype._unBindEffect.call(this);
  31747. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31748. var instance = _a[_i];
  31749. instance._unBindEffect();
  31750. }
  31751. };
  31752. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31753. /**
  31754. * True if the mesh has some Levels Of Details (LOD).
  31755. * Returns a boolean.
  31756. */
  31757. get: function () {
  31758. return this._LODLevels.length > 0;
  31759. },
  31760. enumerable: true,
  31761. configurable: true
  31762. });
  31763. /**
  31764. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31765. * @returns an array of {BABYLON.MeshLODLevel}
  31766. */
  31767. Mesh.prototype.getLODLevels = function () {
  31768. return this._LODLevels;
  31769. };
  31770. Mesh.prototype._sortLODLevels = function () {
  31771. this._LODLevels.sort(function (a, b) {
  31772. if (a.distance < b.distance) {
  31773. return 1;
  31774. }
  31775. if (a.distance > b.distance) {
  31776. return -1;
  31777. }
  31778. return 0;
  31779. });
  31780. };
  31781. /**
  31782. * Add a mesh as LOD level triggered at the given distance.
  31783. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31784. * @param distance The distance from the center of the object to show this level
  31785. * @param mesh The mesh to be added as LOD level (can be null)
  31786. * @return This mesh (for chaining)
  31787. */
  31788. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31789. if (mesh && mesh._masterMesh) {
  31790. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31791. return this;
  31792. }
  31793. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31794. this._LODLevels.push(level);
  31795. if (mesh) {
  31796. mesh._masterMesh = this;
  31797. }
  31798. this._sortLODLevels();
  31799. return this;
  31800. };
  31801. /**
  31802. * Returns the LOD level mesh at the passed distance or null if not found.
  31803. * It is related to the method `addLODLevel(distance, mesh)`.
  31804. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31805. * Returns an object Mesh or `null`.
  31806. */
  31807. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31808. for (var index = 0; index < this._LODLevels.length; index++) {
  31809. var level = this._LODLevels[index];
  31810. if (level.distance === distance) {
  31811. return level.mesh;
  31812. }
  31813. }
  31814. return null;
  31815. };
  31816. /**
  31817. * Remove a mesh from the LOD array
  31818. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31819. * @param {Mesh} mesh The mesh to be removed.
  31820. * @return {Mesh} This mesh (for chaining)
  31821. */
  31822. Mesh.prototype.removeLODLevel = function (mesh) {
  31823. for (var index = 0; index < this._LODLevels.length; index++) {
  31824. if (this._LODLevels[index].mesh === mesh) {
  31825. this._LODLevels.splice(index, 1);
  31826. if (mesh) {
  31827. mesh._masterMesh = null;
  31828. }
  31829. }
  31830. }
  31831. this._sortLODLevels();
  31832. return this;
  31833. };
  31834. /**
  31835. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31836. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31837. */
  31838. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31839. if (!this._LODLevels || this._LODLevels.length === 0) {
  31840. return this;
  31841. }
  31842. var bSphere;
  31843. if (boundingSphere) {
  31844. bSphere = boundingSphere;
  31845. }
  31846. else {
  31847. var boundingInfo = this.getBoundingInfo();
  31848. bSphere = boundingInfo.boundingSphere;
  31849. }
  31850. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31851. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31852. if (this.onLODLevelSelection) {
  31853. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31854. }
  31855. return this;
  31856. }
  31857. for (var index = 0; index < this._LODLevels.length; index++) {
  31858. var level = this._LODLevels[index];
  31859. if (level.distance < distanceToCamera) {
  31860. if (level.mesh) {
  31861. level.mesh._preActivate();
  31862. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31863. }
  31864. if (this.onLODLevelSelection) {
  31865. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31866. }
  31867. return level.mesh;
  31868. }
  31869. }
  31870. if (this.onLODLevelSelection) {
  31871. this.onLODLevelSelection(distanceToCamera, this, this);
  31872. }
  31873. return this;
  31874. };
  31875. Object.defineProperty(Mesh.prototype, "geometry", {
  31876. /**
  31877. * Returns the mesh internal Geometry object.
  31878. */
  31879. get: function () {
  31880. return this._geometry;
  31881. },
  31882. enumerable: true,
  31883. configurable: true
  31884. });
  31885. /**
  31886. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31887. */
  31888. Mesh.prototype.getTotalVertices = function () {
  31889. if (this._geometry === null || this._geometry === undefined) {
  31890. return 0;
  31891. }
  31892. return this._geometry.getTotalVertices();
  31893. };
  31894. /**
  31895. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31896. * 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.
  31897. * You can force the copy with forceCopy === true
  31898. * Returns null if the mesh has no geometry or no vertex buffer.
  31899. * Possible `kind` values :
  31900. * - BABYLON.VertexBuffer.PositionKind
  31901. * - BABYLON.VertexBuffer.UVKind
  31902. * - BABYLON.VertexBuffer.UV2Kind
  31903. * - BABYLON.VertexBuffer.UV3Kind
  31904. * - BABYLON.VertexBuffer.UV4Kind
  31905. * - BABYLON.VertexBuffer.UV5Kind
  31906. * - BABYLON.VertexBuffer.UV6Kind
  31907. * - BABYLON.VertexBuffer.ColorKind
  31908. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31909. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31910. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31911. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31912. */
  31913. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31914. if (!this._geometry) {
  31915. return null;
  31916. }
  31917. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31918. };
  31919. /**
  31920. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31921. * Returns `null` if the mesh has no geometry.
  31922. * Possible `kind` values :
  31923. * - BABYLON.VertexBuffer.PositionKind
  31924. * - BABYLON.VertexBuffer.UVKind
  31925. * - BABYLON.VertexBuffer.UV2Kind
  31926. * - BABYLON.VertexBuffer.UV3Kind
  31927. * - BABYLON.VertexBuffer.UV4Kind
  31928. * - BABYLON.VertexBuffer.UV5Kind
  31929. * - BABYLON.VertexBuffer.UV6Kind
  31930. * - BABYLON.VertexBuffer.ColorKind
  31931. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31932. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31933. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31934. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31935. */
  31936. Mesh.prototype.getVertexBuffer = function (kind) {
  31937. if (!this._geometry) {
  31938. return null;
  31939. }
  31940. return this._geometry.getVertexBuffer(kind);
  31941. };
  31942. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31943. if (!this._geometry) {
  31944. if (this._delayInfo) {
  31945. return this._delayInfo.indexOf(kind) !== -1;
  31946. }
  31947. return false;
  31948. }
  31949. return this._geometry.isVerticesDataPresent(kind);
  31950. };
  31951. /**
  31952. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31953. * Possible `kind` values :
  31954. * - BABYLON.VertexBuffer.PositionKind
  31955. * - BABYLON.VertexBuffer.UVKind
  31956. * - BABYLON.VertexBuffer.UV2Kind
  31957. * - BABYLON.VertexBuffer.UV3Kind
  31958. * - BABYLON.VertexBuffer.UV4Kind
  31959. * - BABYLON.VertexBuffer.UV5Kind
  31960. * - BABYLON.VertexBuffer.UV6Kind
  31961. * - BABYLON.VertexBuffer.ColorKind
  31962. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31963. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31964. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31965. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31966. */
  31967. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31968. if (!this._geometry) {
  31969. if (this._delayInfo) {
  31970. return this._delayInfo.indexOf(kind) !== -1;
  31971. }
  31972. return false;
  31973. }
  31974. return this._geometry.isVertexBufferUpdatable(kind);
  31975. };
  31976. /**
  31977. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31978. * Possible `kind` values :
  31979. * - BABYLON.VertexBuffer.PositionKind
  31980. * - BABYLON.VertexBuffer.UVKind
  31981. * - BABYLON.VertexBuffer.UV2Kind
  31982. * - BABYLON.VertexBuffer.UV3Kind
  31983. * - BABYLON.VertexBuffer.UV4Kind
  31984. * - BABYLON.VertexBuffer.UV5Kind
  31985. * - BABYLON.VertexBuffer.UV6Kind
  31986. * - BABYLON.VertexBuffer.ColorKind
  31987. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31988. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31989. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31990. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31991. */
  31992. Mesh.prototype.getVerticesDataKinds = function () {
  31993. if (!this._geometry) {
  31994. var result = new Array();
  31995. if (this._delayInfo) {
  31996. this._delayInfo.forEach(function (kind, index, array) {
  31997. result.push(kind);
  31998. });
  31999. }
  32000. return result;
  32001. }
  32002. return this._geometry.getVerticesDataKinds();
  32003. };
  32004. /**
  32005. * Returns a positive integer : the total number of indices in this mesh geometry.
  32006. * Returns zero if the mesh has no geometry.
  32007. */
  32008. Mesh.prototype.getTotalIndices = function () {
  32009. if (!this._geometry) {
  32010. return 0;
  32011. }
  32012. return this._geometry.getTotalIndices();
  32013. };
  32014. /**
  32015. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32016. * 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.
  32017. * Returns an empty array if the mesh has no geometry.
  32018. */
  32019. Mesh.prototype.getIndices = function (copyWhenShared) {
  32020. if (!this._geometry) {
  32021. return [];
  32022. }
  32023. return this._geometry.getIndices(copyWhenShared);
  32024. };
  32025. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32026. get: function () {
  32027. return this._masterMesh !== null && this._masterMesh !== undefined;
  32028. },
  32029. enumerable: true,
  32030. configurable: true
  32031. });
  32032. /**
  32033. * Determine if the current mesh is ready to be rendered
  32034. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32035. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32036. * @returns true if all associated assets are ready (material, textures, shaders)
  32037. */
  32038. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32039. if (completeCheck === void 0) { completeCheck = false; }
  32040. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32041. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32042. return false;
  32043. }
  32044. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32045. return false;
  32046. }
  32047. if (!this.subMeshes || this.subMeshes.length === 0) {
  32048. return true;
  32049. }
  32050. if (!completeCheck) {
  32051. return true;
  32052. }
  32053. var engine = this.getEngine();
  32054. var scene = this.getScene();
  32055. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32056. this.computeWorldMatrix();
  32057. var mat = this.material || scene.defaultMaterial;
  32058. if (mat) {
  32059. if (mat.storeEffectOnSubMeshes) {
  32060. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32061. var subMesh = _a[_i];
  32062. var effectiveMaterial = subMesh.getMaterial();
  32063. if (effectiveMaterial) {
  32064. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32065. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32066. return false;
  32067. }
  32068. }
  32069. else {
  32070. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32071. return false;
  32072. }
  32073. }
  32074. }
  32075. }
  32076. }
  32077. else {
  32078. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32079. return false;
  32080. }
  32081. }
  32082. }
  32083. // Shadows
  32084. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32085. var light = _c[_b];
  32086. var generator = light.getShadowGenerator();
  32087. if (generator) {
  32088. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32089. var subMesh = _e[_d];
  32090. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32091. return false;
  32092. }
  32093. }
  32094. }
  32095. }
  32096. // LOD
  32097. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32098. var lod = _g[_f];
  32099. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32100. return false;
  32101. }
  32102. }
  32103. return true;
  32104. };
  32105. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32106. /**
  32107. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32108. * This property is pertinent only for updatable parametric shapes.
  32109. */
  32110. get: function () {
  32111. return this._areNormalsFrozen;
  32112. },
  32113. enumerable: true,
  32114. configurable: true
  32115. });
  32116. /**
  32117. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32118. * It has no effect at all on other shapes.
  32119. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32120. * Returns the Mesh.
  32121. */
  32122. Mesh.prototype.freezeNormals = function () {
  32123. this._areNormalsFrozen = true;
  32124. return this;
  32125. };
  32126. /**
  32127. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32128. * It has no effect at all on other shapes.
  32129. * It reactivates the mesh normals computation if it was previously frozen.
  32130. * Returns the Mesh.
  32131. */
  32132. Mesh.prototype.unfreezeNormals = function () {
  32133. this._areNormalsFrozen = false;
  32134. return this;
  32135. };
  32136. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32137. /**
  32138. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32139. */
  32140. set: function (count) {
  32141. this._overridenInstanceCount = count;
  32142. },
  32143. enumerable: true,
  32144. configurable: true
  32145. });
  32146. // Methods
  32147. Mesh.prototype._preActivate = function () {
  32148. var sceneRenderId = this.getScene().getRenderId();
  32149. if (this._preActivateId === sceneRenderId) {
  32150. return this;
  32151. }
  32152. this._preActivateId = sceneRenderId;
  32153. this._visibleInstances = null;
  32154. return this;
  32155. };
  32156. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32157. if (this._visibleInstances) {
  32158. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32159. }
  32160. return this;
  32161. };
  32162. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32163. if (!this._visibleInstances) {
  32164. this._visibleInstances = {};
  32165. this._visibleInstances.defaultRenderId = renderId;
  32166. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32167. }
  32168. if (!this._visibleInstances[renderId]) {
  32169. this._visibleInstances[renderId] = new Array();
  32170. }
  32171. this._visibleInstances[renderId].push(instance);
  32172. return this;
  32173. };
  32174. /**
  32175. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32176. * This means the mesh underlying bounding box and sphere are recomputed.
  32177. * Returns the Mesh.
  32178. */
  32179. Mesh.prototype.refreshBoundingInfo = function () {
  32180. return this._refreshBoundingInfo(false);
  32181. };
  32182. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32183. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32184. return this;
  32185. }
  32186. var data = this._getPositionData(applySkeleton);
  32187. if (data) {
  32188. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32189. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32190. }
  32191. if (this.subMeshes) {
  32192. for (var index = 0; index < this.subMeshes.length; index++) {
  32193. this.subMeshes[index].refreshBoundingInfo();
  32194. }
  32195. }
  32196. this._updateBoundingInfo();
  32197. return this;
  32198. };
  32199. Mesh.prototype._getPositionData = function (applySkeleton) {
  32200. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32201. if (data && applySkeleton && this.skeleton) {
  32202. data = BABYLON.Tools.Slice(data);
  32203. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32204. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32205. if (matricesWeightsData && matricesIndicesData) {
  32206. var needExtras = this.numBoneInfluencers > 4;
  32207. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32208. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32209. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32210. var tempVector = BABYLON.Tmp.Vector3[0];
  32211. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32212. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32213. var matWeightIdx = 0;
  32214. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32215. finalMatrix.reset();
  32216. var inf;
  32217. var weight;
  32218. for (inf = 0; inf < 4; inf++) {
  32219. weight = matricesWeightsData[matWeightIdx + inf];
  32220. if (weight <= 0)
  32221. break;
  32222. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32223. finalMatrix.addToSelf(tempMatrix);
  32224. }
  32225. if (needExtras) {
  32226. for (inf = 0; inf < 4; inf++) {
  32227. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32228. if (weight <= 0)
  32229. break;
  32230. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32231. finalMatrix.addToSelf(tempMatrix);
  32232. }
  32233. }
  32234. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32235. tempVector.toArray(data, index);
  32236. }
  32237. }
  32238. }
  32239. return data;
  32240. };
  32241. Mesh.prototype._createGlobalSubMesh = function (force) {
  32242. var totalVertices = this.getTotalVertices();
  32243. if (!totalVertices || !this.getIndices()) {
  32244. return null;
  32245. }
  32246. // Check if we need to recreate the submeshes
  32247. if (this.subMeshes && this.subMeshes.length > 0) {
  32248. var ib = this.getIndices();
  32249. if (!ib) {
  32250. return null;
  32251. }
  32252. var totalIndices = ib.length;
  32253. var needToRecreate = false;
  32254. if (force) {
  32255. needToRecreate = true;
  32256. }
  32257. else {
  32258. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32259. var submesh = _a[_i];
  32260. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32261. needToRecreate = true;
  32262. break;
  32263. }
  32264. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32265. needToRecreate = true;
  32266. break;
  32267. }
  32268. }
  32269. }
  32270. if (!needToRecreate) {
  32271. return this.subMeshes[0];
  32272. }
  32273. }
  32274. this.releaseSubMeshes();
  32275. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32276. };
  32277. Mesh.prototype.subdivide = function (count) {
  32278. if (count < 1) {
  32279. return;
  32280. }
  32281. var totalIndices = this.getTotalIndices();
  32282. var subdivisionSize = (totalIndices / count) | 0;
  32283. var offset = 0;
  32284. // Ensure that subdivisionSize is a multiple of 3
  32285. while (subdivisionSize % 3 !== 0) {
  32286. subdivisionSize++;
  32287. }
  32288. this.releaseSubMeshes();
  32289. for (var index = 0; index < count; index++) {
  32290. if (offset >= totalIndices) {
  32291. break;
  32292. }
  32293. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32294. offset += subdivisionSize;
  32295. }
  32296. this.synchronizeInstances();
  32297. };
  32298. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32299. if (updatable === void 0) { updatable = false; }
  32300. if (!this._geometry) {
  32301. var vertexData = new BABYLON.VertexData();
  32302. vertexData.set(data, kind);
  32303. var scene = this.getScene();
  32304. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32305. }
  32306. else {
  32307. this._geometry.setVerticesData(kind, data, updatable, stride);
  32308. }
  32309. return this;
  32310. };
  32311. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32312. if (updatable === void 0) { updatable = true; }
  32313. var vb = this.getVertexBuffer(kind);
  32314. if (!vb || vb.isUpdatable() === updatable) {
  32315. return;
  32316. }
  32317. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32318. };
  32319. /**
  32320. * Sets the mesh VertexBuffer.
  32321. * Returns the Mesh.
  32322. */
  32323. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32324. if (!this._geometry) {
  32325. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32326. }
  32327. this._geometry.setVerticesBuffer(buffer);
  32328. return this;
  32329. };
  32330. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32331. if (!this._geometry) {
  32332. return this;
  32333. }
  32334. if (!makeItUnique) {
  32335. this._geometry.updateVerticesData(kind, data, updateExtends);
  32336. }
  32337. else {
  32338. this.makeGeometryUnique();
  32339. this.updateVerticesData(kind, data, updateExtends, false);
  32340. }
  32341. return this;
  32342. };
  32343. /**
  32344. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32345. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32346. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32347. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32348. * Returns the Mesh.
  32349. */
  32350. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32351. if (computeNormals === void 0) { computeNormals = true; }
  32352. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32353. if (!positions) {
  32354. return this;
  32355. }
  32356. positionFunction(positions);
  32357. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32358. if (computeNormals) {
  32359. var indices = this.getIndices();
  32360. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32361. if (!normals) {
  32362. return this;
  32363. }
  32364. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32365. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32366. }
  32367. return this;
  32368. };
  32369. /**
  32370. * Creates a un-shared specific occurence of the geometry for the mesh.
  32371. * Returns the Mesh.
  32372. */
  32373. Mesh.prototype.makeGeometryUnique = function () {
  32374. if (!this._geometry) {
  32375. return this;
  32376. }
  32377. var oldGeometry = this._geometry;
  32378. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32379. oldGeometry.releaseForMesh(this, true);
  32380. geometry.applyToMesh(this);
  32381. return this;
  32382. };
  32383. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32384. if (totalVertices === void 0) { totalVertices = null; }
  32385. if (updatable === void 0) { updatable = false; }
  32386. if (!this._geometry) {
  32387. var vertexData = new BABYLON.VertexData();
  32388. vertexData.indices = indices;
  32389. var scene = this.getScene();
  32390. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32391. }
  32392. else {
  32393. this._geometry.setIndices(indices, totalVertices, updatable);
  32394. }
  32395. return this;
  32396. };
  32397. /**
  32398. * Update the current index buffer
  32399. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32400. * Returns the Mesh.
  32401. */
  32402. Mesh.prototype.updateIndices = function (indices, offset) {
  32403. if (!this._geometry) {
  32404. return this;
  32405. }
  32406. this._geometry.updateIndices(indices, offset);
  32407. return this;
  32408. };
  32409. /**
  32410. * Invert the geometry to move from a right handed system to a left handed one.
  32411. * Returns the Mesh.
  32412. */
  32413. Mesh.prototype.toLeftHanded = function () {
  32414. if (!this._geometry) {
  32415. return this;
  32416. }
  32417. this._geometry.toLeftHanded();
  32418. return this;
  32419. };
  32420. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32421. if (!this._geometry) {
  32422. return this;
  32423. }
  32424. var engine = this.getScene().getEngine();
  32425. // Wireframe
  32426. var indexToBind;
  32427. if (this._unIndexed) {
  32428. indexToBind = null;
  32429. }
  32430. else {
  32431. switch (fillMode) {
  32432. case BABYLON.Material.PointFillMode:
  32433. indexToBind = null;
  32434. break;
  32435. case BABYLON.Material.WireFrameFillMode:
  32436. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32437. break;
  32438. default:
  32439. case BABYLON.Material.TriangleFillMode:
  32440. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32441. break;
  32442. }
  32443. }
  32444. // VBOs
  32445. this._geometry._bind(effect, indexToBind);
  32446. return this;
  32447. };
  32448. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32449. if (alternate === void 0) { alternate = false; }
  32450. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32451. return this;
  32452. }
  32453. this.onBeforeDrawObservable.notifyObservers(this);
  32454. var scene = this.getScene();
  32455. var engine = scene.getEngine();
  32456. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32457. // or triangles as points
  32458. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32459. }
  32460. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32461. // Triangles as wireframe
  32462. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32463. }
  32464. else {
  32465. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32466. }
  32467. if (scene._isAlternateRenderingEnabled && !alternate) {
  32468. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32469. if (!effect || !scene.activeCamera) {
  32470. return this;
  32471. }
  32472. scene._switchToAlternateCameraConfiguration(true);
  32473. this._effectiveMaterial.bindView(effect);
  32474. this._effectiveMaterial.bindViewProjection(effect);
  32475. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32476. this._draw(subMesh, fillMode, instancesCount, true);
  32477. engine.setViewport(scene.activeCamera.viewport);
  32478. scene._switchToAlternateCameraConfiguration(false);
  32479. this._effectiveMaterial.bindView(effect);
  32480. this._effectiveMaterial.bindViewProjection(effect);
  32481. }
  32482. return this;
  32483. };
  32484. /**
  32485. * Registers for this mesh a javascript function called just before the rendering process.
  32486. * This function is passed the current mesh.
  32487. * Return the Mesh.
  32488. */
  32489. Mesh.prototype.registerBeforeRender = function (func) {
  32490. this.onBeforeRenderObservable.add(func);
  32491. return this;
  32492. };
  32493. /**
  32494. * Disposes a previously registered javascript function called before the rendering.
  32495. * This function is passed the current mesh.
  32496. * Returns the Mesh.
  32497. */
  32498. Mesh.prototype.unregisterBeforeRender = function (func) {
  32499. this.onBeforeRenderObservable.removeCallback(func);
  32500. return this;
  32501. };
  32502. /**
  32503. * Registers for this mesh a javascript function called just after the rendering is complete.
  32504. * This function is passed the current mesh.
  32505. * Returns the Mesh.
  32506. */
  32507. Mesh.prototype.registerAfterRender = function (func) {
  32508. this.onAfterRenderObservable.add(func);
  32509. return this;
  32510. };
  32511. /**
  32512. * Disposes a previously registered javascript function called after the rendering.
  32513. * This function is passed the current mesh.
  32514. * Return the Mesh.
  32515. */
  32516. Mesh.prototype.unregisterAfterRender = function (func) {
  32517. this.onAfterRenderObservable.removeCallback(func);
  32518. return this;
  32519. };
  32520. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32521. var scene = this.getScene();
  32522. this._batchCache.mustReturn = false;
  32523. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32524. this._batchCache.visibleInstances[subMeshId] = null;
  32525. if (this._visibleInstances) {
  32526. var currentRenderId = scene.getRenderId();
  32527. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32528. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32529. var selfRenderId = this._renderId;
  32530. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32531. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32532. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32533. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32534. }
  32535. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32536. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32537. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32538. this._batchCache.mustReturn = true;
  32539. return this._batchCache;
  32540. }
  32541. if (currentRenderId !== selfRenderId) {
  32542. this._batchCache.renderSelf[subMeshId] = false;
  32543. }
  32544. }
  32545. this._renderIdForInstances[subMeshId] = currentRenderId;
  32546. }
  32547. return this._batchCache;
  32548. };
  32549. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32550. var visibleInstances = batch.visibleInstances[subMesh._id];
  32551. if (!visibleInstances) {
  32552. return this;
  32553. }
  32554. var matricesCount = visibleInstances.length + 1;
  32555. var bufferSize = matricesCount * 16 * 4;
  32556. var currentInstancesBufferSize = this._instancesBufferSize;
  32557. var instancesBuffer = this._instancesBuffer;
  32558. while (this._instancesBufferSize < bufferSize) {
  32559. this._instancesBufferSize *= 2;
  32560. }
  32561. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32562. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32563. }
  32564. var offset = 0;
  32565. var instancesCount = 0;
  32566. var world = this.getWorldMatrix();
  32567. if (batch.renderSelf[subMesh._id]) {
  32568. world.copyToArray(this._instancesData, offset);
  32569. offset += 16;
  32570. instancesCount++;
  32571. }
  32572. if (visibleInstances) {
  32573. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32574. var instance = visibleInstances[instanceIndex];
  32575. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32576. offset += 16;
  32577. instancesCount++;
  32578. }
  32579. }
  32580. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32581. if (instancesBuffer) {
  32582. instancesBuffer.dispose();
  32583. }
  32584. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32585. this._instancesBuffer = instancesBuffer;
  32586. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32587. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32588. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32589. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32590. }
  32591. else {
  32592. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32593. }
  32594. this._bind(subMesh, effect, fillMode);
  32595. this._draw(subMesh, fillMode, instancesCount);
  32596. engine.unbindInstanceAttributes();
  32597. return this;
  32598. };
  32599. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32600. var scene = this.getScene();
  32601. var engine = scene.getEngine();
  32602. if (hardwareInstancedRendering) {
  32603. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32604. }
  32605. else {
  32606. if (batch.renderSelf[subMesh._id]) {
  32607. // Draw
  32608. if (onBeforeDraw) {
  32609. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32610. }
  32611. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32612. }
  32613. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32614. if (visibleInstancesForSubMesh) {
  32615. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32616. var instance = visibleInstancesForSubMesh[instanceIndex];
  32617. // World
  32618. var world = instance.getWorldMatrix();
  32619. if (onBeforeDraw) {
  32620. onBeforeDraw(true, world, effectiveMaterial);
  32621. }
  32622. // Draw
  32623. this._draw(subMesh, fillMode);
  32624. }
  32625. }
  32626. }
  32627. return this;
  32628. };
  32629. /**
  32630. * Triggers the draw call for the mesh.
  32631. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32632. * Returns the Mesh.
  32633. */
  32634. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32635. this._checkOcclusionQuery();
  32636. if (this._isOccluded) {
  32637. return this;
  32638. }
  32639. var scene = this.getScene();
  32640. // Managing instances
  32641. var batch = this._getInstancesRenderList(subMesh._id);
  32642. if (batch.mustReturn) {
  32643. return this;
  32644. }
  32645. // Checking geometry state
  32646. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32647. return this;
  32648. }
  32649. this.onBeforeRenderObservable.notifyObservers(this);
  32650. var engine = scene.getEngine();
  32651. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32652. // Material
  32653. var material = subMesh.getMaterial();
  32654. if (!material) {
  32655. return this;
  32656. }
  32657. this._effectiveMaterial = material;
  32658. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32659. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32660. return this;
  32661. }
  32662. }
  32663. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32664. return this;
  32665. }
  32666. // Alpha mode
  32667. if (enableAlphaMode) {
  32668. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32669. }
  32670. // Outline - step 1
  32671. var savedDepthWrite = engine.getDepthWrite();
  32672. if (this.renderOutline) {
  32673. engine.setDepthWrite(false);
  32674. scene.getOutlineRenderer().render(subMesh, batch);
  32675. engine.setDepthWrite(savedDepthWrite);
  32676. }
  32677. var effect;
  32678. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32679. effect = subMesh.effect;
  32680. }
  32681. else {
  32682. effect = this._effectiveMaterial.getEffect();
  32683. }
  32684. if (!effect) {
  32685. return this;
  32686. }
  32687. var sideOrientation = this.overrideMaterialSideOrientation;
  32688. if (sideOrientation == null) {
  32689. sideOrientation = this._effectiveMaterial.sideOrientation;
  32690. if (this._getWorldMatrixDeterminant() < 0) {
  32691. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32692. }
  32693. }
  32694. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32695. if (this._effectiveMaterial.forceDepthWrite) {
  32696. engine.setDepthWrite(true);
  32697. }
  32698. // Bind
  32699. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32700. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32701. this._bind(subMesh, effect, fillMode);
  32702. }
  32703. var world = this.getWorldMatrix();
  32704. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32705. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32706. }
  32707. else {
  32708. this._effectiveMaterial.bind(world, this);
  32709. }
  32710. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32711. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32712. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32713. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32714. }
  32715. // Draw
  32716. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32717. // Unbind
  32718. this._effectiveMaterial.unbind();
  32719. // Outline - step 2
  32720. if (this.renderOutline && savedDepthWrite) {
  32721. engine.setDepthWrite(true);
  32722. engine.setColorWrite(false);
  32723. scene.getOutlineRenderer().render(subMesh, batch);
  32724. engine.setColorWrite(true);
  32725. }
  32726. // Overlay
  32727. if (this.renderOverlay) {
  32728. var currentMode = engine.getAlphaMode();
  32729. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32730. scene.getOutlineRenderer().render(subMesh, batch, true);
  32731. engine.setAlphaMode(currentMode);
  32732. }
  32733. this.onAfterRenderObservable.notifyObservers(this);
  32734. return this;
  32735. };
  32736. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32737. if (isInstance && effectiveMaterial) {
  32738. effectiveMaterial.bindOnlyWorldMatrix(world);
  32739. }
  32740. };
  32741. /**
  32742. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32743. */
  32744. Mesh.prototype.getEmittedParticleSystems = function () {
  32745. var results = new Array();
  32746. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32747. var particleSystem = this.getScene().particleSystems[index];
  32748. if (particleSystem.emitter === this) {
  32749. results.push(particleSystem);
  32750. }
  32751. }
  32752. return results;
  32753. };
  32754. /**
  32755. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32756. */
  32757. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32758. var results = new Array();
  32759. var descendants = this.getDescendants();
  32760. descendants.push(this);
  32761. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32762. var particleSystem = this.getScene().particleSystems[index];
  32763. var emitter = particleSystem.emitter;
  32764. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32765. results.push(particleSystem);
  32766. }
  32767. }
  32768. return results;
  32769. };
  32770. /**
  32771. * Normalize matrix weights so that all vertices have a total weight set to 1
  32772. */
  32773. Mesh.prototype.cleanMatrixWeights = function () {
  32774. var epsilon = 1e-3;
  32775. var noInfluenceBoneIndex = 0.0;
  32776. if (this.skeleton) {
  32777. noInfluenceBoneIndex = this.skeleton.bones.length;
  32778. }
  32779. else {
  32780. return;
  32781. }
  32782. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32783. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32784. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32785. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32786. var influencers = this.numBoneInfluencers;
  32787. var size = matricesWeights.length;
  32788. for (var i = 0; i < size; i += 4) {
  32789. var weight = 0.0;
  32790. var firstZeroWeight = -1;
  32791. for (var j = 0; j < 4; j++) {
  32792. var w = matricesWeights[i + j];
  32793. weight += w;
  32794. if (w < epsilon && firstZeroWeight < 0) {
  32795. firstZeroWeight = j;
  32796. }
  32797. }
  32798. if (matricesWeightsExtra) {
  32799. for (var j = 0; j < 4; j++) {
  32800. var w = matricesWeightsExtra[i + j];
  32801. weight += w;
  32802. if (w < epsilon && firstZeroWeight < 0) {
  32803. firstZeroWeight = j + 4;
  32804. }
  32805. }
  32806. }
  32807. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32808. firstZeroWeight = influencers - 1;
  32809. }
  32810. if (weight > epsilon) {
  32811. var mweight = 1.0 / weight;
  32812. for (var j = 0; j < 4; j++) {
  32813. matricesWeights[i + j] *= mweight;
  32814. }
  32815. if (matricesWeightsExtra) {
  32816. for (var j = 0; j < 4; j++) {
  32817. matricesWeightsExtra[i + j] *= mweight;
  32818. }
  32819. }
  32820. }
  32821. else {
  32822. if (firstZeroWeight >= 4) {
  32823. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32824. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32825. }
  32826. else {
  32827. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32828. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32829. }
  32830. }
  32831. }
  32832. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32833. if (matricesIndicesExtra) {
  32834. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32835. }
  32836. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32837. if (matricesWeightsExtra) {
  32838. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32839. }
  32840. };
  32841. Mesh.prototype._checkDelayState = function () {
  32842. var scene = this.getScene();
  32843. if (this._geometry) {
  32844. this._geometry.load(scene);
  32845. }
  32846. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32847. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32848. this._queueLoad(scene);
  32849. }
  32850. return this;
  32851. };
  32852. Mesh.prototype._queueLoad = function (scene) {
  32853. var _this = this;
  32854. scene._addPendingData(this);
  32855. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32856. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32857. if (data instanceof ArrayBuffer) {
  32858. _this._delayLoadingFunction(data, _this);
  32859. }
  32860. else {
  32861. _this._delayLoadingFunction(JSON.parse(data), _this);
  32862. }
  32863. _this.instances.forEach(function (instance) {
  32864. instance._syncSubMeshes();
  32865. });
  32866. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32867. scene._removePendingData(_this);
  32868. }, function () { }, scene.database, getBinaryData);
  32869. return this;
  32870. };
  32871. /**
  32872. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32873. */
  32874. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32875. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32876. return false;
  32877. }
  32878. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32879. return false;
  32880. }
  32881. this._checkDelayState();
  32882. return true;
  32883. };
  32884. /**
  32885. * Sets the mesh material by the material or multiMaterial `id` property.
  32886. * The material `id` is a string identifying the material or the multiMaterial.
  32887. * This method returns the Mesh.
  32888. */
  32889. Mesh.prototype.setMaterialByID = function (id) {
  32890. var materials = this.getScene().materials;
  32891. var index;
  32892. for (index = materials.length - 1; index > -1; index--) {
  32893. if (materials[index].id === id) {
  32894. this.material = materials[index];
  32895. return this;
  32896. }
  32897. }
  32898. // Multi
  32899. var multiMaterials = this.getScene().multiMaterials;
  32900. for (index = multiMaterials.length - 1; index > -1; index--) {
  32901. if (multiMaterials[index].id === id) {
  32902. this.material = multiMaterials[index];
  32903. return this;
  32904. }
  32905. }
  32906. return this;
  32907. };
  32908. /**
  32909. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32910. */
  32911. Mesh.prototype.getAnimatables = function () {
  32912. var results = new Array();
  32913. if (this.material) {
  32914. results.push(this.material);
  32915. }
  32916. if (this.skeleton) {
  32917. results.push(this.skeleton);
  32918. }
  32919. return results;
  32920. };
  32921. /**
  32922. * Modifies the mesh geometry according to the passed transformation matrix.
  32923. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32924. * The mesh normals are modified accordingly the same transformation.
  32925. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32926. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32927. * Returns the Mesh.
  32928. */
  32929. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32930. // Position
  32931. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32932. return this;
  32933. }
  32934. var submeshes = this.subMeshes.splice(0);
  32935. this._resetPointsArrayCache();
  32936. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32937. var temp = new Array();
  32938. var index;
  32939. for (index = 0; index < data.length; index += 3) {
  32940. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32941. }
  32942. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32943. // Normals
  32944. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32945. return this;
  32946. }
  32947. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32948. temp = [];
  32949. for (index = 0; index < data.length; index += 3) {
  32950. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32951. }
  32952. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32953. // flip faces?
  32954. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32955. this.flipFaces();
  32956. }
  32957. // Restore submeshes
  32958. this.releaseSubMeshes();
  32959. this.subMeshes = submeshes;
  32960. return this;
  32961. };
  32962. /**
  32963. * Modifies the mesh geometry according to its own current World Matrix.
  32964. * The mesh World Matrix is then reset.
  32965. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32966. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32967. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32968. * Returns the Mesh.
  32969. */
  32970. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32971. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32972. this.scaling.copyFromFloats(1, 1, 1);
  32973. this.position.copyFromFloats(0, 0, 0);
  32974. this.rotation.copyFromFloats(0, 0, 0);
  32975. //only if quaternion is already set
  32976. if (this.rotationQuaternion) {
  32977. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32978. }
  32979. this._worldMatrix = BABYLON.Matrix.Identity();
  32980. return this;
  32981. };
  32982. Object.defineProperty(Mesh.prototype, "_positions", {
  32983. // Cache
  32984. get: function () {
  32985. if (this._geometry) {
  32986. return this._geometry._positions;
  32987. }
  32988. return null;
  32989. },
  32990. enumerable: true,
  32991. configurable: true
  32992. });
  32993. Mesh.prototype._resetPointsArrayCache = function () {
  32994. if (this._geometry) {
  32995. this._geometry._resetPointsArrayCache();
  32996. }
  32997. return this;
  32998. };
  32999. Mesh.prototype._generatePointsArray = function () {
  33000. if (this._geometry) {
  33001. return this._geometry._generatePointsArray();
  33002. }
  33003. return false;
  33004. };
  33005. /**
  33006. * Returns a new Mesh object generated from the current mesh properties.
  33007. * This method must not get confused with createInstance().
  33008. * The parameter `name` is a string, the name given to the new mesh.
  33009. * The optional parameter `newParent` can be any Node object (default `null`).
  33010. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  33011. * 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.
  33012. */
  33013. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33014. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33015. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33016. };
  33017. /**
  33018. * Releases resources associated with this mesh.
  33019. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33020. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33021. */
  33022. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33023. var _this = this;
  33024. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33025. this.morphTargetManager = null;
  33026. if (this._geometry) {
  33027. this._geometry.releaseForMesh(this, true);
  33028. }
  33029. // Sources
  33030. var meshes = this.getScene().meshes;
  33031. meshes.forEach(function (abstractMesh) {
  33032. var mesh = abstractMesh;
  33033. if (mesh._source && mesh._source === _this) {
  33034. mesh._source = null;
  33035. }
  33036. });
  33037. this._source = null;
  33038. // Instances
  33039. if (this._instancesBuffer) {
  33040. this._instancesBuffer.dispose();
  33041. this._instancesBuffer = null;
  33042. }
  33043. while (this.instances.length) {
  33044. this.instances[0].dispose();
  33045. }
  33046. // Effect layers.
  33047. var effectLayers = this.getScene().effectLayers;
  33048. for (var i = 0; i < effectLayers.length; i++) {
  33049. var effectLayer = effectLayers[i];
  33050. if (effectLayer) {
  33051. effectLayer._disposeMesh(this);
  33052. }
  33053. }
  33054. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33055. };
  33056. /**
  33057. * Modifies the mesh geometry according to a displacement map.
  33058. * 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.
  33059. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33060. * This method returns nothing.
  33061. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33062. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33063. * 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.
  33064. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33065. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33066. *
  33067. * Returns the Mesh.
  33068. */
  33069. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33070. var _this = this;
  33071. var scene = this.getScene();
  33072. var onload = function (img) {
  33073. // Getting height map data
  33074. var canvas = document.createElement("canvas");
  33075. var context = canvas.getContext("2d");
  33076. var heightMapWidth = img.width;
  33077. var heightMapHeight = img.height;
  33078. canvas.width = heightMapWidth;
  33079. canvas.height = heightMapHeight;
  33080. context.drawImage(img, 0, 0);
  33081. // Create VertexData from map data
  33082. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33083. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33084. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33085. //execute success callback, if set
  33086. if (onSuccess) {
  33087. onSuccess(_this);
  33088. }
  33089. };
  33090. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33091. return this;
  33092. };
  33093. /**
  33094. * Modifies the mesh geometry according to a displacementMap buffer.
  33095. * 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.
  33096. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33097. * This method returns nothing.
  33098. * 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.
  33099. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33100. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33101. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33102. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33103. *
  33104. * Returns the Mesh.
  33105. */
  33106. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33107. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33108. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33109. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33110. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33111. return this;
  33112. }
  33113. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33114. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33115. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33116. var position = BABYLON.Vector3.Zero();
  33117. var normal = BABYLON.Vector3.Zero();
  33118. var uv = BABYLON.Vector2.Zero();
  33119. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33120. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33121. for (var index = 0; index < positions.length; index += 3) {
  33122. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33123. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33124. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33125. // Compute height
  33126. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33127. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33128. var pos = (u + v * heightMapWidth) * 4;
  33129. var r = buffer[pos] / 255.0;
  33130. var g = buffer[pos + 1] / 255.0;
  33131. var b = buffer[pos + 2] / 255.0;
  33132. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33133. normal.normalize();
  33134. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33135. position = position.add(normal);
  33136. position.toArray(positions, index);
  33137. }
  33138. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33139. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33140. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33141. return this;
  33142. };
  33143. /**
  33144. * Modify the mesh to get a flat shading rendering.
  33145. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33146. * This method returns the Mesh.
  33147. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33148. */
  33149. Mesh.prototype.convertToFlatShadedMesh = function () {
  33150. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33151. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33152. var kinds = this.getVerticesDataKinds();
  33153. var vbs = {};
  33154. var data = {};
  33155. var newdata = {};
  33156. var updatableNormals = false;
  33157. var kindIndex;
  33158. var kind;
  33159. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33160. kind = kinds[kindIndex];
  33161. var vertexBuffer = this.getVertexBuffer(kind);
  33162. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33163. updatableNormals = vertexBuffer.isUpdatable();
  33164. kinds.splice(kindIndex, 1);
  33165. kindIndex--;
  33166. continue;
  33167. }
  33168. vbs[kind] = vertexBuffer;
  33169. data[kind] = vbs[kind].getData();
  33170. newdata[kind] = [];
  33171. }
  33172. // Save previous submeshes
  33173. var previousSubmeshes = this.subMeshes.slice(0);
  33174. var indices = this.getIndices();
  33175. var totalIndices = this.getTotalIndices();
  33176. // Generating unique vertices per face
  33177. var index;
  33178. for (index = 0; index < totalIndices; index++) {
  33179. var vertexIndex = indices[index];
  33180. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33181. kind = kinds[kindIndex];
  33182. var stride = vbs[kind].getStrideSize();
  33183. for (var offset = 0; offset < stride; offset++) {
  33184. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33185. }
  33186. }
  33187. }
  33188. // Updating faces & normal
  33189. var normals = [];
  33190. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33191. for (index = 0; index < totalIndices; index += 3) {
  33192. indices[index] = index;
  33193. indices[index + 1] = index + 1;
  33194. indices[index + 2] = index + 2;
  33195. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33196. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33197. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33198. var p1p2 = p1.subtract(p2);
  33199. var p3p2 = p3.subtract(p2);
  33200. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33201. // Store same normals for every vertex
  33202. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33203. normals.push(normal.x);
  33204. normals.push(normal.y);
  33205. normals.push(normal.z);
  33206. }
  33207. }
  33208. this.setIndices(indices);
  33209. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33210. // Updating vertex buffers
  33211. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33212. kind = kinds[kindIndex];
  33213. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33214. }
  33215. // Updating submeshes
  33216. this.releaseSubMeshes();
  33217. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33218. var previousOne = previousSubmeshes[submeshIndex];
  33219. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33220. }
  33221. this.synchronizeInstances();
  33222. return this;
  33223. };
  33224. /**
  33225. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33226. * In other words, more vertices, no more indices and a single bigger VBO.
  33227. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33228. * Returns the Mesh.
  33229. */
  33230. Mesh.prototype.convertToUnIndexedMesh = function () {
  33231. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33232. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33233. var kinds = this.getVerticesDataKinds();
  33234. var vbs = {};
  33235. var data = {};
  33236. var newdata = {};
  33237. var kindIndex;
  33238. var kind;
  33239. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33240. kind = kinds[kindIndex];
  33241. var vertexBuffer = this.getVertexBuffer(kind);
  33242. vbs[kind] = vertexBuffer;
  33243. data[kind] = vbs[kind].getData();
  33244. newdata[kind] = [];
  33245. }
  33246. // Save previous submeshes
  33247. var previousSubmeshes = this.subMeshes.slice(0);
  33248. var indices = this.getIndices();
  33249. var totalIndices = this.getTotalIndices();
  33250. // Generating unique vertices per face
  33251. var index;
  33252. for (index = 0; index < totalIndices; index++) {
  33253. var vertexIndex = indices[index];
  33254. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33255. kind = kinds[kindIndex];
  33256. var stride = vbs[kind].getStrideSize();
  33257. for (var offset = 0; offset < stride; offset++) {
  33258. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33259. }
  33260. }
  33261. }
  33262. // Updating indices
  33263. for (index = 0; index < totalIndices; index += 3) {
  33264. indices[index] = index;
  33265. indices[index + 1] = index + 1;
  33266. indices[index + 2] = index + 2;
  33267. }
  33268. this.setIndices(indices);
  33269. // Updating vertex buffers
  33270. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33271. kind = kinds[kindIndex];
  33272. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33273. }
  33274. // Updating submeshes
  33275. this.releaseSubMeshes();
  33276. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33277. var previousOne = previousSubmeshes[submeshIndex];
  33278. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33279. }
  33280. this._unIndexed = true;
  33281. this.synchronizeInstances();
  33282. return this;
  33283. };
  33284. /**
  33285. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33286. * This method returns the Mesh.
  33287. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33288. */
  33289. Mesh.prototype.flipFaces = function (flipNormals) {
  33290. if (flipNormals === void 0) { flipNormals = false; }
  33291. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33292. var i;
  33293. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33294. for (i = 0; i < vertex_data.normals.length; i++) {
  33295. vertex_data.normals[i] *= -1;
  33296. }
  33297. }
  33298. if (vertex_data.indices) {
  33299. var temp;
  33300. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33301. // reassign indices
  33302. temp = vertex_data.indices[i + 1];
  33303. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33304. vertex_data.indices[i + 2] = temp;
  33305. }
  33306. }
  33307. vertex_data.applyToMesh(this);
  33308. return this;
  33309. };
  33310. // Instances
  33311. /**
  33312. * Creates a new InstancedMesh object from the mesh model.
  33313. * An instance shares the same properties and the same material than its model.
  33314. * Only these properties of each instance can then be set individually :
  33315. * - position
  33316. * - rotation
  33317. * - rotationQuaternion
  33318. * - setPivotMatrix
  33319. * - scaling
  33320. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33321. * Warning : this method is not supported for Line mesh and LineSystem
  33322. */
  33323. Mesh.prototype.createInstance = function (name) {
  33324. return new BABYLON.InstancedMesh(name, this);
  33325. };
  33326. /**
  33327. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33328. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33329. * This method returns the Mesh.
  33330. */
  33331. Mesh.prototype.synchronizeInstances = function () {
  33332. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33333. var instance = this.instances[instanceIndex];
  33334. instance._syncSubMeshes();
  33335. }
  33336. return this;
  33337. };
  33338. /**
  33339. * Simplify the mesh according to the given array of settings.
  33340. * Function will return immediately and will simplify async. It returns the Mesh.
  33341. * @param settings a collection of simplification settings.
  33342. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33343. * @param type the type of simplification to run.
  33344. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33345. */
  33346. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33347. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33348. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33349. this.getScene().simplificationQueue.addTask({
  33350. settings: settings,
  33351. parallelProcessing: parallelProcessing,
  33352. mesh: this,
  33353. simplificationType: simplificationType,
  33354. successCallback: successCallback
  33355. });
  33356. return this;
  33357. };
  33358. /**
  33359. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33360. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33361. * This should be used together with the simplification to avoid disappearing triangles.
  33362. * Returns the Mesh.
  33363. * @param successCallback an optional success callback to be called after the optimization finished.
  33364. */
  33365. Mesh.prototype.optimizeIndices = function (successCallback) {
  33366. var _this = this;
  33367. var indices = this.getIndices();
  33368. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33369. if (!positions || !indices) {
  33370. return this;
  33371. }
  33372. var vectorPositions = new Array();
  33373. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33374. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33375. }
  33376. var dupes = new Array();
  33377. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33378. var realPos = vectorPositions.length - 1 - iteration;
  33379. var testedPosition = vectorPositions[realPos];
  33380. for (var j = 0; j < realPos; ++j) {
  33381. var againstPosition = vectorPositions[j];
  33382. if (testedPosition.equals(againstPosition)) {
  33383. dupes[realPos] = j;
  33384. break;
  33385. }
  33386. }
  33387. }, function () {
  33388. for (var i = 0; i < indices.length; ++i) {
  33389. indices[i] = dupes[indices[i]] || indices[i];
  33390. }
  33391. //indices are now reordered
  33392. var originalSubMeshes = _this.subMeshes.slice(0);
  33393. _this.setIndices(indices);
  33394. _this.subMeshes = originalSubMeshes;
  33395. if (successCallback) {
  33396. successCallback(_this);
  33397. }
  33398. });
  33399. return this;
  33400. };
  33401. Mesh.prototype.serialize = function (serializationObject) {
  33402. serializationObject.name = this.name;
  33403. serializationObject.id = this.id;
  33404. serializationObject.type = this.getClassName();
  33405. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33406. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33407. }
  33408. serializationObject.position = this.position.asArray();
  33409. if (this.rotationQuaternion) {
  33410. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33411. }
  33412. else if (this.rotation) {
  33413. serializationObject.rotation = this.rotation.asArray();
  33414. }
  33415. serializationObject.scaling = this.scaling.asArray();
  33416. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33417. serializationObject.isEnabled = this.isEnabled(false);
  33418. serializationObject.isVisible = this.isVisible;
  33419. serializationObject.infiniteDistance = this.infiniteDistance;
  33420. serializationObject.pickable = this.isPickable;
  33421. serializationObject.receiveShadows = this.receiveShadows;
  33422. serializationObject.billboardMode = this.billboardMode;
  33423. serializationObject.visibility = this.visibility;
  33424. serializationObject.checkCollisions = this.checkCollisions;
  33425. serializationObject.isBlocker = this.isBlocker;
  33426. // Parent
  33427. if (this.parent) {
  33428. serializationObject.parentId = this.parent.id;
  33429. }
  33430. // Geometry
  33431. serializationObject.isUnIndexed = this.isUnIndexed;
  33432. var geometry = this._geometry;
  33433. if (geometry) {
  33434. var geometryId = geometry.id;
  33435. serializationObject.geometryId = geometryId;
  33436. // SubMeshes
  33437. serializationObject.subMeshes = [];
  33438. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33439. var subMesh = this.subMeshes[subIndex];
  33440. serializationObject.subMeshes.push({
  33441. materialIndex: subMesh.materialIndex,
  33442. verticesStart: subMesh.verticesStart,
  33443. verticesCount: subMesh.verticesCount,
  33444. indexStart: subMesh.indexStart,
  33445. indexCount: subMesh.indexCount
  33446. });
  33447. }
  33448. }
  33449. // Material
  33450. if (this.material) {
  33451. serializationObject.materialId = this.material.id;
  33452. }
  33453. else {
  33454. this.material = null;
  33455. }
  33456. // Morph targets
  33457. if (this.morphTargetManager) {
  33458. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33459. }
  33460. // Skeleton
  33461. if (this.skeleton) {
  33462. serializationObject.skeletonId = this.skeleton.id;
  33463. }
  33464. // Physics
  33465. //TODO implement correct serialization for physics impostors.
  33466. var impostor = this.getPhysicsImpostor();
  33467. if (impostor) {
  33468. serializationObject.physicsMass = impostor.getParam("mass");
  33469. serializationObject.physicsFriction = impostor.getParam("friction");
  33470. serializationObject.physicsRestitution = impostor.getParam("mass");
  33471. serializationObject.physicsImpostor = impostor.type;
  33472. }
  33473. // Metadata
  33474. if (this.metadata) {
  33475. serializationObject.metadata = this.metadata;
  33476. }
  33477. // Instances
  33478. serializationObject.instances = [];
  33479. for (var index = 0; index < this.instances.length; index++) {
  33480. var instance = this.instances[index];
  33481. var serializationInstance = {
  33482. name: instance.name,
  33483. id: instance.id,
  33484. position: instance.position.asArray(),
  33485. scaling: instance.scaling.asArray()
  33486. };
  33487. if (instance.rotationQuaternion) {
  33488. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33489. }
  33490. else if (instance.rotation) {
  33491. serializationInstance.rotation = instance.rotation.asArray();
  33492. }
  33493. serializationObject.instances.push(serializationInstance);
  33494. // Animations
  33495. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33496. serializationInstance.ranges = instance.serializeAnimationRanges();
  33497. }
  33498. //
  33499. // Animations
  33500. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33501. serializationObject.ranges = this.serializeAnimationRanges();
  33502. // Layer mask
  33503. serializationObject.layerMask = this.layerMask;
  33504. // Alpha
  33505. serializationObject.alphaIndex = this.alphaIndex;
  33506. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33507. // Overlay
  33508. serializationObject.overlayAlpha = this.overlayAlpha;
  33509. serializationObject.overlayColor = this.overlayColor.asArray();
  33510. serializationObject.renderOverlay = this.renderOverlay;
  33511. // Fog
  33512. serializationObject.applyFog = this.applyFog;
  33513. // Action Manager
  33514. if (this.actionManager) {
  33515. serializationObject.actions = this.actionManager.serialize(this.name);
  33516. }
  33517. };
  33518. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33519. if (!this.geometry) {
  33520. return;
  33521. }
  33522. this._markSubMeshesAsAttributesDirty();
  33523. var morphTargetManager = this._morphTargetManager;
  33524. if (morphTargetManager && morphTargetManager.vertexCount) {
  33525. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33526. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33527. this.morphTargetManager = null;
  33528. return;
  33529. }
  33530. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33531. var morphTarget = morphTargetManager.getActiveTarget(index);
  33532. var positions = morphTarget.getPositions();
  33533. if (!positions) {
  33534. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33535. return;
  33536. }
  33537. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33538. var normals = morphTarget.getNormals();
  33539. if (normals) {
  33540. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33541. }
  33542. var tangents = morphTarget.getTangents();
  33543. if (tangents) {
  33544. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33545. }
  33546. }
  33547. }
  33548. else {
  33549. var index = 0;
  33550. // Positions
  33551. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33552. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33553. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33554. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33555. }
  33556. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33557. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33558. }
  33559. index++;
  33560. }
  33561. }
  33562. };
  33563. // Statics
  33564. /**
  33565. * Returns a new Mesh object parsed from the source provided.
  33566. * The parameter `parsedMesh` is the source.
  33567. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33568. */
  33569. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33570. var mesh;
  33571. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33572. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33573. }
  33574. else {
  33575. mesh = new Mesh(parsedMesh.name, scene);
  33576. }
  33577. mesh.id = parsedMesh.id;
  33578. if (BABYLON.Tags) {
  33579. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33580. }
  33581. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33582. if (parsedMesh.metadata !== undefined) {
  33583. mesh.metadata = parsedMesh.metadata;
  33584. }
  33585. if (parsedMesh.rotationQuaternion) {
  33586. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33587. }
  33588. else if (parsedMesh.rotation) {
  33589. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33590. }
  33591. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33592. if (parsedMesh.localMatrix) {
  33593. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33594. }
  33595. else if (parsedMesh.pivotMatrix) {
  33596. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33597. }
  33598. mesh.setEnabled(parsedMesh.isEnabled);
  33599. mesh.isVisible = parsedMesh.isVisible;
  33600. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33601. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33602. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33603. if (parsedMesh.applyFog !== undefined) {
  33604. mesh.applyFog = parsedMesh.applyFog;
  33605. }
  33606. if (parsedMesh.pickable !== undefined) {
  33607. mesh.isPickable = parsedMesh.pickable;
  33608. }
  33609. if (parsedMesh.alphaIndex !== undefined) {
  33610. mesh.alphaIndex = parsedMesh.alphaIndex;
  33611. }
  33612. mesh.receiveShadows = parsedMesh.receiveShadows;
  33613. mesh.billboardMode = parsedMesh.billboardMode;
  33614. if (parsedMesh.visibility !== undefined) {
  33615. mesh.visibility = parsedMesh.visibility;
  33616. }
  33617. mesh.checkCollisions = parsedMesh.checkCollisions;
  33618. if (parsedMesh.isBlocker !== undefined) {
  33619. mesh.isBlocker = parsedMesh.isBlocker;
  33620. }
  33621. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33622. // freezeWorldMatrix
  33623. if (parsedMesh.freezeWorldMatrix) {
  33624. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33625. }
  33626. // Parent
  33627. if (parsedMesh.parentId) {
  33628. mesh._waitingParentId = parsedMesh.parentId;
  33629. }
  33630. // Actions
  33631. if (parsedMesh.actions !== undefined) {
  33632. mesh._waitingActions = parsedMesh.actions;
  33633. }
  33634. // Overlay
  33635. if (parsedMesh.overlayAlpha !== undefined) {
  33636. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33637. }
  33638. if (parsedMesh.overlayColor !== undefined) {
  33639. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33640. }
  33641. if (parsedMesh.renderOverlay !== undefined) {
  33642. mesh.renderOverlay = parsedMesh.renderOverlay;
  33643. }
  33644. // Geometry
  33645. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33646. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33647. if (parsedMesh.delayLoadingFile) {
  33648. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33649. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33650. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33651. if (parsedMesh._binaryInfo) {
  33652. mesh._binaryInfo = parsedMesh._binaryInfo;
  33653. }
  33654. mesh._delayInfo = [];
  33655. if (parsedMesh.hasUVs) {
  33656. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33657. }
  33658. if (parsedMesh.hasUVs2) {
  33659. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33660. }
  33661. if (parsedMesh.hasUVs3) {
  33662. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33663. }
  33664. if (parsedMesh.hasUVs4) {
  33665. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33666. }
  33667. if (parsedMesh.hasUVs5) {
  33668. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33669. }
  33670. if (parsedMesh.hasUVs6) {
  33671. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33672. }
  33673. if (parsedMesh.hasColors) {
  33674. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33675. }
  33676. if (parsedMesh.hasMatricesIndices) {
  33677. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33678. }
  33679. if (parsedMesh.hasMatricesWeights) {
  33680. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33681. }
  33682. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33683. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33684. mesh._checkDelayState();
  33685. }
  33686. }
  33687. else {
  33688. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33689. }
  33690. // Material
  33691. if (parsedMesh.materialId) {
  33692. mesh.setMaterialByID(parsedMesh.materialId);
  33693. }
  33694. else {
  33695. mesh.material = null;
  33696. }
  33697. // Morph targets
  33698. if (parsedMesh.morphTargetManagerId > -1) {
  33699. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33700. }
  33701. // Skeleton
  33702. if (parsedMesh.skeletonId > -1) {
  33703. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33704. if (parsedMesh.numBoneInfluencers) {
  33705. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33706. }
  33707. }
  33708. // Animations
  33709. if (parsedMesh.animations) {
  33710. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33711. var parsedAnimation = parsedMesh.animations[animationIndex];
  33712. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33713. }
  33714. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33715. }
  33716. if (parsedMesh.autoAnimate) {
  33717. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33718. }
  33719. // Layer Mask
  33720. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33721. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33722. }
  33723. else {
  33724. mesh.layerMask = 0x0FFFFFFF;
  33725. }
  33726. // Physics
  33727. if (parsedMesh.physicsImpostor) {
  33728. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33729. mass: parsedMesh.physicsMass,
  33730. friction: parsedMesh.physicsFriction,
  33731. restitution: parsedMesh.physicsRestitution
  33732. }, scene);
  33733. }
  33734. // Instances
  33735. if (parsedMesh.instances) {
  33736. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33737. var parsedInstance = parsedMesh.instances[index];
  33738. var instance = mesh.createInstance(parsedInstance.name);
  33739. if (parsedInstance.id) {
  33740. instance.id = parsedInstance.id;
  33741. }
  33742. if (BABYLON.Tags) {
  33743. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33744. }
  33745. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33746. if (parsedInstance.parentId) {
  33747. instance._waitingParentId = parsedInstance.parentId;
  33748. }
  33749. if (parsedInstance.rotationQuaternion) {
  33750. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33751. }
  33752. else if (parsedInstance.rotation) {
  33753. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33754. }
  33755. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33756. instance.checkCollisions = mesh.checkCollisions;
  33757. if (parsedMesh.animations) {
  33758. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33759. parsedAnimation = parsedMesh.animations[animationIndex];
  33760. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33761. }
  33762. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33763. if (parsedMesh.autoAnimate) {
  33764. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33765. }
  33766. }
  33767. }
  33768. }
  33769. return mesh;
  33770. };
  33771. /**
  33772. * Creates a ribbon mesh.
  33773. * Please consider using the same method from the MeshBuilder class instead.
  33774. * 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.
  33775. *
  33776. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33777. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33778. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33779. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33780. * 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.
  33781. * 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.
  33782. * 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
  33783. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33784. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33785. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33786. */
  33787. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33788. if (closeArray === void 0) { closeArray = false; }
  33789. if (updatable === void 0) { updatable = false; }
  33790. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33791. pathArray: pathArray,
  33792. closeArray: closeArray,
  33793. closePath: closePath,
  33794. offset: offset,
  33795. updatable: updatable,
  33796. sideOrientation: sideOrientation,
  33797. instance: instance
  33798. }, scene);
  33799. };
  33800. /**
  33801. * Creates a plane polygonal mesh. By default, this is a disc.
  33802. * Please consider using the same method from the MeshBuilder class instead.
  33803. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33804. * 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.
  33805. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33806. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33808. */
  33809. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33810. if (scene === void 0) { scene = null; }
  33811. var options = {
  33812. radius: radius,
  33813. tessellation: tessellation,
  33814. sideOrientation: sideOrientation,
  33815. updatable: updatable
  33816. };
  33817. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33818. };
  33819. /**
  33820. * Creates a box mesh.
  33821. * Please consider using the same method from the MeshBuilder class instead.
  33822. * The parameter `size` sets the size (float) of each box side (default 1).
  33823. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33824. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33825. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33826. */
  33827. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33828. if (scene === void 0) { scene = null; }
  33829. var options = {
  33830. size: size,
  33831. sideOrientation: sideOrientation,
  33832. updatable: updatable
  33833. };
  33834. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33835. };
  33836. /**
  33837. * Creates a sphere mesh.
  33838. * Please consider using the same method from the MeshBuilder class instead.
  33839. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33840. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33841. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33842. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33843. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33844. */
  33845. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33846. var options = {
  33847. segments: segments,
  33848. diameterX: diameter,
  33849. diameterY: diameter,
  33850. diameterZ: diameter,
  33851. sideOrientation: sideOrientation,
  33852. updatable: updatable
  33853. };
  33854. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33855. };
  33856. /**
  33857. * Creates a cylinder or a cone mesh.
  33858. * Please consider using the same method from the MeshBuilder class instead.
  33859. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33860. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33861. * 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.
  33862. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33863. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33864. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33865. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33866. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33867. */
  33868. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33869. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33870. if (scene !== undefined) {
  33871. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33872. updatable = scene;
  33873. }
  33874. scene = subdivisions;
  33875. subdivisions = 1;
  33876. }
  33877. var options = {
  33878. height: height,
  33879. diameterTop: diameterTop,
  33880. diameterBottom: diameterBottom,
  33881. tessellation: tessellation,
  33882. subdivisions: subdivisions,
  33883. sideOrientation: sideOrientation,
  33884. updatable: updatable
  33885. };
  33886. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33887. };
  33888. // Torus (Code from SharpDX.org)
  33889. /**
  33890. * Creates a torus mesh.
  33891. * Please consider using the same method from the MeshBuilder class instead.
  33892. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33893. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33894. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33895. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33896. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33897. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33898. */
  33899. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33900. var options = {
  33901. diameter: diameter,
  33902. thickness: thickness,
  33903. tessellation: tessellation,
  33904. sideOrientation: sideOrientation,
  33905. updatable: updatable
  33906. };
  33907. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33908. };
  33909. /**
  33910. * Creates a torus knot mesh.
  33911. * Please consider using the same method from the MeshBuilder class instead.
  33912. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33913. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33914. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33915. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33916. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33917. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33918. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33919. */
  33920. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33921. var options = {
  33922. radius: radius,
  33923. tube: tube,
  33924. radialSegments: radialSegments,
  33925. tubularSegments: tubularSegments,
  33926. p: p,
  33927. q: q,
  33928. sideOrientation: sideOrientation,
  33929. updatable: updatable
  33930. };
  33931. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33932. };
  33933. /**
  33934. * Creates a line mesh.
  33935. * Please consider using the same method from the MeshBuilder class instead.
  33936. * 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.
  33937. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33938. * The parameter `points` is an array successive Vector3.
  33939. * 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
  33940. * When updating an instance, remember that only point positions can change, not the number of points.
  33941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33942. */
  33943. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33944. if (scene === void 0) { scene = null; }
  33945. if (updatable === void 0) { updatable = false; }
  33946. if (instance === void 0) { instance = null; }
  33947. var options = {
  33948. points: points,
  33949. updatable: updatable,
  33950. instance: instance
  33951. };
  33952. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33953. };
  33954. /**
  33955. * Creates a dashed line mesh.
  33956. * Please consider using the same method from the MeshBuilder class instead.
  33957. * 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.
  33958. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33959. * The parameter `points` is an array successive Vector3.
  33960. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33961. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33962. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33963. * 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
  33964. * When updating an instance, remember that only point positions can change, not the number of points.
  33965. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33966. */
  33967. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33968. if (scene === void 0) { scene = null; }
  33969. var options = {
  33970. points: points,
  33971. dashSize: dashSize,
  33972. gapSize: gapSize,
  33973. dashNb: dashNb,
  33974. updatable: updatable,
  33975. instance: instance
  33976. };
  33977. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33978. };
  33979. /**
  33980. * Creates a polygon mesh.
  33981. * Please consider using the same method from the MeshBuilder class instead.
  33982. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33983. * 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.
  33984. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33986. * Remember you can only change the shape positions, not their number when updating a polygon.
  33987. */
  33988. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33989. var options = {
  33990. shape: shape,
  33991. holes: holes,
  33992. updatable: updatable,
  33993. sideOrientation: sideOrientation
  33994. };
  33995. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33996. };
  33997. /**
  33998. * Creates an extruded polygon mesh, with depth in the Y direction.
  33999. * Please consider using the same method from the MeshBuilder class instead.
  34000. */
  34001. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34002. var options = {
  34003. shape: shape,
  34004. holes: holes,
  34005. depth: depth,
  34006. updatable: updatable,
  34007. sideOrientation: sideOrientation
  34008. };
  34009. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34010. };
  34011. /**
  34012. * Creates an extruded shape mesh.
  34013. * 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.
  34014. * Please consider using the same method from the MeshBuilder class instead.
  34015. *
  34016. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34017. * 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
  34018. * extruded along the Z axis.
  34019. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34020. * 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.
  34021. * The parameter `scale` (float, default 1) is the value to scale the shape.
  34022. * 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
  34023. * 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
  34024. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34025. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34026. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34028. */
  34029. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34030. if (scene === void 0) { scene = null; }
  34031. var options = {
  34032. shape: shape,
  34033. path: path,
  34034. scale: scale,
  34035. rotation: rotation,
  34036. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34037. sideOrientation: sideOrientation,
  34038. instance: instance,
  34039. updatable: updatable
  34040. };
  34041. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34042. };
  34043. /**
  34044. * Creates an custom extruded shape mesh.
  34045. * 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.
  34046. * Please consider using the same method from the MeshBuilder class instead.
  34047. *
  34048. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34049. * 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
  34050. * extruded along the Z axis.
  34051. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34052. * 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
  34053. * and the distance of this point from the begining of the path :
  34054. * ```javascript
  34055. * var rotationFunction = function(i, distance) {
  34056. * // do things
  34057. * return rotationValue; }
  34058. * ```
  34059. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34060. * 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
  34061. * and the distance of this point from the begining of the path :
  34062. * ```javascript
  34063. * var scaleFunction = function(i, distance) {
  34064. * // do things
  34065. * return scaleValue;}
  34066. * ```
  34067. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34068. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34069. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34070. * 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
  34071. * 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
  34072. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34074. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34076. */
  34077. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34078. var options = {
  34079. shape: shape,
  34080. path: path,
  34081. scaleFunction: scaleFunction,
  34082. rotationFunction: rotationFunction,
  34083. ribbonCloseArray: ribbonCloseArray,
  34084. ribbonClosePath: ribbonClosePath,
  34085. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34086. sideOrientation: sideOrientation,
  34087. instance: instance,
  34088. updatable: updatable
  34089. };
  34090. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34091. };
  34092. /**
  34093. * Creates lathe mesh.
  34094. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34095. * Please consider using the same method from the MeshBuilder class instead.
  34096. * 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
  34097. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34098. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34099. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34100. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34101. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34102. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34103. */
  34104. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34105. var options = {
  34106. shape: shape,
  34107. radius: radius,
  34108. tessellation: tessellation,
  34109. sideOrientation: sideOrientation,
  34110. updatable: updatable
  34111. };
  34112. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34113. };
  34114. /**
  34115. * Creates a plane mesh.
  34116. * Please consider using the same method from the MeshBuilder class instead.
  34117. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34119. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34120. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34121. */
  34122. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34123. var options = {
  34124. size: size,
  34125. width: size,
  34126. height: size,
  34127. sideOrientation: sideOrientation,
  34128. updatable: updatable
  34129. };
  34130. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34131. };
  34132. /**
  34133. * Creates a ground mesh.
  34134. * Please consider using the same method from the MeshBuilder class instead.
  34135. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34136. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34137. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34138. */
  34139. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34140. var options = {
  34141. width: width,
  34142. height: height,
  34143. subdivisions: subdivisions,
  34144. updatable: updatable
  34145. };
  34146. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34147. };
  34148. /**
  34149. * Creates a tiled ground mesh.
  34150. * Please consider using the same method from the MeshBuilder class instead.
  34151. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34152. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34153. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34154. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34155. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34156. * numbers of subdivisions on the ground width and height of each tile.
  34157. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34158. */
  34159. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34160. var options = {
  34161. xmin: xmin,
  34162. zmin: zmin,
  34163. xmax: xmax,
  34164. zmax: zmax,
  34165. subdivisions: subdivisions,
  34166. precision: precision,
  34167. updatable: updatable
  34168. };
  34169. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34170. };
  34171. /**
  34172. * Creates a ground mesh from a height map.
  34173. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34174. * Please consider using the same method from the MeshBuilder class instead.
  34175. * The parameter `url` sets the URL of the height map image resource.
  34176. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34177. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34178. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34179. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34180. * 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).
  34181. * This function is passed the newly built mesh :
  34182. * ```javascript
  34183. * function(mesh) { // do things
  34184. * return; }
  34185. * ```
  34186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34187. */
  34188. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34189. var options = {
  34190. width: width,
  34191. height: height,
  34192. subdivisions: subdivisions,
  34193. minHeight: minHeight,
  34194. maxHeight: maxHeight,
  34195. updatable: updatable,
  34196. onReady: onReady
  34197. };
  34198. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34199. };
  34200. /**
  34201. * Creates a tube mesh.
  34202. * 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.
  34203. * Please consider using the same method from the MeshBuilder class instead.
  34204. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34205. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34206. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34207. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34208. * 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.
  34209. * It must return a radius value (positive float) :
  34210. * ```javascript
  34211. * var radiusFunction = function(i, distance) {
  34212. * // do things
  34213. * return radius; }
  34214. * ```
  34215. * 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
  34216. * 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
  34217. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34218. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34219. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34220. */
  34221. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34222. var options = {
  34223. path: path,
  34224. radius: radius,
  34225. tessellation: tessellation,
  34226. radiusFunction: radiusFunction,
  34227. arc: 1,
  34228. cap: cap,
  34229. updatable: updatable,
  34230. sideOrientation: sideOrientation,
  34231. instance: instance
  34232. };
  34233. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34234. };
  34235. /**
  34236. * Creates a polyhedron mesh.
  34237. * Please consider using the same method from the MeshBuilder class instead.
  34238. * 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
  34239. * to choose the wanted type.
  34240. * The parameter `size` (positive float, default 1) sets the polygon size.
  34241. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34242. * 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`.
  34243. * 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
  34244. * 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)`).
  34245. * 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
  34246. * 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.
  34247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34248. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34250. */
  34251. Mesh.CreatePolyhedron = function (name, options, scene) {
  34252. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34253. };
  34254. /**
  34255. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34256. * Please consider using the same method from the MeshBuilder class instead.
  34257. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34258. * 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`).
  34259. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34260. * 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.
  34261. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34262. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34263. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34264. */
  34265. Mesh.CreateIcoSphere = function (name, options, scene) {
  34266. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34267. };
  34268. /**
  34269. * Creates a decal mesh.
  34270. * Please consider using the same method from the MeshBuilder class instead.
  34271. * 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.
  34272. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34273. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34274. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34275. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34276. */
  34277. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34278. var options = {
  34279. position: position,
  34280. normal: normal,
  34281. size: size,
  34282. angle: angle
  34283. };
  34284. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34285. };
  34286. // Skeletons
  34287. /**
  34288. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34289. */
  34290. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34291. if (!this._sourcePositions) {
  34292. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34293. if (!source) {
  34294. return this._sourcePositions;
  34295. }
  34296. this._sourcePositions = new Float32Array(source);
  34297. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34298. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34299. }
  34300. }
  34301. return this._sourcePositions;
  34302. };
  34303. /**
  34304. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34305. */
  34306. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34307. if (!this._sourceNormals) {
  34308. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34309. if (!source) {
  34310. return this._sourceNormals;
  34311. }
  34312. this._sourceNormals = new Float32Array(source);
  34313. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34314. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34315. }
  34316. }
  34317. return this._sourceNormals;
  34318. };
  34319. /**
  34320. * Updates the vertex buffer by applying transformation from the bones.
  34321. * Returns the Mesh.
  34322. *
  34323. * @param {skeleton} skeleton to apply
  34324. */
  34325. Mesh.prototype.applySkeleton = function (skeleton) {
  34326. if (!this.geometry) {
  34327. return this;
  34328. }
  34329. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34330. return this;
  34331. }
  34332. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34333. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34334. return this;
  34335. }
  34336. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34337. return this;
  34338. }
  34339. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34340. return this;
  34341. }
  34342. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34343. return this;
  34344. }
  34345. if (!this._sourcePositions) {
  34346. var submeshes = this.subMeshes.slice();
  34347. this.setPositionsForCPUSkinning();
  34348. this.subMeshes = submeshes;
  34349. }
  34350. if (!this._sourceNormals) {
  34351. this.setNormalsForCPUSkinning();
  34352. }
  34353. // positionsData checks for not being Float32Array will only pass at most once
  34354. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34355. if (!positionsData) {
  34356. return this;
  34357. }
  34358. if (!(positionsData instanceof Float32Array)) {
  34359. positionsData = new Float32Array(positionsData);
  34360. }
  34361. // normalsData checks for not being Float32Array will only pass at most once
  34362. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34363. if (!normalsData) {
  34364. return this;
  34365. }
  34366. if (!(normalsData instanceof Float32Array)) {
  34367. normalsData = new Float32Array(normalsData);
  34368. }
  34369. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34370. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34371. if (!matricesWeightsData || !matricesIndicesData) {
  34372. return this;
  34373. }
  34374. var needExtras = this.numBoneInfluencers > 4;
  34375. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34376. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34377. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34378. var tempVector3 = BABYLON.Vector3.Zero();
  34379. var finalMatrix = new BABYLON.Matrix();
  34380. var tempMatrix = new BABYLON.Matrix();
  34381. var matWeightIdx = 0;
  34382. var inf;
  34383. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34384. var weight;
  34385. for (inf = 0; inf < 4; inf++) {
  34386. weight = matricesWeightsData[matWeightIdx + inf];
  34387. if (weight > 0) {
  34388. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34389. finalMatrix.addToSelf(tempMatrix);
  34390. }
  34391. else
  34392. break;
  34393. }
  34394. if (needExtras) {
  34395. for (inf = 0; inf < 4; inf++) {
  34396. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34397. if (weight > 0) {
  34398. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34399. finalMatrix.addToSelf(tempMatrix);
  34400. }
  34401. else
  34402. break;
  34403. }
  34404. }
  34405. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34406. tempVector3.toArray(positionsData, index);
  34407. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34408. tempVector3.toArray(normalsData, index);
  34409. finalMatrix.reset();
  34410. }
  34411. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34412. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34413. return this;
  34414. };
  34415. // Tools
  34416. /**
  34417. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34418. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34419. */
  34420. Mesh.MinMax = function (meshes) {
  34421. var minVector = null;
  34422. var maxVector = null;
  34423. meshes.forEach(function (mesh, index, array) {
  34424. var boundingInfo = mesh.getBoundingInfo();
  34425. var boundingBox = boundingInfo.boundingBox;
  34426. if (!minVector || !maxVector) {
  34427. minVector = boundingBox.minimumWorld;
  34428. maxVector = boundingBox.maximumWorld;
  34429. }
  34430. else {
  34431. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34432. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34433. }
  34434. });
  34435. if (!minVector || !maxVector) {
  34436. return {
  34437. min: BABYLON.Vector3.Zero(),
  34438. max: BABYLON.Vector3.Zero()
  34439. };
  34440. }
  34441. return {
  34442. min: minVector,
  34443. max: maxVector
  34444. };
  34445. };
  34446. /**
  34447. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34448. */
  34449. Mesh.Center = function (meshesOrMinMaxVector) {
  34450. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34451. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34452. };
  34453. /**
  34454. * Merge the array of meshes into a single mesh for performance reasons.
  34455. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34456. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34457. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34458. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34459. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34460. */
  34461. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34462. if (disposeSource === void 0) { disposeSource = true; }
  34463. var index;
  34464. if (!allow32BitsIndices) {
  34465. var totalVertices = 0;
  34466. // Counting vertices
  34467. for (index = 0; index < meshes.length; index++) {
  34468. if (meshes[index]) {
  34469. totalVertices += meshes[index].getTotalVertices();
  34470. if (totalVertices > 65536) {
  34471. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34472. return null;
  34473. }
  34474. }
  34475. }
  34476. }
  34477. // Merge
  34478. var vertexData = null;
  34479. var otherVertexData;
  34480. var indiceArray = new Array();
  34481. var source = null;
  34482. for (index = 0; index < meshes.length; index++) {
  34483. if (meshes[index]) {
  34484. meshes[index].computeWorldMatrix(true);
  34485. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34486. otherVertexData.transform(meshes[index].getWorldMatrix());
  34487. if (vertexData) {
  34488. vertexData.merge(otherVertexData);
  34489. }
  34490. else {
  34491. vertexData = otherVertexData;
  34492. source = meshes[index];
  34493. }
  34494. if (subdivideWithSubMeshes) {
  34495. indiceArray.push(meshes[index].getTotalIndices());
  34496. }
  34497. }
  34498. }
  34499. source = source;
  34500. if (!meshSubclass) {
  34501. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34502. }
  34503. vertexData.applyToMesh(meshSubclass);
  34504. // Setting properties
  34505. meshSubclass.material = source.material;
  34506. meshSubclass.checkCollisions = source.checkCollisions;
  34507. // Cleaning
  34508. if (disposeSource) {
  34509. for (index = 0; index < meshes.length; index++) {
  34510. if (meshes[index]) {
  34511. meshes[index].dispose();
  34512. }
  34513. }
  34514. }
  34515. // Subdivide
  34516. if (subdivideWithSubMeshes) {
  34517. //-- removal of global submesh
  34518. meshSubclass.releaseSubMeshes();
  34519. index = 0;
  34520. var offset = 0;
  34521. //-- apply subdivision according to index table
  34522. while (index < indiceArray.length) {
  34523. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34524. offset += indiceArray[index];
  34525. index++;
  34526. }
  34527. }
  34528. return meshSubclass;
  34529. };
  34530. // Consts
  34531. Mesh._FRONTSIDE = 0;
  34532. Mesh._BACKSIDE = 1;
  34533. Mesh._DOUBLESIDE = 2;
  34534. Mesh._DEFAULTSIDE = 0;
  34535. Mesh._NO_CAP = 0;
  34536. Mesh._CAP_START = 1;
  34537. Mesh._CAP_END = 2;
  34538. Mesh._CAP_ALL = 3;
  34539. return Mesh;
  34540. }(BABYLON.AbstractMesh));
  34541. BABYLON.Mesh = Mesh;
  34542. })(BABYLON || (BABYLON = {}));
  34543. //# sourceMappingURL=babylon.mesh.js.map
  34544. var BABYLON;
  34545. (function (BABYLON) {
  34546. var BaseSubMesh = /** @class */ (function () {
  34547. function BaseSubMesh() {
  34548. }
  34549. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34550. get: function () {
  34551. return this._materialEffect;
  34552. },
  34553. enumerable: true,
  34554. configurable: true
  34555. });
  34556. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34557. if (defines === void 0) { defines = null; }
  34558. if (this._materialEffect === effect) {
  34559. if (!effect) {
  34560. this._materialDefines = null;
  34561. }
  34562. return;
  34563. }
  34564. this._materialDefines = defines;
  34565. this._materialEffect = effect;
  34566. };
  34567. return BaseSubMesh;
  34568. }());
  34569. BABYLON.BaseSubMesh = BaseSubMesh;
  34570. var SubMesh = /** @class */ (function (_super) {
  34571. __extends(SubMesh, _super);
  34572. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34573. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34574. var _this = _super.call(this) || this;
  34575. _this.materialIndex = materialIndex;
  34576. _this.verticesStart = verticesStart;
  34577. _this.verticesCount = verticesCount;
  34578. _this.indexStart = indexStart;
  34579. _this.indexCount = indexCount;
  34580. _this._renderId = 0;
  34581. _this._mesh = mesh;
  34582. _this._renderingMesh = renderingMesh || mesh;
  34583. mesh.subMeshes.push(_this);
  34584. _this._trianglePlanes = [];
  34585. _this._id = mesh.subMeshes.length - 1;
  34586. if (createBoundingBox) {
  34587. _this.refreshBoundingInfo();
  34588. mesh.computeWorldMatrix(true);
  34589. }
  34590. return _this;
  34591. }
  34592. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34593. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34594. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34595. };
  34596. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34597. get: function () {
  34598. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34599. },
  34600. enumerable: true,
  34601. configurable: true
  34602. });
  34603. /**
  34604. * Returns the submesh BoudingInfo object.
  34605. */
  34606. SubMesh.prototype.getBoundingInfo = function () {
  34607. if (this.IsGlobal) {
  34608. return this._mesh.getBoundingInfo();
  34609. }
  34610. return this._boundingInfo;
  34611. };
  34612. /**
  34613. * Sets the submesh BoundingInfo.
  34614. * Return the SubMesh.
  34615. */
  34616. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34617. this._boundingInfo = boundingInfo;
  34618. return this;
  34619. };
  34620. /**
  34621. * Returns the mesh of the current submesh.
  34622. */
  34623. SubMesh.prototype.getMesh = function () {
  34624. return this._mesh;
  34625. };
  34626. /**
  34627. * Returns the rendering mesh of the submesh.
  34628. */
  34629. SubMesh.prototype.getRenderingMesh = function () {
  34630. return this._renderingMesh;
  34631. };
  34632. /**
  34633. * Returns the submesh material.
  34634. */
  34635. SubMesh.prototype.getMaterial = function () {
  34636. var rootMaterial = this._renderingMesh.material;
  34637. if (rootMaterial === null || rootMaterial === undefined) {
  34638. return this._mesh.getScene().defaultMaterial;
  34639. }
  34640. else if (rootMaterial.getSubMaterial) {
  34641. var multiMaterial = rootMaterial;
  34642. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34643. if (this._currentMaterial !== effectiveMaterial) {
  34644. this._currentMaterial = effectiveMaterial;
  34645. this._materialDefines = null;
  34646. }
  34647. return effectiveMaterial;
  34648. }
  34649. return rootMaterial;
  34650. };
  34651. // Methods
  34652. /**
  34653. * Sets a new updated BoundingInfo object to the submesh.
  34654. * Returns the SubMesh.
  34655. */
  34656. SubMesh.prototype.refreshBoundingInfo = function () {
  34657. this._lastColliderWorldVertices = null;
  34658. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34659. return this;
  34660. }
  34661. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34662. if (!data) {
  34663. this._boundingInfo = this._mesh.getBoundingInfo();
  34664. return this;
  34665. }
  34666. var indices = this._renderingMesh.getIndices();
  34667. var extend;
  34668. //is this the only submesh?
  34669. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34670. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34671. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34672. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34673. }
  34674. else {
  34675. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34676. }
  34677. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34678. return this;
  34679. };
  34680. SubMesh.prototype._checkCollision = function (collider) {
  34681. var boundingInfo = this.getBoundingInfo();
  34682. return boundingInfo._checkCollision(collider);
  34683. };
  34684. /**
  34685. * Updates the submesh BoundingInfo.
  34686. * Returns the Submesh.
  34687. */
  34688. SubMesh.prototype.updateBoundingInfo = function (world) {
  34689. var boundingInfo = this.getBoundingInfo();
  34690. if (!boundingInfo) {
  34691. this.refreshBoundingInfo();
  34692. boundingInfo = this.getBoundingInfo();
  34693. }
  34694. boundingInfo.update(world);
  34695. return this;
  34696. };
  34697. /**
  34698. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34699. * Boolean returned.
  34700. */
  34701. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34702. var boundingInfo = this.getBoundingInfo();
  34703. if (!boundingInfo) {
  34704. return false;
  34705. }
  34706. return boundingInfo.isInFrustum(frustumPlanes);
  34707. };
  34708. /**
  34709. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34710. * Boolean returned.
  34711. */
  34712. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34713. var boundingInfo = this.getBoundingInfo();
  34714. if (!boundingInfo) {
  34715. return false;
  34716. }
  34717. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34718. };
  34719. /**
  34720. * Renders the submesh.
  34721. * Returns it.
  34722. */
  34723. SubMesh.prototype.render = function (enableAlphaMode) {
  34724. this._renderingMesh.render(this, enableAlphaMode);
  34725. return this;
  34726. };
  34727. /**
  34728. * Returns a new Index Buffer.
  34729. * Type returned : WebGLBuffer.
  34730. */
  34731. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34732. if (!this._linesIndexBuffer) {
  34733. var linesIndices = [];
  34734. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34735. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34736. }
  34737. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34738. this.linesIndexCount = linesIndices.length;
  34739. }
  34740. return this._linesIndexBuffer;
  34741. };
  34742. /**
  34743. * True is the passed Ray intersects the submesh bounding box.
  34744. * Boolean returned.
  34745. */
  34746. SubMesh.prototype.canIntersects = function (ray) {
  34747. var boundingInfo = this.getBoundingInfo();
  34748. if (!boundingInfo) {
  34749. return false;
  34750. }
  34751. return ray.intersectsBox(boundingInfo.boundingBox);
  34752. };
  34753. /**
  34754. * Returns an object IntersectionInfo.
  34755. */
  34756. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34757. var intersectInfo = null;
  34758. var material = this.getMaterial();
  34759. if (!material) {
  34760. return null;
  34761. }
  34762. switch (material.fillMode) {
  34763. case BABYLON.Material.PointListDrawMode:
  34764. case BABYLON.Material.LineListDrawMode:
  34765. case BABYLON.Material.LineLoopDrawMode:
  34766. case BABYLON.Material.LineStripDrawMode:
  34767. case BABYLON.Material.TriangleFanDrawMode:
  34768. case BABYLON.Material.TriangleStripDrawMode:
  34769. return null;
  34770. }
  34771. // LineMesh first as it's also a Mesh...
  34772. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34773. var lineMesh = this._mesh;
  34774. // Line test
  34775. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34776. var p0 = positions[indices[index]];
  34777. var p1 = positions[indices[index + 1]];
  34778. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34779. if (length < 0) {
  34780. continue;
  34781. }
  34782. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34783. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34784. if (fastCheck) {
  34785. break;
  34786. }
  34787. }
  34788. }
  34789. }
  34790. else {
  34791. // Triangles test
  34792. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34793. var p0 = positions[indices[index]];
  34794. var p1 = positions[indices[index + 1]];
  34795. var p2 = positions[indices[index + 2]];
  34796. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34797. if (currentIntersectInfo) {
  34798. if (currentIntersectInfo.distance < 0) {
  34799. continue;
  34800. }
  34801. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34802. intersectInfo = currentIntersectInfo;
  34803. intersectInfo.faceId = index / 3;
  34804. if (fastCheck) {
  34805. break;
  34806. }
  34807. }
  34808. }
  34809. }
  34810. }
  34811. return intersectInfo;
  34812. };
  34813. SubMesh.prototype._rebuild = function () {
  34814. if (this._linesIndexBuffer) {
  34815. this._linesIndexBuffer = null;
  34816. }
  34817. };
  34818. // Clone
  34819. /**
  34820. * Creates a new Submesh from the passed Mesh.
  34821. */
  34822. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34823. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34824. if (!this.IsGlobal) {
  34825. var boundingInfo = this.getBoundingInfo();
  34826. if (!boundingInfo) {
  34827. return result;
  34828. }
  34829. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34830. }
  34831. return result;
  34832. };
  34833. // Dispose
  34834. /**
  34835. * Disposes the Submesh.
  34836. * Returns nothing.
  34837. */
  34838. SubMesh.prototype.dispose = function () {
  34839. if (this._linesIndexBuffer) {
  34840. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34841. this._linesIndexBuffer = null;
  34842. }
  34843. // Remove from mesh
  34844. var index = this._mesh.subMeshes.indexOf(this);
  34845. this._mesh.subMeshes.splice(index, 1);
  34846. };
  34847. // Statics
  34848. /**
  34849. * Creates a new Submesh from the passed parameters :
  34850. * - materialIndex (integer) : the index of the main mesh material.
  34851. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34852. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34853. * - mesh (Mesh) : the main mesh to create the submesh from.
  34854. * - renderingMesh (optional Mesh) : rendering mesh.
  34855. */
  34856. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34857. var minVertexIndex = Number.MAX_VALUE;
  34858. var maxVertexIndex = -Number.MAX_VALUE;
  34859. renderingMesh = (renderingMesh || mesh);
  34860. var indices = renderingMesh.getIndices();
  34861. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34862. var vertexIndex = indices[index];
  34863. if (vertexIndex < minVertexIndex)
  34864. minVertexIndex = vertexIndex;
  34865. if (vertexIndex > maxVertexIndex)
  34866. maxVertexIndex = vertexIndex;
  34867. }
  34868. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34869. };
  34870. return SubMesh;
  34871. }(BaseSubMesh));
  34872. BABYLON.SubMesh = SubMesh;
  34873. })(BABYLON || (BABYLON = {}));
  34874. //# sourceMappingURL=babylon.subMesh.js.map
  34875. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34876. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34877. s = arguments[i];
  34878. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34879. t[p] = s[p];
  34880. }
  34881. return t;
  34882. };
  34883. var BABYLON;
  34884. (function (BABYLON) {
  34885. /**
  34886. * Manages the defines for the Material
  34887. */
  34888. var MaterialDefines = /** @class */ (function () {
  34889. function MaterialDefines() {
  34890. this._isDirty = true;
  34891. /** @hidden */
  34892. this._areLightsDirty = true;
  34893. /** @hidden */
  34894. this._areAttributesDirty = true;
  34895. /** @hidden */
  34896. this._areTexturesDirty = true;
  34897. /** @hidden */
  34898. this._areFresnelDirty = true;
  34899. /** @hidden */
  34900. this._areMiscDirty = true;
  34901. /** @hidden */
  34902. this._areImageProcessingDirty = true;
  34903. /** @hidden */
  34904. this._normals = false;
  34905. /** @hidden */
  34906. this._uvs = false;
  34907. /** @hidden */
  34908. this._needNormals = false;
  34909. /** @hidden */
  34910. this._needUVs = false;
  34911. }
  34912. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34913. /**
  34914. * Specifies if the material needs to be re-calculated
  34915. */
  34916. get: function () {
  34917. return this._isDirty;
  34918. },
  34919. enumerable: true,
  34920. configurable: true
  34921. });
  34922. /**
  34923. * Marks the material to indicate that it has been re-calculated
  34924. */
  34925. MaterialDefines.prototype.markAsProcessed = function () {
  34926. this._isDirty = false;
  34927. this._areAttributesDirty = false;
  34928. this._areTexturesDirty = false;
  34929. this._areFresnelDirty = false;
  34930. this._areLightsDirty = false;
  34931. this._areMiscDirty = false;
  34932. this._areImageProcessingDirty = false;
  34933. };
  34934. /**
  34935. * Marks the material to indicate that it needs to be re-calculated
  34936. */
  34937. MaterialDefines.prototype.markAsUnprocessed = function () {
  34938. this._isDirty = true;
  34939. };
  34940. /**
  34941. * Marks the material to indicate all of its defines need to be re-calculated
  34942. */
  34943. MaterialDefines.prototype.markAllAsDirty = function () {
  34944. this._areTexturesDirty = true;
  34945. this._areAttributesDirty = true;
  34946. this._areLightsDirty = true;
  34947. this._areFresnelDirty = true;
  34948. this._areMiscDirty = true;
  34949. this._areImageProcessingDirty = true;
  34950. this._isDirty = true;
  34951. };
  34952. /**
  34953. * Marks the material to indicate that image processing needs to be re-calculated
  34954. */
  34955. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34956. this._areImageProcessingDirty = true;
  34957. this._isDirty = true;
  34958. };
  34959. /**
  34960. * Marks the material to indicate the lights need to be re-calculated
  34961. */
  34962. MaterialDefines.prototype.markAsLightDirty = function () {
  34963. this._areLightsDirty = true;
  34964. this._isDirty = true;
  34965. };
  34966. /**
  34967. * Marks the attribute state as changed
  34968. */
  34969. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34970. this._areAttributesDirty = true;
  34971. this._isDirty = true;
  34972. };
  34973. /**
  34974. * Marks the texture state as changed
  34975. */
  34976. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34977. this._areTexturesDirty = true;
  34978. this._isDirty = true;
  34979. };
  34980. /**
  34981. * Marks the fresnel state as changed
  34982. */
  34983. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34984. this._areFresnelDirty = true;
  34985. this._isDirty = true;
  34986. };
  34987. /**
  34988. * Marks the misc state as changed
  34989. */
  34990. MaterialDefines.prototype.markAsMiscDirty = function () {
  34991. this._areMiscDirty = true;
  34992. this._isDirty = true;
  34993. };
  34994. /**
  34995. * Rebuilds the material defines
  34996. */
  34997. MaterialDefines.prototype.rebuild = function () {
  34998. if (this._keys) {
  34999. delete this._keys;
  35000. }
  35001. this._keys = [];
  35002. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35003. var key = _a[_i];
  35004. if (key[0] === "_") {
  35005. continue;
  35006. }
  35007. this._keys.push(key);
  35008. }
  35009. };
  35010. /**
  35011. * Specifies if two material defines are equal
  35012. * @param other - A material define instance to compare to
  35013. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35014. */
  35015. MaterialDefines.prototype.isEqual = function (other) {
  35016. if (this._keys.length !== other._keys.length) {
  35017. return false;
  35018. }
  35019. for (var index = 0; index < this._keys.length; index++) {
  35020. var prop = this._keys[index];
  35021. if (this[prop] !== other[prop]) {
  35022. return false;
  35023. }
  35024. }
  35025. return true;
  35026. };
  35027. /**
  35028. * Clones this instance's defines to another instance
  35029. * @param other - material defines to clone values to
  35030. */
  35031. MaterialDefines.prototype.cloneTo = function (other) {
  35032. if (this._keys.length !== other._keys.length) {
  35033. other._keys = this._keys.slice(0);
  35034. }
  35035. for (var index = 0; index < this._keys.length; index++) {
  35036. var prop = this._keys[index];
  35037. other[prop] = this[prop];
  35038. }
  35039. };
  35040. /**
  35041. * Resets the material define values
  35042. */
  35043. MaterialDefines.prototype.reset = function () {
  35044. for (var index = 0; index < this._keys.length; index++) {
  35045. var prop = this._keys[index];
  35046. var type = typeof this[prop];
  35047. switch (type) {
  35048. case "number":
  35049. this[prop] = 0;
  35050. break;
  35051. case "string":
  35052. this[prop] = "";
  35053. break;
  35054. default:
  35055. this[prop] = false;
  35056. break;
  35057. }
  35058. }
  35059. };
  35060. /**
  35061. * Converts the material define values to a string
  35062. * @returns - String of material define information
  35063. */
  35064. MaterialDefines.prototype.toString = function () {
  35065. var result = "";
  35066. for (var index = 0; index < this._keys.length; index++) {
  35067. var prop = this._keys[index];
  35068. var value = this[prop];
  35069. var type = typeof value;
  35070. switch (type) {
  35071. case "number":
  35072. case "string":
  35073. result += "#define " + prop + " " + value + "\n";
  35074. break;
  35075. default:
  35076. if (value) {
  35077. result += "#define " + prop + "\n";
  35078. }
  35079. break;
  35080. }
  35081. }
  35082. return result;
  35083. };
  35084. return MaterialDefines;
  35085. }());
  35086. BABYLON.MaterialDefines = MaterialDefines;
  35087. /**
  35088. * Base class for the main features of a material in Babylon.js
  35089. */
  35090. var Material = /** @class */ (function () {
  35091. /**
  35092. * Creates a material instance
  35093. * @param name defines the name of the material
  35094. * @param scene defines the scene to reference
  35095. * @param doNotAdd specifies if the material should be added to the scene
  35096. */
  35097. function Material(name, scene, doNotAdd) {
  35098. /**
  35099. * Specifies if the ready state should be checked on each call
  35100. */
  35101. this.checkReadyOnEveryCall = false;
  35102. /**
  35103. * Specifies if the ready state should be checked once
  35104. */
  35105. this.checkReadyOnlyOnce = false;
  35106. /**
  35107. * The state of the material
  35108. */
  35109. this.state = "";
  35110. /**
  35111. * The alpha value of the material
  35112. */
  35113. this._alpha = 1.0;
  35114. /**
  35115. * Specifies if back face culling is enabled
  35116. */
  35117. this._backFaceCulling = true;
  35118. /**
  35119. * Specifies if the material should be serialized
  35120. */
  35121. this.doNotSerialize = false;
  35122. /**
  35123. * Specifies if the effect should be stored on sub meshes
  35124. */
  35125. this.storeEffectOnSubMeshes = false;
  35126. /**
  35127. * An event triggered when the material is disposed
  35128. */
  35129. this.onDisposeObservable = new BABYLON.Observable();
  35130. /**
  35131. * An event triggered when the material is bound
  35132. */
  35133. this.onBindObservable = new BABYLON.Observable();
  35134. /**
  35135. * An event triggered when the material is unbound
  35136. */
  35137. this.onUnBindObservable = new BABYLON.Observable();
  35138. /**
  35139. * Stores the value of the alpha mode
  35140. */
  35141. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35142. /**
  35143. * Stores the state of the need depth pre-pass value
  35144. */
  35145. this._needDepthPrePass = false;
  35146. /**
  35147. * Specifies if depth writing should be disabled
  35148. */
  35149. this.disableDepthWrite = false;
  35150. /**
  35151. * Specifies if depth writing should be forced
  35152. */
  35153. this.forceDepthWrite = false;
  35154. /**
  35155. * Specifies if there should be a separate pass for culling
  35156. */
  35157. this.separateCullingPass = false;
  35158. /**
  35159. * Stores the state specifing if fog should be enabled
  35160. */
  35161. this._fogEnabled = true;
  35162. /**
  35163. * Stores the size of points
  35164. */
  35165. this.pointSize = 1.0;
  35166. /**
  35167. * Stores the z offset value
  35168. */
  35169. this.zOffset = 0;
  35170. /**
  35171. * Specifies if the material was previously ready
  35172. */
  35173. this._wasPreviouslyReady = false;
  35174. /**
  35175. * Stores the fill mode state
  35176. */
  35177. this._fillMode = Material.TriangleFillMode;
  35178. this.name = name;
  35179. this.id = name || BABYLON.Tools.RandomId();
  35180. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35181. this.uniqueId = this._scene.getUniqueId();
  35182. if (this._scene.useRightHandedSystem) {
  35183. this.sideOrientation = Material.ClockWiseSideOrientation;
  35184. }
  35185. else {
  35186. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35187. }
  35188. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35189. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35190. if (!doNotAdd) {
  35191. this._scene.materials.push(this);
  35192. }
  35193. }
  35194. Object.defineProperty(Material, "TriangleFillMode", {
  35195. /**
  35196. * Returns the triangle fill mode
  35197. */
  35198. get: function () {
  35199. return Material._TriangleFillMode;
  35200. },
  35201. enumerable: true,
  35202. configurable: true
  35203. });
  35204. Object.defineProperty(Material, "WireFrameFillMode", {
  35205. /**
  35206. * Returns the wireframe mode
  35207. */
  35208. get: function () {
  35209. return Material._WireFrameFillMode;
  35210. },
  35211. enumerable: true,
  35212. configurable: true
  35213. });
  35214. Object.defineProperty(Material, "PointFillMode", {
  35215. /**
  35216. * Returns the point fill mode
  35217. */
  35218. get: function () {
  35219. return Material._PointFillMode;
  35220. },
  35221. enumerable: true,
  35222. configurable: true
  35223. });
  35224. Object.defineProperty(Material, "PointListDrawMode", {
  35225. /**
  35226. * Returns the point list draw mode
  35227. */
  35228. get: function () {
  35229. return Material._PointListDrawMode;
  35230. },
  35231. enumerable: true,
  35232. configurable: true
  35233. });
  35234. Object.defineProperty(Material, "LineListDrawMode", {
  35235. /**
  35236. * Returns the line list draw mode
  35237. */
  35238. get: function () {
  35239. return Material._LineListDrawMode;
  35240. },
  35241. enumerable: true,
  35242. configurable: true
  35243. });
  35244. Object.defineProperty(Material, "LineLoopDrawMode", {
  35245. /**
  35246. * Returns the line loop draw mode
  35247. */
  35248. get: function () {
  35249. return Material._LineLoopDrawMode;
  35250. },
  35251. enumerable: true,
  35252. configurable: true
  35253. });
  35254. Object.defineProperty(Material, "LineStripDrawMode", {
  35255. /**
  35256. * Returns the line strip draw mode
  35257. */
  35258. get: function () {
  35259. return Material._LineStripDrawMode;
  35260. },
  35261. enumerable: true,
  35262. configurable: true
  35263. });
  35264. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35265. /**
  35266. * Returns the triangle strip draw mode
  35267. */
  35268. get: function () {
  35269. return Material._TriangleStripDrawMode;
  35270. },
  35271. enumerable: true,
  35272. configurable: true
  35273. });
  35274. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35275. /**
  35276. * Returns the triangle fan draw mode
  35277. */
  35278. get: function () {
  35279. return Material._TriangleFanDrawMode;
  35280. },
  35281. enumerable: true,
  35282. configurable: true
  35283. });
  35284. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35285. /**
  35286. * Returns the clock-wise side orientation
  35287. */
  35288. get: function () {
  35289. return Material._ClockWiseSideOrientation;
  35290. },
  35291. enumerable: true,
  35292. configurable: true
  35293. });
  35294. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35295. /**
  35296. * Returns the counter clock-wise side orientation
  35297. */
  35298. get: function () {
  35299. return Material._CounterClockWiseSideOrientation;
  35300. },
  35301. enumerable: true,
  35302. configurable: true
  35303. });
  35304. Object.defineProperty(Material, "TextureDirtyFlag", {
  35305. /**
  35306. * Returns the dirty texture flag value
  35307. */
  35308. get: function () {
  35309. return Material._TextureDirtyFlag;
  35310. },
  35311. enumerable: true,
  35312. configurable: true
  35313. });
  35314. Object.defineProperty(Material, "LightDirtyFlag", {
  35315. /**
  35316. * Returns the dirty light flag value
  35317. */
  35318. get: function () {
  35319. return Material._LightDirtyFlag;
  35320. },
  35321. enumerable: true,
  35322. configurable: true
  35323. });
  35324. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35325. /**
  35326. * Returns the dirty fresnel flag value
  35327. */
  35328. get: function () {
  35329. return Material._FresnelDirtyFlag;
  35330. },
  35331. enumerable: true,
  35332. configurable: true
  35333. });
  35334. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35335. /**
  35336. * Returns the dirty attributes flag value
  35337. */
  35338. get: function () {
  35339. return Material._AttributesDirtyFlag;
  35340. },
  35341. enumerable: true,
  35342. configurable: true
  35343. });
  35344. Object.defineProperty(Material, "MiscDirtyFlag", {
  35345. /**
  35346. * Returns the dirty misc flag value
  35347. */
  35348. get: function () {
  35349. return Material._MiscDirtyFlag;
  35350. },
  35351. enumerable: true,
  35352. configurable: true
  35353. });
  35354. Object.defineProperty(Material.prototype, "alpha", {
  35355. /**
  35356. * Gets the alpha value of the material
  35357. */
  35358. get: function () {
  35359. return this._alpha;
  35360. },
  35361. /**
  35362. * Sets the alpha value of the material
  35363. */
  35364. set: function (value) {
  35365. if (this._alpha === value) {
  35366. return;
  35367. }
  35368. this._alpha = value;
  35369. this.markAsDirty(Material.MiscDirtyFlag);
  35370. },
  35371. enumerable: true,
  35372. configurable: true
  35373. });
  35374. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35375. /**
  35376. * Gets the back-face culling state
  35377. */
  35378. get: function () {
  35379. return this._backFaceCulling;
  35380. },
  35381. /**
  35382. * Sets the back-face culling state
  35383. */
  35384. set: function (value) {
  35385. if (this._backFaceCulling === value) {
  35386. return;
  35387. }
  35388. this._backFaceCulling = value;
  35389. this.markAsDirty(Material.TextureDirtyFlag);
  35390. },
  35391. enumerable: true,
  35392. configurable: true
  35393. });
  35394. Object.defineProperty(Material.prototype, "onDispose", {
  35395. /**
  35396. * Called during a dispose event
  35397. */
  35398. set: function (callback) {
  35399. if (this._onDisposeObserver) {
  35400. this.onDisposeObservable.remove(this._onDisposeObserver);
  35401. }
  35402. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35403. },
  35404. enumerable: true,
  35405. configurable: true
  35406. });
  35407. Object.defineProperty(Material.prototype, "onBind", {
  35408. /**
  35409. * Called during a bind event
  35410. */
  35411. set: function (callback) {
  35412. if (this._onBindObserver) {
  35413. this.onBindObservable.remove(this._onBindObserver);
  35414. }
  35415. this._onBindObserver = this.onBindObservable.add(callback);
  35416. },
  35417. enumerable: true,
  35418. configurable: true
  35419. });
  35420. Object.defineProperty(Material.prototype, "alphaMode", {
  35421. /**
  35422. * Gets the value of the alpha mode
  35423. */
  35424. get: function () {
  35425. return this._alphaMode;
  35426. },
  35427. /**
  35428. * Sets the value of the alpha mode.
  35429. *
  35430. * | Value | Type | Description |
  35431. * | --- | --- | --- |
  35432. * | 0 | ALPHA_DISABLE | |
  35433. * | 1 | ALPHA_ADD | |
  35434. * | 2 | ALPHA_COMBINE | |
  35435. * | 3 | ALPHA_SUBTRACT | |
  35436. * | 4 | ALPHA_MULTIPLY | |
  35437. * | 5 | ALPHA_MAXIMIZED | |
  35438. * | 6 | ALPHA_ONEONE | |
  35439. * | 7 | ALPHA_PREMULTIPLIED | |
  35440. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35441. * | 9 | ALPHA_INTERPOLATE | |
  35442. * | 10 | ALPHA_SCREENMODE | |
  35443. *
  35444. */
  35445. set: function (value) {
  35446. if (this._alphaMode === value) {
  35447. return;
  35448. }
  35449. this._alphaMode = value;
  35450. this.markAsDirty(Material.TextureDirtyFlag);
  35451. },
  35452. enumerable: true,
  35453. configurable: true
  35454. });
  35455. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35456. /**
  35457. * Gets the depth pre-pass value
  35458. */
  35459. get: function () {
  35460. return this._needDepthPrePass;
  35461. },
  35462. /**
  35463. * Sets the need depth pre-pass value
  35464. */
  35465. set: function (value) {
  35466. if (this._needDepthPrePass === value) {
  35467. return;
  35468. }
  35469. this._needDepthPrePass = value;
  35470. if (this._needDepthPrePass) {
  35471. this.checkReadyOnEveryCall = true;
  35472. }
  35473. },
  35474. enumerable: true,
  35475. configurable: true
  35476. });
  35477. Object.defineProperty(Material.prototype, "fogEnabled", {
  35478. /**
  35479. * Gets the value of the fog enabled state
  35480. */
  35481. get: function () {
  35482. return this._fogEnabled;
  35483. },
  35484. /**
  35485. * Sets the state for enabling fog
  35486. */
  35487. set: function (value) {
  35488. if (this._fogEnabled === value) {
  35489. return;
  35490. }
  35491. this._fogEnabled = value;
  35492. this.markAsDirty(Material.MiscDirtyFlag);
  35493. },
  35494. enumerable: true,
  35495. configurable: true
  35496. });
  35497. Object.defineProperty(Material.prototype, "wireframe", {
  35498. /**
  35499. * Gets a value specifying if wireframe mode is enabled
  35500. */
  35501. get: function () {
  35502. switch (this._fillMode) {
  35503. case Material.WireFrameFillMode:
  35504. case Material.LineListDrawMode:
  35505. case Material.LineLoopDrawMode:
  35506. case Material.LineStripDrawMode:
  35507. return true;
  35508. }
  35509. return this._scene.forceWireframe;
  35510. },
  35511. /**
  35512. * Sets the state of wireframe mode
  35513. */
  35514. set: function (value) {
  35515. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35516. },
  35517. enumerable: true,
  35518. configurable: true
  35519. });
  35520. Object.defineProperty(Material.prototype, "pointsCloud", {
  35521. /**
  35522. * Gets the value specifying if point clouds are enabled
  35523. */
  35524. get: function () {
  35525. switch (this._fillMode) {
  35526. case Material.PointFillMode:
  35527. case Material.PointListDrawMode:
  35528. return true;
  35529. }
  35530. return this._scene.forcePointsCloud;
  35531. },
  35532. /**
  35533. * Sets the state of point cloud mode
  35534. */
  35535. set: function (value) {
  35536. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35537. },
  35538. enumerable: true,
  35539. configurable: true
  35540. });
  35541. Object.defineProperty(Material.prototype, "fillMode", {
  35542. /**
  35543. * Gets the material fill mode
  35544. */
  35545. get: function () {
  35546. return this._fillMode;
  35547. },
  35548. /**
  35549. * Sets the material fill mode
  35550. */
  35551. set: function (value) {
  35552. if (this._fillMode === value) {
  35553. return;
  35554. }
  35555. this._fillMode = value;
  35556. this.markAsDirty(Material.MiscDirtyFlag);
  35557. },
  35558. enumerable: true,
  35559. configurable: true
  35560. });
  35561. /**
  35562. * Returns a string representation of the current material
  35563. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35564. * @returns a string with material information
  35565. */
  35566. Material.prototype.toString = function (fullDetails) {
  35567. var ret = "Name: " + this.name;
  35568. if (fullDetails) {
  35569. }
  35570. return ret;
  35571. };
  35572. /**
  35573. * Gets the class name of the material
  35574. * @returns a string with the class name of the material
  35575. */
  35576. Material.prototype.getClassName = function () {
  35577. return "Material";
  35578. };
  35579. Object.defineProperty(Material.prototype, "isFrozen", {
  35580. /**
  35581. * Specifies if updates for the material been locked
  35582. */
  35583. get: function () {
  35584. return this.checkReadyOnlyOnce;
  35585. },
  35586. enumerable: true,
  35587. configurable: true
  35588. });
  35589. /**
  35590. * Locks updates for the material
  35591. */
  35592. Material.prototype.freeze = function () {
  35593. this.checkReadyOnlyOnce = true;
  35594. };
  35595. /**
  35596. * Unlocks updates for the material
  35597. */
  35598. Material.prototype.unfreeze = function () {
  35599. this.checkReadyOnlyOnce = false;
  35600. };
  35601. /**
  35602. * Specifies if the material is ready to be used
  35603. * @param mesh defines the mesh to check
  35604. * @param useInstances specifies if instances should be used
  35605. * @returns a boolean indicating if the material is ready to be used
  35606. */
  35607. Material.prototype.isReady = function (mesh, useInstances) {
  35608. return true;
  35609. };
  35610. /**
  35611. * Specifies that the submesh is ready to be used
  35612. * @param mesh defines the mesh to check
  35613. * @param subMesh defines which submesh to check
  35614. * @param useInstances specifies that instances should be used
  35615. * @returns a boolean indicating that the submesh is ready or not
  35616. */
  35617. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35618. return false;
  35619. };
  35620. /**
  35621. * Returns the material effect
  35622. * @returns the effect associated with the material
  35623. */
  35624. Material.prototype.getEffect = function () {
  35625. return this._effect;
  35626. };
  35627. /**
  35628. * Returns the current scene
  35629. * @returns a Scene
  35630. */
  35631. Material.prototype.getScene = function () {
  35632. return this._scene;
  35633. };
  35634. /**
  35635. * Specifies if the material will require alpha blending
  35636. * @returns a boolean specifying if alpha blending is needed
  35637. */
  35638. Material.prototype.needAlphaBlending = function () {
  35639. return (this.alpha < 1.0);
  35640. };
  35641. /**
  35642. * Specifies if the mesh will require alpha blending
  35643. * @param mesh defines the mesh to check
  35644. * @returns a boolean specifying if alpha blending is needed for the mesh
  35645. */
  35646. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35647. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35648. };
  35649. /**
  35650. * Specifies if this material should be rendered in alpha test mode
  35651. * @returns a boolean specifying if an alpha test is needed.
  35652. */
  35653. Material.prototype.needAlphaTesting = function () {
  35654. return false;
  35655. };
  35656. /**
  35657. * Gets the texture used for the alpha test
  35658. * @returns the texture to use for alpha testing
  35659. */
  35660. Material.prototype.getAlphaTestTexture = function () {
  35661. return null;
  35662. };
  35663. /**
  35664. * Marks the material to indicate that it needs to be re-calculated
  35665. */
  35666. Material.prototype.markDirty = function () {
  35667. this._wasPreviouslyReady = false;
  35668. };
  35669. /** @hidden */
  35670. Material.prototype._preBind = function (effect, overrideOrientation) {
  35671. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35672. var engine = this._scene.getEngine();
  35673. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35674. var reverse = orientation === Material.ClockWiseSideOrientation;
  35675. engine.enableEffect(effect ? effect : this._effect);
  35676. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35677. return reverse;
  35678. };
  35679. /**
  35680. * Binds the material to the mesh
  35681. * @param world defines the world transformation matrix
  35682. * @param mesh defines the mesh to bind the material to
  35683. */
  35684. Material.prototype.bind = function (world, mesh) {
  35685. };
  35686. /**
  35687. * Binds the submesh to the material
  35688. * @param world defines the world transformation matrix
  35689. * @param mesh defines the mesh containing the submesh
  35690. * @param subMesh defines the submesh to bind the material to
  35691. */
  35692. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35693. };
  35694. /**
  35695. * Binds the world matrix to the material
  35696. * @param world defines the world transformation matrix
  35697. */
  35698. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35699. };
  35700. /**
  35701. * Binds the scene's uniform buffer to the effect.
  35702. * @param effect defines the effect to bind to the scene uniform buffer
  35703. * @param sceneUbo defines the uniform buffer storing scene data
  35704. */
  35705. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35706. sceneUbo.bindToEffect(effect, "Scene");
  35707. };
  35708. /**
  35709. * Binds the view matrix to the effect
  35710. * @param effect defines the effect to bind the view matrix to
  35711. */
  35712. Material.prototype.bindView = function (effect) {
  35713. if (!this._useUBO) {
  35714. effect.setMatrix("view", this.getScene().getViewMatrix());
  35715. }
  35716. else {
  35717. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35718. }
  35719. };
  35720. /**
  35721. * Binds the view projection matrix to the effect
  35722. * @param effect defines the effect to bind the view projection matrix to
  35723. */
  35724. Material.prototype.bindViewProjection = function (effect) {
  35725. if (!this._useUBO) {
  35726. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35727. }
  35728. else {
  35729. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35730. }
  35731. };
  35732. /**
  35733. * Specifies if material alpha testing should be turned on for the mesh
  35734. * @param mesh defines the mesh to check
  35735. */
  35736. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35737. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35738. };
  35739. /**
  35740. * Processes to execute after binding the material to a mesh
  35741. * @param mesh defines the rendered mesh
  35742. */
  35743. Material.prototype._afterBind = function (mesh) {
  35744. this._scene._cachedMaterial = this;
  35745. if (mesh) {
  35746. this._scene._cachedVisibility = mesh.visibility;
  35747. }
  35748. else {
  35749. this._scene._cachedVisibility = 1;
  35750. }
  35751. if (mesh) {
  35752. this.onBindObservable.notifyObservers(mesh);
  35753. }
  35754. if (this.disableDepthWrite) {
  35755. var engine = this._scene.getEngine();
  35756. this._cachedDepthWriteState = engine.getDepthWrite();
  35757. engine.setDepthWrite(false);
  35758. }
  35759. };
  35760. /**
  35761. * Unbinds the material from the mesh
  35762. */
  35763. Material.prototype.unbind = function () {
  35764. this.onUnBindObservable.notifyObservers(this);
  35765. if (this.disableDepthWrite) {
  35766. var engine = this._scene.getEngine();
  35767. engine.setDepthWrite(this._cachedDepthWriteState);
  35768. }
  35769. };
  35770. /**
  35771. * Gets the active textures from the material
  35772. * @returns an array of textures
  35773. */
  35774. Material.prototype.getActiveTextures = function () {
  35775. return [];
  35776. };
  35777. /**
  35778. * Specifies if the material uses a texture
  35779. * @param texture defines the texture to check against the material
  35780. * @returns a boolean specifying if the material uses the texture
  35781. */
  35782. Material.prototype.hasTexture = function (texture) {
  35783. return false;
  35784. };
  35785. /**
  35786. * Makes a duplicate of the material, and gives it a new name
  35787. * @param name defines the new name for the duplicated material
  35788. * @returns the cloned material
  35789. */
  35790. Material.prototype.clone = function (name) {
  35791. return null;
  35792. };
  35793. /**
  35794. * Gets the meshes bound to the material
  35795. * @returns an array of meshes bound to the material
  35796. */
  35797. Material.prototype.getBindedMeshes = function () {
  35798. var result = new Array();
  35799. for (var index = 0; index < this._scene.meshes.length; index++) {
  35800. var mesh = this._scene.meshes[index];
  35801. if (mesh.material === this) {
  35802. result.push(mesh);
  35803. }
  35804. }
  35805. return result;
  35806. };
  35807. /**
  35808. * Force shader compilation
  35809. * @param mesh defines the mesh associated with this material
  35810. * @param onCompiled defines a function to execute once the material is compiled
  35811. * @param options defines the options to configure the compilation
  35812. */
  35813. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35814. var _this = this;
  35815. var localOptions = __assign({ clipPlane: false }, options);
  35816. var subMesh = new BABYLON.BaseSubMesh();
  35817. var scene = this.getScene();
  35818. var checkReady = function () {
  35819. if (!_this._scene || !_this._scene.getEngine()) {
  35820. return;
  35821. }
  35822. if (subMesh._materialDefines) {
  35823. subMesh._materialDefines._renderId = -1;
  35824. }
  35825. var clipPlaneState = scene.clipPlane;
  35826. if (localOptions.clipPlane) {
  35827. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35828. }
  35829. if (_this.storeEffectOnSubMeshes) {
  35830. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35831. if (onCompiled) {
  35832. onCompiled(_this);
  35833. }
  35834. }
  35835. else {
  35836. setTimeout(checkReady, 16);
  35837. }
  35838. }
  35839. else {
  35840. if (_this.isReady(mesh)) {
  35841. if (onCompiled) {
  35842. onCompiled(_this);
  35843. }
  35844. }
  35845. else {
  35846. setTimeout(checkReady, 16);
  35847. }
  35848. }
  35849. if (localOptions.clipPlane) {
  35850. scene.clipPlane = clipPlaneState;
  35851. }
  35852. };
  35853. checkReady();
  35854. };
  35855. /**
  35856. * Force shader compilation
  35857. * @param mesh defines the mesh that will use this material
  35858. * @param options defines additional options for compiling the shaders
  35859. * @returns a promise that resolves when the compilation completes
  35860. */
  35861. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35862. var _this = this;
  35863. return new Promise(function (resolve) {
  35864. _this.forceCompilation(mesh, function () {
  35865. resolve();
  35866. }, options);
  35867. });
  35868. };
  35869. /**
  35870. * Marks a define in the material to indicate that it needs to be re-computed
  35871. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35872. */
  35873. Material.prototype.markAsDirty = function (flag) {
  35874. if (flag & Material.TextureDirtyFlag) {
  35875. this._markAllSubMeshesAsTexturesDirty();
  35876. }
  35877. if (flag & Material.LightDirtyFlag) {
  35878. this._markAllSubMeshesAsLightsDirty();
  35879. }
  35880. if (flag & Material.FresnelDirtyFlag) {
  35881. this._markAllSubMeshesAsFresnelDirty();
  35882. }
  35883. if (flag & Material.AttributesDirtyFlag) {
  35884. this._markAllSubMeshesAsAttributesDirty();
  35885. }
  35886. if (flag & Material.MiscDirtyFlag) {
  35887. this._markAllSubMeshesAsMiscDirty();
  35888. }
  35889. this.getScene().resetCachedMaterial();
  35890. };
  35891. /**
  35892. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35893. * @param func defines a function which checks material defines against the submeshes
  35894. */
  35895. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35896. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35897. var mesh = _a[_i];
  35898. if (!mesh.subMeshes) {
  35899. continue;
  35900. }
  35901. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35902. var subMesh = _c[_b];
  35903. if (subMesh.getMaterial() !== this) {
  35904. continue;
  35905. }
  35906. if (!subMesh._materialDefines) {
  35907. continue;
  35908. }
  35909. func(subMesh._materialDefines);
  35910. }
  35911. }
  35912. };
  35913. /**
  35914. * Indicates that image processing needs to be re-calculated for all submeshes
  35915. */
  35916. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35917. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35918. };
  35919. /**
  35920. * Indicates that textures need to be re-calculated for all submeshes
  35921. */
  35922. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35923. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35924. };
  35925. /**
  35926. * Indicates that fresnel needs to be re-calculated for all submeshes
  35927. */
  35928. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35929. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35930. };
  35931. /**
  35932. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35933. */
  35934. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35935. this._markAllSubMeshesAsDirty(function (defines) {
  35936. defines.markAsFresnelDirty();
  35937. defines.markAsMiscDirty();
  35938. });
  35939. };
  35940. /**
  35941. * Indicates that lights need to be re-calculated for all submeshes
  35942. */
  35943. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35944. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35945. };
  35946. /**
  35947. * Indicates that attributes need to be re-calculated for all submeshes
  35948. */
  35949. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35950. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35951. };
  35952. /**
  35953. * Indicates that misc needs to be re-calculated for all submeshes
  35954. */
  35955. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35956. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35957. };
  35958. /**
  35959. * Indicates that textures and misc need to be re-calculated for all submeshes
  35960. */
  35961. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35962. this._markAllSubMeshesAsDirty(function (defines) {
  35963. defines.markAsTexturesDirty();
  35964. defines.markAsMiscDirty();
  35965. });
  35966. };
  35967. /**
  35968. * Disposes the material
  35969. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35970. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35971. */
  35972. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35973. // Animations
  35974. this.getScene().stopAnimation(this);
  35975. this.getScene().freeProcessedMaterials();
  35976. // Remove from scene
  35977. var index = this._scene.materials.indexOf(this);
  35978. if (index >= 0) {
  35979. this._scene.materials.splice(index, 1);
  35980. }
  35981. // Remove from meshes
  35982. for (index = 0; index < this._scene.meshes.length; index++) {
  35983. var mesh = this._scene.meshes[index];
  35984. if (mesh.material === this) {
  35985. mesh.material = null;
  35986. if (mesh.geometry) {
  35987. var geometry = (mesh.geometry);
  35988. if (this.storeEffectOnSubMeshes) {
  35989. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35990. var subMesh = _a[_i];
  35991. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35992. if (forceDisposeEffect && subMesh._materialEffect) {
  35993. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35994. }
  35995. }
  35996. }
  35997. else {
  35998. geometry._releaseVertexArrayObject(this._effect);
  35999. }
  36000. }
  36001. }
  36002. }
  36003. this._uniformBuffer.dispose();
  36004. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36005. if (forceDisposeEffect && this._effect) {
  36006. if (!this.storeEffectOnSubMeshes) {
  36007. this._scene.getEngine()._releaseEffect(this._effect);
  36008. }
  36009. this._effect = null;
  36010. }
  36011. // Callback
  36012. this.onDisposeObservable.notifyObservers(this);
  36013. this.onDisposeObservable.clear();
  36014. this.onBindObservable.clear();
  36015. this.onUnBindObservable.clear();
  36016. };
  36017. /**
  36018. * Serializes this material
  36019. * @returns the serialized material object
  36020. */
  36021. Material.prototype.serialize = function () {
  36022. return BABYLON.SerializationHelper.Serialize(this);
  36023. };
  36024. /**
  36025. * Creates a MultiMaterial from parsed MultiMaterial data.
  36026. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36027. * @param scene defines the hosting scene
  36028. * @returns a new MultiMaterial
  36029. */
  36030. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36031. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36032. multiMaterial.id = parsedMultiMaterial.id;
  36033. if (BABYLON.Tags) {
  36034. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36035. }
  36036. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36037. var subMatId = parsedMultiMaterial.materials[matIndex];
  36038. if (subMatId) {
  36039. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36040. }
  36041. else {
  36042. multiMaterial.subMaterials.push(null);
  36043. }
  36044. }
  36045. return multiMaterial;
  36046. };
  36047. /**
  36048. * Creates a material from parsed material data
  36049. * @param parsedMaterial defines parsed material data
  36050. * @param scene defines the hosting scene
  36051. * @param rootUrl defines the root URL to use to load textures
  36052. * @returns a new material
  36053. */
  36054. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36055. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36056. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36057. }
  36058. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36059. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36060. if (!BABYLON.LegacyPBRMaterial) {
  36061. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36062. return;
  36063. }
  36064. }
  36065. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36066. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36067. };
  36068. // Triangle views
  36069. Material._TriangleFillMode = 0;
  36070. Material._WireFrameFillMode = 1;
  36071. Material._PointFillMode = 2;
  36072. // Draw modes
  36073. Material._PointListDrawMode = 3;
  36074. Material._LineListDrawMode = 4;
  36075. Material._LineLoopDrawMode = 5;
  36076. Material._LineStripDrawMode = 6;
  36077. Material._TriangleStripDrawMode = 7;
  36078. Material._TriangleFanDrawMode = 8;
  36079. /**
  36080. * Stores the clock-wise side orientation
  36081. */
  36082. Material._ClockWiseSideOrientation = 0;
  36083. /**
  36084. * Stores the counter clock-wise side orientation
  36085. */
  36086. Material._CounterClockWiseSideOrientation = 1;
  36087. /**
  36088. * The dirty texture flag value
  36089. */
  36090. Material._TextureDirtyFlag = 1;
  36091. /**
  36092. * The dirty light flag value
  36093. */
  36094. Material._LightDirtyFlag = 2;
  36095. /**
  36096. * The dirty fresnel flag value
  36097. */
  36098. Material._FresnelDirtyFlag = 4;
  36099. /**
  36100. * The dirty attribute flag value
  36101. */
  36102. Material._AttributesDirtyFlag = 8;
  36103. /**
  36104. * The dirty misc flag value
  36105. */
  36106. Material._MiscDirtyFlag = 16;
  36107. __decorate([
  36108. BABYLON.serialize()
  36109. ], Material.prototype, "id", void 0);
  36110. __decorate([
  36111. BABYLON.serialize()
  36112. ], Material.prototype, "uniqueId", void 0);
  36113. __decorate([
  36114. BABYLON.serialize()
  36115. ], Material.prototype, "name", void 0);
  36116. __decorate([
  36117. BABYLON.serialize()
  36118. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36119. __decorate([
  36120. BABYLON.serialize()
  36121. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36122. __decorate([
  36123. BABYLON.serialize()
  36124. ], Material.prototype, "state", void 0);
  36125. __decorate([
  36126. BABYLON.serialize("alpha")
  36127. ], Material.prototype, "_alpha", void 0);
  36128. __decorate([
  36129. BABYLON.serialize("backFaceCulling")
  36130. ], Material.prototype, "_backFaceCulling", void 0);
  36131. __decorate([
  36132. BABYLON.serialize()
  36133. ], Material.prototype, "sideOrientation", void 0);
  36134. __decorate([
  36135. BABYLON.serialize("alphaMode")
  36136. ], Material.prototype, "_alphaMode", void 0);
  36137. __decorate([
  36138. BABYLON.serialize()
  36139. ], Material.prototype, "_needDepthPrePass", void 0);
  36140. __decorate([
  36141. BABYLON.serialize()
  36142. ], Material.prototype, "disableDepthWrite", void 0);
  36143. __decorate([
  36144. BABYLON.serialize()
  36145. ], Material.prototype, "forceDepthWrite", void 0);
  36146. __decorate([
  36147. BABYLON.serialize()
  36148. ], Material.prototype, "separateCullingPass", void 0);
  36149. __decorate([
  36150. BABYLON.serialize("fogEnabled")
  36151. ], Material.prototype, "_fogEnabled", void 0);
  36152. __decorate([
  36153. BABYLON.serialize()
  36154. ], Material.prototype, "pointSize", void 0);
  36155. __decorate([
  36156. BABYLON.serialize()
  36157. ], Material.prototype, "zOffset", void 0);
  36158. __decorate([
  36159. BABYLON.serialize()
  36160. ], Material.prototype, "wireframe", null);
  36161. __decorate([
  36162. BABYLON.serialize()
  36163. ], Material.prototype, "pointsCloud", null);
  36164. __decorate([
  36165. BABYLON.serialize()
  36166. ], Material.prototype, "fillMode", null);
  36167. return Material;
  36168. }());
  36169. BABYLON.Material = Material;
  36170. })(BABYLON || (BABYLON = {}));
  36171. //# sourceMappingURL=babylon.material.js.map
  36172. var BABYLON;
  36173. (function (BABYLON) {
  36174. var UniformBuffer = /** @class */ (function () {
  36175. /**
  36176. * Uniform buffer objects.
  36177. *
  36178. * Handles blocks of uniform on the GPU.
  36179. *
  36180. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36181. *
  36182. * For more information, please refer to :
  36183. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36184. */
  36185. function UniformBuffer(engine, data, dynamic) {
  36186. this._engine = engine;
  36187. this._noUBO = !engine.supportsUniformBuffers;
  36188. this._dynamic = dynamic;
  36189. this._data = data || [];
  36190. this._uniformLocations = {};
  36191. this._uniformSizes = {};
  36192. this._uniformLocationPointer = 0;
  36193. this._needSync = false;
  36194. if (this._noUBO) {
  36195. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36196. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36197. this.updateFloat = this._updateFloatForEffect;
  36198. this.updateFloat2 = this._updateFloat2ForEffect;
  36199. this.updateFloat3 = this._updateFloat3ForEffect;
  36200. this.updateFloat4 = this._updateFloat4ForEffect;
  36201. this.updateMatrix = this._updateMatrixForEffect;
  36202. this.updateVector3 = this._updateVector3ForEffect;
  36203. this.updateVector4 = this._updateVector4ForEffect;
  36204. this.updateColor3 = this._updateColor3ForEffect;
  36205. this.updateColor4 = this._updateColor4ForEffect;
  36206. }
  36207. else {
  36208. this._engine._uniformBuffers.push(this);
  36209. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36210. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36211. this.updateFloat = this._updateFloatForUniform;
  36212. this.updateFloat2 = this._updateFloat2ForUniform;
  36213. this.updateFloat3 = this._updateFloat3ForUniform;
  36214. this.updateFloat4 = this._updateFloat4ForUniform;
  36215. this.updateMatrix = this._updateMatrixForUniform;
  36216. this.updateVector3 = this._updateVector3ForUniform;
  36217. this.updateVector4 = this._updateVector4ForUniform;
  36218. this.updateColor3 = this._updateColor3ForUniform;
  36219. this.updateColor4 = this._updateColor4ForUniform;
  36220. }
  36221. }
  36222. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36223. // Properties
  36224. /**
  36225. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36226. * or just falling back on setUniformXXX calls.
  36227. */
  36228. get: function () {
  36229. return !this._noUBO;
  36230. },
  36231. enumerable: true,
  36232. configurable: true
  36233. });
  36234. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36235. /**
  36236. * Indicates if the WebGL underlying uniform buffer is in sync
  36237. * with the javascript cache data.
  36238. */
  36239. get: function () {
  36240. return !this._needSync;
  36241. },
  36242. enumerable: true,
  36243. configurable: true
  36244. });
  36245. /**
  36246. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36247. * Also, a dynamic UniformBuffer will disable cache verification and always
  36248. * update the underlying WebGL uniform buffer to the GPU.
  36249. */
  36250. UniformBuffer.prototype.isDynamic = function () {
  36251. return this._dynamic !== undefined;
  36252. };
  36253. /**
  36254. * The data cache on JS side.
  36255. */
  36256. UniformBuffer.prototype.getData = function () {
  36257. return this._bufferData;
  36258. };
  36259. /**
  36260. * The underlying WebGL Uniform buffer.
  36261. */
  36262. UniformBuffer.prototype.getBuffer = function () {
  36263. return this._buffer;
  36264. };
  36265. /**
  36266. * std140 layout specifies how to align data within an UBO structure.
  36267. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36268. * for specs.
  36269. */
  36270. UniformBuffer.prototype._fillAlignment = function (size) {
  36271. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36272. // and 4x4 matrices
  36273. // TODO : change if other types are used
  36274. var alignment;
  36275. if (size <= 2) {
  36276. alignment = size;
  36277. }
  36278. else {
  36279. alignment = 4;
  36280. }
  36281. if ((this._uniformLocationPointer % alignment) !== 0) {
  36282. var oldPointer = this._uniformLocationPointer;
  36283. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36284. var diff = this._uniformLocationPointer - oldPointer;
  36285. for (var i = 0; i < diff; i++) {
  36286. this._data.push(0);
  36287. }
  36288. }
  36289. };
  36290. /**
  36291. * Adds an uniform in the buffer.
  36292. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36293. * for the layout to be correct !
  36294. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36295. * @param {number|number[]} size Data size, or data directly.
  36296. */
  36297. UniformBuffer.prototype.addUniform = function (name, size) {
  36298. if (this._noUBO) {
  36299. return;
  36300. }
  36301. if (this._uniformLocations[name] !== undefined) {
  36302. // Already existing uniform
  36303. return;
  36304. }
  36305. // This function must be called in the order of the shader layout !
  36306. // size can be the size of the uniform, or data directly
  36307. var data;
  36308. if (size instanceof Array) {
  36309. data = size;
  36310. size = data.length;
  36311. }
  36312. else {
  36313. size = size;
  36314. data = [];
  36315. // Fill with zeros
  36316. for (var i = 0; i < size; i++) {
  36317. data.push(0);
  36318. }
  36319. }
  36320. this._fillAlignment(size);
  36321. this._uniformSizes[name] = size;
  36322. this._uniformLocations[name] = this._uniformLocationPointer;
  36323. this._uniformLocationPointer += size;
  36324. for (var i = 0; i < size; i++) {
  36325. this._data.push(data[i]);
  36326. }
  36327. this._needSync = true;
  36328. };
  36329. /**
  36330. * Wrapper for addUniform.
  36331. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36332. * @param {Matrix} mat A 4x4 matrix.
  36333. */
  36334. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36335. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  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 {number} x
  36341. * @param {number} y
  36342. */
  36343. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36344. var temp = [x, y];
  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. * @param {number} x
  36351. * @param {number} y
  36352. * @param {number} z
  36353. */
  36354. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36355. var temp = [x, y, z];
  36356. this.addUniform(name, temp);
  36357. };
  36358. /**
  36359. * Wrapper for addUniform.
  36360. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36361. * @param {Color3} color
  36362. */
  36363. UniformBuffer.prototype.addColor3 = function (name, color) {
  36364. var temp = new Array();
  36365. color.toArray(temp);
  36366. this.addUniform(name, temp);
  36367. };
  36368. /**
  36369. * Wrapper for addUniform.
  36370. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36371. * @param {Color3} color
  36372. * @param {number} alpha
  36373. */
  36374. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36375. var temp = new Array();
  36376. color.toArray(temp);
  36377. temp.push(alpha);
  36378. this.addUniform(name, temp);
  36379. };
  36380. /**
  36381. * Wrapper for addUniform.
  36382. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36383. * @param {Vector3} vector
  36384. */
  36385. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36386. var temp = new Array();
  36387. vector.toArray(temp);
  36388. this.addUniform(name, temp);
  36389. };
  36390. /**
  36391. * Wrapper for addUniform.
  36392. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36393. */
  36394. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36395. this.addUniform(name, 12);
  36396. };
  36397. /**
  36398. * Wrapper for addUniform.
  36399. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36400. */
  36401. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36402. this.addUniform(name, 8);
  36403. };
  36404. /**
  36405. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36406. */
  36407. UniformBuffer.prototype.create = function () {
  36408. if (this._noUBO) {
  36409. return;
  36410. }
  36411. if (this._buffer) {
  36412. return; // nothing to do
  36413. }
  36414. // See spec, alignment must be filled as a vec4
  36415. this._fillAlignment(4);
  36416. this._bufferData = new Float32Array(this._data);
  36417. this._rebuild();
  36418. this._needSync = true;
  36419. };
  36420. UniformBuffer.prototype._rebuild = function () {
  36421. if (this._noUBO) {
  36422. return;
  36423. }
  36424. if (this._dynamic) {
  36425. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36426. }
  36427. else {
  36428. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36429. }
  36430. };
  36431. /**
  36432. * Updates the WebGL Uniform Buffer on the GPU.
  36433. * If the `dynamic` flag is set to true, no cache comparison is done.
  36434. * Otherwise, the buffer will be updated only if the cache differs.
  36435. */
  36436. UniformBuffer.prototype.update = function () {
  36437. if (!this._buffer) {
  36438. this.create();
  36439. return;
  36440. }
  36441. if (!this._dynamic && !this._needSync) {
  36442. return;
  36443. }
  36444. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36445. this._needSync = false;
  36446. };
  36447. /**
  36448. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36449. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36450. * @param {number[]|Float32Array} data Flattened data
  36451. * @param {number} size Size of the data.
  36452. */
  36453. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36454. var location = this._uniformLocations[uniformName];
  36455. if (location === undefined) {
  36456. if (this._buffer) {
  36457. // Cannot add an uniform if the buffer is already created
  36458. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36459. return;
  36460. }
  36461. this.addUniform(uniformName, size);
  36462. location = this._uniformLocations[uniformName];
  36463. }
  36464. if (!this._buffer) {
  36465. this.create();
  36466. }
  36467. if (!this._dynamic) {
  36468. // Cache for static uniform buffers
  36469. var changed = false;
  36470. for (var i = 0; i < size; i++) {
  36471. if (this._bufferData[location + i] !== data[i]) {
  36472. changed = true;
  36473. this._bufferData[location + i] = data[i];
  36474. }
  36475. }
  36476. this._needSync = this._needSync || changed;
  36477. }
  36478. else {
  36479. // No cache for dynamic
  36480. for (var i = 0; i < size; i++) {
  36481. this._bufferData[location + i] = data[i];
  36482. }
  36483. }
  36484. };
  36485. // Update methods
  36486. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36487. // To match std140, matrix must be realigned
  36488. for (var i = 0; i < 3; i++) {
  36489. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36490. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36491. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36492. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36493. }
  36494. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36495. };
  36496. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36497. this._currentEffect.setMatrix3x3(name, matrix);
  36498. };
  36499. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36500. this._currentEffect.setMatrix2x2(name, matrix);
  36501. };
  36502. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36503. // To match std140, matrix must be realigned
  36504. for (var i = 0; i < 2; i++) {
  36505. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36506. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36507. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36508. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36509. }
  36510. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36511. };
  36512. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36513. this._currentEffect.setFloat(name, x);
  36514. };
  36515. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36516. UniformBuffer._tempBuffer[0] = x;
  36517. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36518. };
  36519. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36520. if (suffix === void 0) { suffix = ""; }
  36521. this._currentEffect.setFloat2(name + suffix, x, y);
  36522. };
  36523. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36524. if (suffix === void 0) { suffix = ""; }
  36525. UniformBuffer._tempBuffer[0] = x;
  36526. UniformBuffer._tempBuffer[1] = y;
  36527. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36528. };
  36529. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36530. if (suffix === void 0) { suffix = ""; }
  36531. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36532. };
  36533. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36534. if (suffix === void 0) { suffix = ""; }
  36535. UniformBuffer._tempBuffer[0] = x;
  36536. UniformBuffer._tempBuffer[1] = y;
  36537. UniformBuffer._tempBuffer[2] = z;
  36538. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36539. };
  36540. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36541. if (suffix === void 0) { suffix = ""; }
  36542. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36543. };
  36544. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36545. if (suffix === void 0) { suffix = ""; }
  36546. UniformBuffer._tempBuffer[0] = x;
  36547. UniformBuffer._tempBuffer[1] = y;
  36548. UniformBuffer._tempBuffer[2] = z;
  36549. UniformBuffer._tempBuffer[3] = w;
  36550. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36551. };
  36552. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36553. this._currentEffect.setMatrix(name, mat);
  36554. };
  36555. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36556. this.updateUniform(name, mat.toArray(), 16);
  36557. };
  36558. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36559. this._currentEffect.setVector3(name, vector);
  36560. };
  36561. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36562. vector.toArray(UniformBuffer._tempBuffer);
  36563. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36564. };
  36565. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36566. this._currentEffect.setVector4(name, vector);
  36567. };
  36568. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36569. vector.toArray(UniformBuffer._tempBuffer);
  36570. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36571. };
  36572. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36573. if (suffix === void 0) { suffix = ""; }
  36574. this._currentEffect.setColor3(name + suffix, color);
  36575. };
  36576. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36577. if (suffix === void 0) { suffix = ""; }
  36578. color.toArray(UniformBuffer._tempBuffer);
  36579. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36580. };
  36581. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36582. if (suffix === void 0) { suffix = ""; }
  36583. this._currentEffect.setColor4(name + suffix, color, alpha);
  36584. };
  36585. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36586. if (suffix === void 0) { suffix = ""; }
  36587. color.toArray(UniformBuffer._tempBuffer);
  36588. UniformBuffer._tempBuffer[3] = alpha;
  36589. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36590. };
  36591. /**
  36592. * Sets a sampler uniform on the effect.
  36593. * @param {string} name Name of the sampler.
  36594. * @param {Texture} texture
  36595. */
  36596. UniformBuffer.prototype.setTexture = function (name, texture) {
  36597. this._currentEffect.setTexture(name, texture);
  36598. };
  36599. /**
  36600. * Directly updates the value of the uniform in the cache AND on the GPU.
  36601. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36602. * @param {number[]|Float32Array} data Flattened data
  36603. */
  36604. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36605. this.updateUniform(uniformName, data, data.length);
  36606. this.update();
  36607. };
  36608. /**
  36609. * Binds this uniform buffer to an effect.
  36610. * @param {Effect} effect
  36611. * @param {string} name Name of the uniform block in the shader.
  36612. */
  36613. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36614. this._currentEffect = effect;
  36615. if (this._noUBO || !this._buffer) {
  36616. return;
  36617. }
  36618. effect.bindUniformBuffer(this._buffer, name);
  36619. };
  36620. /**
  36621. * Disposes the uniform buffer.
  36622. */
  36623. UniformBuffer.prototype.dispose = function () {
  36624. if (this._noUBO) {
  36625. return;
  36626. }
  36627. var index = this._engine._uniformBuffers.indexOf(this);
  36628. if (index !== -1) {
  36629. this._engine._uniformBuffers.splice(index, 1);
  36630. }
  36631. if (!this._buffer) {
  36632. return;
  36633. }
  36634. if (this._engine._releaseBuffer(this._buffer)) {
  36635. this._buffer = null;
  36636. }
  36637. };
  36638. // Pool for avoiding memory leaks
  36639. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36640. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36641. return UniformBuffer;
  36642. }());
  36643. BABYLON.UniformBuffer = UniformBuffer;
  36644. })(BABYLON || (BABYLON = {}));
  36645. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36646. var BABYLON;
  36647. (function (BABYLON) {
  36648. /**
  36649. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36650. */
  36651. var VertexData = /** @class */ (function () {
  36652. function VertexData() {
  36653. }
  36654. /**
  36655. * Uses the passed data array to set the set the values for the specified kind of data
  36656. * @param data a linear array of floating numbers
  36657. * @param kind the type of data that is being set, eg positions, colors etc
  36658. */
  36659. VertexData.prototype.set = function (data, kind) {
  36660. switch (kind) {
  36661. case BABYLON.VertexBuffer.PositionKind:
  36662. this.positions = data;
  36663. break;
  36664. case BABYLON.VertexBuffer.NormalKind:
  36665. this.normals = data;
  36666. break;
  36667. case BABYLON.VertexBuffer.TangentKind:
  36668. this.tangents = data;
  36669. break;
  36670. case BABYLON.VertexBuffer.UVKind:
  36671. this.uvs = data;
  36672. break;
  36673. case BABYLON.VertexBuffer.UV2Kind:
  36674. this.uvs2 = data;
  36675. break;
  36676. case BABYLON.VertexBuffer.UV3Kind:
  36677. this.uvs3 = data;
  36678. break;
  36679. case BABYLON.VertexBuffer.UV4Kind:
  36680. this.uvs4 = data;
  36681. break;
  36682. case BABYLON.VertexBuffer.UV5Kind:
  36683. this.uvs5 = data;
  36684. break;
  36685. case BABYLON.VertexBuffer.UV6Kind:
  36686. this.uvs6 = data;
  36687. break;
  36688. case BABYLON.VertexBuffer.ColorKind:
  36689. this.colors = data;
  36690. break;
  36691. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36692. this.matricesIndices = data;
  36693. break;
  36694. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36695. this.matricesWeights = data;
  36696. break;
  36697. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36698. this.matricesIndicesExtra = data;
  36699. break;
  36700. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36701. this.matricesWeightsExtra = data;
  36702. break;
  36703. }
  36704. };
  36705. /**
  36706. * Associates the vertexData to the passed Mesh.
  36707. * Sets it as updatable or not (default `false`)
  36708. * @param mesh the mesh the vertexData is applied to
  36709. * @param updatable when used and having the value true allows new data to update the vertexData
  36710. * @returns the VertexData
  36711. */
  36712. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36713. this._applyTo(mesh, updatable);
  36714. return this;
  36715. };
  36716. /**
  36717. * Associates the vertexData to the passed Geometry.
  36718. * Sets it as updatable or not (default `false`)
  36719. * @param geometry the geometry the vertexData is applied to
  36720. * @param updatable when used and having the value true allows new data to update the vertexData
  36721. * @returns VertexData
  36722. */
  36723. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36724. this._applyTo(geometry, updatable);
  36725. return this;
  36726. };
  36727. /**
  36728. * Updates the associated mesh
  36729. * @param mesh the mesh to be updated
  36730. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36731. * @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
  36732. * @returns VertexData
  36733. */
  36734. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36735. this._update(mesh);
  36736. return this;
  36737. };
  36738. /**
  36739. * Updates the associated geometry
  36740. * @param geometry the geometry to be updated
  36741. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36742. * @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
  36743. * @returns VertexData.
  36744. */
  36745. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36746. this._update(geometry);
  36747. return this;
  36748. };
  36749. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36750. if (updatable === void 0) { updatable = false; }
  36751. if (this.positions) {
  36752. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36753. }
  36754. if (this.normals) {
  36755. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36756. }
  36757. if (this.tangents) {
  36758. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36759. }
  36760. if (this.uvs) {
  36761. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36762. }
  36763. if (this.uvs2) {
  36764. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36765. }
  36766. if (this.uvs3) {
  36767. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36768. }
  36769. if (this.uvs4) {
  36770. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36771. }
  36772. if (this.uvs5) {
  36773. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36774. }
  36775. if (this.uvs6) {
  36776. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36777. }
  36778. if (this.colors) {
  36779. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36780. }
  36781. if (this.matricesIndices) {
  36782. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36783. }
  36784. if (this.matricesWeights) {
  36785. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36786. }
  36787. if (this.matricesIndicesExtra) {
  36788. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36789. }
  36790. if (this.matricesWeightsExtra) {
  36791. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36792. }
  36793. if (this.indices) {
  36794. meshOrGeometry.setIndices(this.indices, null, updatable);
  36795. }
  36796. else {
  36797. meshOrGeometry.setIndices([], null);
  36798. }
  36799. return this;
  36800. };
  36801. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36802. if (this.positions) {
  36803. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36804. }
  36805. if (this.normals) {
  36806. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36807. }
  36808. if (this.tangents) {
  36809. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36810. }
  36811. if (this.uvs) {
  36812. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36813. }
  36814. if (this.uvs2) {
  36815. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36816. }
  36817. if (this.uvs3) {
  36818. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36819. }
  36820. if (this.uvs4) {
  36821. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36822. }
  36823. if (this.uvs5) {
  36824. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36825. }
  36826. if (this.uvs6) {
  36827. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36828. }
  36829. if (this.colors) {
  36830. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36831. }
  36832. if (this.matricesIndices) {
  36833. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36834. }
  36835. if (this.matricesWeights) {
  36836. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36837. }
  36838. if (this.matricesIndicesExtra) {
  36839. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36840. }
  36841. if (this.matricesWeightsExtra) {
  36842. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36843. }
  36844. if (this.indices) {
  36845. meshOrGeometry.setIndices(this.indices, null);
  36846. }
  36847. return this;
  36848. };
  36849. /**
  36850. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36851. * @param matrix the transforming matrix
  36852. * @returns the VertexData
  36853. */
  36854. VertexData.prototype.transform = function (matrix) {
  36855. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36856. var transformed = BABYLON.Vector3.Zero();
  36857. var index;
  36858. if (this.positions) {
  36859. var position = BABYLON.Vector3.Zero();
  36860. for (index = 0; index < this.positions.length; index += 3) {
  36861. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36862. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36863. this.positions[index] = transformed.x;
  36864. this.positions[index + 1] = transformed.y;
  36865. this.positions[index + 2] = transformed.z;
  36866. }
  36867. }
  36868. if (this.normals) {
  36869. var normal = BABYLON.Vector3.Zero();
  36870. for (index = 0; index < this.normals.length; index += 3) {
  36871. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36872. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36873. this.normals[index] = transformed.x;
  36874. this.normals[index + 1] = transformed.y;
  36875. this.normals[index + 2] = transformed.z;
  36876. }
  36877. }
  36878. if (this.tangents) {
  36879. var tangent = BABYLON.Vector4.Zero();
  36880. var tangentTransformed = BABYLON.Vector4.Zero();
  36881. for (index = 0; index < this.tangents.length; index += 4) {
  36882. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36883. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36884. this.tangents[index] = tangentTransformed.x;
  36885. this.tangents[index + 1] = tangentTransformed.y;
  36886. this.tangents[index + 2] = tangentTransformed.z;
  36887. this.tangents[index + 3] = tangentTransformed.w;
  36888. }
  36889. }
  36890. if (flip && this.indices) {
  36891. for (index = 0; index < this.indices.length; index += 3) {
  36892. var tmp = this.indices[index + 1];
  36893. this.indices[index + 1] = this.indices[index + 2];
  36894. this.indices[index + 2] = tmp;
  36895. }
  36896. }
  36897. return this;
  36898. };
  36899. /**
  36900. * Merges the passed VertexData into the current one
  36901. * @param other the VertexData to be merged into the current one
  36902. * @returns the modified VertexData
  36903. */
  36904. VertexData.prototype.merge = function (other) {
  36905. this._validate();
  36906. other._validate();
  36907. if (!this.normals !== !other.normals ||
  36908. !this.tangents !== !other.tangents ||
  36909. !this.uvs !== !other.uvs ||
  36910. !this.uvs2 !== !other.uvs2 ||
  36911. !this.uvs3 !== !other.uvs3 ||
  36912. !this.uvs4 !== !other.uvs4 ||
  36913. !this.uvs5 !== !other.uvs5 ||
  36914. !this.uvs6 !== !other.uvs6 ||
  36915. !this.colors !== !other.colors ||
  36916. !this.matricesIndices !== !other.matricesIndices ||
  36917. !this.matricesWeights !== !other.matricesWeights ||
  36918. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36919. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36920. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36921. }
  36922. if (other.indices) {
  36923. if (!this.indices) {
  36924. this.indices = [];
  36925. }
  36926. var offset = this.positions ? this.positions.length / 3 : 0;
  36927. for (var index = 0; index < other.indices.length; index++) {
  36928. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36929. this.indices.push(other.indices[index] + offset);
  36930. }
  36931. }
  36932. this.positions = this._mergeElement(this.positions, other.positions);
  36933. this.normals = this._mergeElement(this.normals, other.normals);
  36934. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36935. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36936. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36937. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36938. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36939. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36940. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36941. this.colors = this._mergeElement(this.colors, other.colors);
  36942. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36943. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36944. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36945. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36946. return this;
  36947. };
  36948. VertexData.prototype._mergeElement = function (source, other) {
  36949. if (!source) {
  36950. return other;
  36951. }
  36952. if (!other) {
  36953. return source;
  36954. }
  36955. var len = other.length + source.length;
  36956. var isSrcTypedArray = source instanceof Float32Array;
  36957. var isOthTypedArray = other instanceof Float32Array;
  36958. // use non-loop method when the source is Float32Array
  36959. if (isSrcTypedArray) {
  36960. var ret32 = new Float32Array(len);
  36961. ret32.set(source);
  36962. ret32.set(other, source.length);
  36963. return ret32;
  36964. // source is number[], when other is also use concat
  36965. }
  36966. else if (!isOthTypedArray) {
  36967. return source.concat(other);
  36968. // source is a number[], but other is a Float32Array, loop required
  36969. }
  36970. else {
  36971. var ret = source.slice(0); // copy source to a separate array
  36972. for (var i = 0, len = other.length; i < len; i++) {
  36973. ret.push(other[i]);
  36974. }
  36975. return ret;
  36976. }
  36977. };
  36978. VertexData.prototype._validate = function () {
  36979. if (!this.positions) {
  36980. throw new Error("Positions are required");
  36981. }
  36982. var getElementCount = function (kind, values) {
  36983. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36984. if ((values.length % stride) !== 0) {
  36985. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36986. }
  36987. return values.length / stride;
  36988. };
  36989. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36990. var validateElementCount = function (kind, values) {
  36991. var elementCount = getElementCount(kind, values);
  36992. if (elementCount !== positionsElementCount) {
  36993. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36994. }
  36995. };
  36996. if (this.normals)
  36997. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36998. if (this.tangents)
  36999. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37000. if (this.uvs)
  37001. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37002. if (this.uvs2)
  37003. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37004. if (this.uvs3)
  37005. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37006. if (this.uvs4)
  37007. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37008. if (this.uvs5)
  37009. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37010. if (this.uvs6)
  37011. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37012. if (this.colors)
  37013. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37014. if (this.matricesIndices)
  37015. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37016. if (this.matricesWeights)
  37017. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37018. if (this.matricesIndicesExtra)
  37019. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37020. if (this.matricesWeightsExtra)
  37021. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37022. };
  37023. /**
  37024. * Serializes the VertexData
  37025. * @returns a serialized object
  37026. */
  37027. VertexData.prototype.serialize = function () {
  37028. var serializationObject = this.serialize();
  37029. if (this.positions) {
  37030. serializationObject.positions = this.positions;
  37031. }
  37032. if (this.normals) {
  37033. serializationObject.normals = this.normals;
  37034. }
  37035. if (this.tangents) {
  37036. serializationObject.tangents = this.tangents;
  37037. }
  37038. if (this.uvs) {
  37039. serializationObject.uvs = this.uvs;
  37040. }
  37041. if (this.uvs2) {
  37042. serializationObject.uvs2 = this.uvs2;
  37043. }
  37044. if (this.uvs3) {
  37045. serializationObject.uvs3 = this.uvs3;
  37046. }
  37047. if (this.uvs4) {
  37048. serializationObject.uvs4 = this.uvs4;
  37049. }
  37050. if (this.uvs5) {
  37051. serializationObject.uvs5 = this.uvs5;
  37052. }
  37053. if (this.uvs6) {
  37054. serializationObject.uvs6 = this.uvs6;
  37055. }
  37056. if (this.colors) {
  37057. serializationObject.colors = this.colors;
  37058. }
  37059. if (this.matricesIndices) {
  37060. serializationObject.matricesIndices = this.matricesIndices;
  37061. serializationObject.matricesIndices._isExpanded = true;
  37062. }
  37063. if (this.matricesWeights) {
  37064. serializationObject.matricesWeights = this.matricesWeights;
  37065. }
  37066. if (this.matricesIndicesExtra) {
  37067. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37068. serializationObject.matricesIndicesExtra._isExpanded = true;
  37069. }
  37070. if (this.matricesWeightsExtra) {
  37071. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37072. }
  37073. serializationObject.indices = this.indices;
  37074. return serializationObject;
  37075. };
  37076. // Statics
  37077. /**
  37078. * Extracts the vertexData from a mesh
  37079. * @param mesh the mesh from which to extract the VertexData
  37080. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37081. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37082. * @returns the object VertexData associated to the passed mesh
  37083. */
  37084. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37085. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37086. };
  37087. /**
  37088. * Extracts the vertexData from the geometry
  37089. * @param geometry the geometry from which to extract the VertexData
  37090. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37091. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37092. * @returns the object VertexData associated to the passed mesh
  37093. */
  37094. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37095. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37096. };
  37097. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37098. var result = new VertexData();
  37099. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37100. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37101. }
  37102. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37103. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37104. }
  37105. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37106. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37107. }
  37108. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37109. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37110. }
  37111. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37112. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37113. }
  37114. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37115. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37116. }
  37117. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37118. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37119. }
  37120. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37121. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37122. }
  37123. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37124. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37125. }
  37126. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37127. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37128. }
  37129. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37130. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37131. }
  37132. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37133. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37134. }
  37135. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37136. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37137. }
  37138. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37139. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37140. }
  37141. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37142. return result;
  37143. };
  37144. /**
  37145. * Creates the VertexData for a Ribbon
  37146. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37147. * * pathArray array of paths, each of which an array of successive Vector3
  37148. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37149. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37150. * * 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
  37151. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37152. * * 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)
  37153. * * 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)
  37154. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37155. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37156. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37157. * @returns the VertexData of the ribbon
  37158. */
  37159. VertexData.CreateRibbon = function (options) {
  37160. var pathArray = options.pathArray;
  37161. var closeArray = options.closeArray || false;
  37162. var closePath = options.closePath || false;
  37163. var invertUV = options.invertUV || false;
  37164. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37165. var offset = options.offset || defaultOffset;
  37166. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37167. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37168. var customUV = options.uvs;
  37169. var customColors = options.colors;
  37170. var positions = [];
  37171. var indices = [];
  37172. var normals = [];
  37173. var uvs = [];
  37174. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37175. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37176. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37177. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37178. var minlg; // minimal length among all paths from pathArray
  37179. var lg = []; // array of path lengths : nb of vertex per path
  37180. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37181. var p; // path iterator
  37182. var i; // point iterator
  37183. var j; // point iterator
  37184. // if single path in pathArray
  37185. if (pathArray.length < 2) {
  37186. var ar1 = [];
  37187. var ar2 = [];
  37188. for (i = 0; i < pathArray[0].length - offset; i++) {
  37189. ar1.push(pathArray[0][i]);
  37190. ar2.push(pathArray[0][i + offset]);
  37191. }
  37192. pathArray = [ar1, ar2];
  37193. }
  37194. // positions and horizontal distances (u)
  37195. var idc = 0;
  37196. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37197. var path;
  37198. var l;
  37199. minlg = pathArray[0].length;
  37200. var vectlg;
  37201. var dist;
  37202. for (p = 0; p < pathArray.length; p++) {
  37203. uTotalDistance[p] = 0;
  37204. us[p] = [0];
  37205. path = pathArray[p];
  37206. l = path.length;
  37207. minlg = (minlg < l) ? minlg : l;
  37208. j = 0;
  37209. while (j < l) {
  37210. positions.push(path[j].x, path[j].y, path[j].z);
  37211. if (j > 0) {
  37212. vectlg = path[j].subtract(path[j - 1]).length();
  37213. dist = vectlg + uTotalDistance[p];
  37214. us[p].push(dist);
  37215. uTotalDistance[p] = dist;
  37216. }
  37217. j++;
  37218. }
  37219. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37220. j--;
  37221. positions.push(path[0].x, path[0].y, path[0].z);
  37222. vectlg = path[j].subtract(path[0]).length();
  37223. dist = vectlg + uTotalDistance[p];
  37224. us[p].push(dist);
  37225. uTotalDistance[p] = dist;
  37226. }
  37227. lg[p] = l + closePathCorr;
  37228. idx[p] = idc;
  37229. idc += (l + closePathCorr);
  37230. }
  37231. // vertical distances (v)
  37232. var path1;
  37233. var path2;
  37234. var vertex1 = null;
  37235. var vertex2 = null;
  37236. for (i = 0; i < minlg + closePathCorr; i++) {
  37237. vTotalDistance[i] = 0;
  37238. vs[i] = [0];
  37239. for (p = 0; p < pathArray.length - 1; p++) {
  37240. path1 = pathArray[p];
  37241. path2 = pathArray[p + 1];
  37242. if (i === minlg) { // closePath
  37243. vertex1 = path1[0];
  37244. vertex2 = path2[0];
  37245. }
  37246. else {
  37247. vertex1 = path1[i];
  37248. vertex2 = path2[i];
  37249. }
  37250. vectlg = vertex2.subtract(vertex1).length();
  37251. dist = vectlg + vTotalDistance[i];
  37252. vs[i].push(dist);
  37253. vTotalDistance[i] = dist;
  37254. }
  37255. if (closeArray && vertex2 && vertex1) {
  37256. path1 = pathArray[p];
  37257. path2 = pathArray[0];
  37258. if (i === minlg) { // closePath
  37259. vertex2 = path2[0];
  37260. }
  37261. vectlg = vertex2.subtract(vertex1).length();
  37262. dist = vectlg + vTotalDistance[i];
  37263. vTotalDistance[i] = dist;
  37264. }
  37265. }
  37266. // uvs
  37267. var u;
  37268. var v;
  37269. if (customUV) {
  37270. for (p = 0; p < customUV.length; p++) {
  37271. uvs.push(customUV[p].x, customUV[p].y);
  37272. }
  37273. }
  37274. else {
  37275. for (p = 0; p < pathArray.length; p++) {
  37276. for (i = 0; i < minlg + closePathCorr; i++) {
  37277. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37278. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37279. if (invertUV) {
  37280. uvs.push(v, u);
  37281. }
  37282. else {
  37283. uvs.push(u, v);
  37284. }
  37285. }
  37286. }
  37287. }
  37288. // indices
  37289. p = 0; // path index
  37290. var pi = 0; // positions array index
  37291. var l1 = lg[p] - 1; // path1 length
  37292. var l2 = lg[p + 1] - 1; // path2 length
  37293. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37294. var shft = idx[1] - idx[0]; // shift
  37295. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37296. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37297. // 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
  37298. indices.push(pi, pi + shft, pi + 1);
  37299. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37300. pi += 1;
  37301. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37302. p++;
  37303. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37304. shft = idx[0] - idx[p];
  37305. l1 = lg[p] - 1;
  37306. l2 = lg[0] - 1;
  37307. }
  37308. else {
  37309. shft = idx[p + 1] - idx[p];
  37310. l1 = lg[p] - 1;
  37311. l2 = lg[p + 1] - 1;
  37312. }
  37313. pi = idx[p];
  37314. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37315. }
  37316. }
  37317. // normals
  37318. VertexData.ComputeNormals(positions, indices, normals);
  37319. if (closePath) { // update both the first and last vertex normals to their average value
  37320. var indexFirst = 0;
  37321. var indexLast = 0;
  37322. for (p = 0; p < pathArray.length; p++) {
  37323. indexFirst = idx[p] * 3;
  37324. if (p + 1 < pathArray.length) {
  37325. indexLast = (idx[p + 1] - 1) * 3;
  37326. }
  37327. else {
  37328. indexLast = normals.length - 3;
  37329. }
  37330. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37331. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37332. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37333. normals[indexLast] = normals[indexFirst];
  37334. normals[indexLast + 1] = normals[indexFirst + 1];
  37335. normals[indexLast + 2] = normals[indexFirst + 2];
  37336. }
  37337. }
  37338. // sides
  37339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37340. // Colors
  37341. var colors = null;
  37342. if (customColors) {
  37343. colors = new Float32Array(customColors.length * 4);
  37344. for (var c = 0; c < customColors.length; c++) {
  37345. colors[c * 4] = customColors[c].r;
  37346. colors[c * 4 + 1] = customColors[c].g;
  37347. colors[c * 4 + 2] = customColors[c].b;
  37348. colors[c * 4 + 3] = customColors[c].a;
  37349. }
  37350. }
  37351. // Result
  37352. var vertexData = new VertexData();
  37353. var positions32 = new Float32Array(positions);
  37354. var normals32 = new Float32Array(normals);
  37355. var uvs32 = new Float32Array(uvs);
  37356. vertexData.indices = indices;
  37357. vertexData.positions = positions32;
  37358. vertexData.normals = normals32;
  37359. vertexData.uvs = uvs32;
  37360. if (colors) {
  37361. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37362. }
  37363. if (closePath) {
  37364. vertexData._idx = idx;
  37365. }
  37366. return vertexData;
  37367. };
  37368. /**
  37369. * Creates the VertexData for a box
  37370. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37371. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37372. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37373. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37374. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37375. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37376. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37377. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37378. * * 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)
  37379. * * 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)
  37380. * @returns the VertexData of the box
  37381. */
  37382. VertexData.CreateBox = function (options) {
  37383. var normalsSource = [
  37384. new BABYLON.Vector3(0, 0, 1),
  37385. new BABYLON.Vector3(0, 0, -1),
  37386. new BABYLON.Vector3(1, 0, 0),
  37387. new BABYLON.Vector3(-1, 0, 0),
  37388. new BABYLON.Vector3(0, 1, 0),
  37389. new BABYLON.Vector3(0, -1, 0)
  37390. ];
  37391. var indices = [];
  37392. var positions = [];
  37393. var normals = [];
  37394. var uvs = [];
  37395. var width = options.width || options.size || 1;
  37396. var height = options.height || options.size || 1;
  37397. var depth = options.depth || options.size || 1;
  37398. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37399. var faceUV = options.faceUV || new Array(6);
  37400. var faceColors = options.faceColors;
  37401. var colors = [];
  37402. // default face colors and UV if undefined
  37403. for (var f = 0; f < 6; f++) {
  37404. if (faceUV[f] === undefined) {
  37405. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37406. }
  37407. if (faceColors && faceColors[f] === undefined) {
  37408. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37409. }
  37410. }
  37411. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37412. // Create each face in turn.
  37413. for (var index = 0; index < normalsSource.length; index++) {
  37414. var normal = normalsSource[index];
  37415. // Get two vectors perpendicular to the face normal and to each other.
  37416. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37417. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37418. // Six indices (two triangles) per face.
  37419. var verticesLength = positions.length / 3;
  37420. indices.push(verticesLength);
  37421. indices.push(verticesLength + 1);
  37422. indices.push(verticesLength + 2);
  37423. indices.push(verticesLength);
  37424. indices.push(verticesLength + 2);
  37425. indices.push(verticesLength + 3);
  37426. // Four vertices per face.
  37427. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37428. positions.push(vertex.x, vertex.y, vertex.z);
  37429. normals.push(normal.x, normal.y, normal.z);
  37430. uvs.push(faceUV[index].z, faceUV[index].w);
  37431. if (faceColors) {
  37432. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37433. }
  37434. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37435. positions.push(vertex.x, vertex.y, vertex.z);
  37436. normals.push(normal.x, normal.y, normal.z);
  37437. uvs.push(faceUV[index].x, faceUV[index].w);
  37438. if (faceColors) {
  37439. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37440. }
  37441. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37442. positions.push(vertex.x, vertex.y, vertex.z);
  37443. normals.push(normal.x, normal.y, normal.z);
  37444. uvs.push(faceUV[index].x, faceUV[index].y);
  37445. if (faceColors) {
  37446. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37447. }
  37448. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37449. positions.push(vertex.x, vertex.y, vertex.z);
  37450. normals.push(normal.x, normal.y, normal.z);
  37451. uvs.push(faceUV[index].z, faceUV[index].y);
  37452. if (faceColors) {
  37453. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37454. }
  37455. }
  37456. // sides
  37457. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37458. // Result
  37459. var vertexData = new VertexData();
  37460. vertexData.indices = indices;
  37461. vertexData.positions = positions;
  37462. vertexData.normals = normals;
  37463. vertexData.uvs = uvs;
  37464. if (faceColors) {
  37465. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37466. vertexData.colors = totalColors;
  37467. }
  37468. return vertexData;
  37469. };
  37470. /**
  37471. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37472. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37473. * * segments sets the number of horizontal strips optional, default 32
  37474. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37475. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37476. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37477. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37478. * * 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
  37479. * * 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
  37480. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37481. * * 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)
  37482. * * 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)
  37483. * @returns the VertexData of the ellipsoid
  37484. */
  37485. VertexData.CreateSphere = function (options) {
  37486. var segments = options.segments || 32;
  37487. var diameterX = options.diameterX || options.diameter || 1;
  37488. var diameterY = options.diameterY || options.diameter || 1;
  37489. var diameterZ = options.diameterZ || options.diameter || 1;
  37490. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37491. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37492. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37493. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37494. var totalZRotationSteps = 2 + segments;
  37495. var totalYRotationSteps = 2 * totalZRotationSteps;
  37496. var indices = [];
  37497. var positions = [];
  37498. var normals = [];
  37499. var uvs = [];
  37500. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37501. var normalizedZ = zRotationStep / totalZRotationSteps;
  37502. var angleZ = normalizedZ * Math.PI * slice;
  37503. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37504. var normalizedY = yRotationStep / totalYRotationSteps;
  37505. var angleY = normalizedY * Math.PI * 2 * arc;
  37506. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37507. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37508. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37509. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37510. var vertex = complete.multiply(radius);
  37511. var normal = complete.divide(radius).normalize();
  37512. positions.push(vertex.x, vertex.y, vertex.z);
  37513. normals.push(normal.x, normal.y, normal.z);
  37514. uvs.push(normalizedY, normalizedZ);
  37515. }
  37516. if (zRotationStep > 0) {
  37517. var verticesCount = positions.length / 3;
  37518. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37519. indices.push((firstIndex));
  37520. indices.push((firstIndex + 1));
  37521. indices.push(firstIndex + totalYRotationSteps + 1);
  37522. indices.push((firstIndex + totalYRotationSteps + 1));
  37523. indices.push((firstIndex + 1));
  37524. indices.push((firstIndex + totalYRotationSteps + 2));
  37525. }
  37526. }
  37527. }
  37528. // Sides
  37529. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37530. // Result
  37531. var vertexData = new VertexData();
  37532. vertexData.indices = indices;
  37533. vertexData.positions = positions;
  37534. vertexData.normals = normals;
  37535. vertexData.uvs = uvs;
  37536. return vertexData;
  37537. };
  37538. /**
  37539. * Creates the VertexData for a cylinder, cone or prism
  37540. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37541. * * height sets the height (y direction) of the cylinder, optional, default 2
  37542. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37543. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37544. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37545. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37546. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37547. * * 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
  37548. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37549. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37550. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37551. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37552. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37553. * * 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)
  37554. * * 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)
  37555. * @returns the VertexData of the cylinder, cone or prism
  37556. */
  37557. VertexData.CreateCylinder = function (options) {
  37558. var height = options.height || 2;
  37559. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37560. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37561. var tessellation = options.tessellation || 24;
  37562. var subdivisions = options.subdivisions || 1;
  37563. var hasRings = options.hasRings ? true : false;
  37564. var enclose = options.enclose ? true : false;
  37565. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37566. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37567. var faceUV = options.faceUV || new Array(3);
  37568. var faceColors = options.faceColors;
  37569. // default face colors and UV if undefined
  37570. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37571. var ringNb = (hasRings) ? subdivisions : 1;
  37572. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37573. var f;
  37574. for (f = 0; f < surfaceNb; f++) {
  37575. if (faceColors && faceColors[f] === undefined) {
  37576. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37577. }
  37578. }
  37579. for (f = 0; f < surfaceNb; f++) {
  37580. if (faceUV && faceUV[f] === undefined) {
  37581. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37582. }
  37583. }
  37584. var indices = new Array();
  37585. var positions = new Array();
  37586. var normals = new Array();
  37587. var uvs = new Array();
  37588. var colors = new Array();
  37589. var angle_step = Math.PI * 2 * arc / tessellation;
  37590. var angle;
  37591. var h;
  37592. var radius;
  37593. var tan = (diameterBottom - diameterTop) / 2 / height;
  37594. var ringVertex = BABYLON.Vector3.Zero();
  37595. var ringNormal = BABYLON.Vector3.Zero();
  37596. var ringFirstVertex = BABYLON.Vector3.Zero();
  37597. var ringFirstNormal = BABYLON.Vector3.Zero();
  37598. var quadNormal = BABYLON.Vector3.Zero();
  37599. var Y = BABYLON.Axis.Y;
  37600. // positions, normals, uvs
  37601. var i;
  37602. var j;
  37603. var r;
  37604. var ringIdx = 1;
  37605. var s = 1; // surface index
  37606. var cs = 0;
  37607. var v = 0;
  37608. for (i = 0; i <= subdivisions; i++) {
  37609. h = i / subdivisions;
  37610. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37611. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37612. for (r = 0; r < ringIdx; r++) {
  37613. if (hasRings) {
  37614. s += r;
  37615. }
  37616. if (enclose) {
  37617. s += 2 * r;
  37618. }
  37619. for (j = 0; j <= tessellation; j++) {
  37620. angle = j * angle_step;
  37621. // position
  37622. ringVertex.x = Math.cos(-angle) * radius;
  37623. ringVertex.y = -height / 2 + h * height;
  37624. ringVertex.z = Math.sin(-angle) * radius;
  37625. // normal
  37626. if (diameterTop === 0 && i === subdivisions) {
  37627. // if no top cap, reuse former normals
  37628. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37629. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37630. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37631. }
  37632. else {
  37633. ringNormal.x = ringVertex.x;
  37634. ringNormal.z = ringVertex.z;
  37635. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37636. ringNormal.normalize();
  37637. }
  37638. // keep first ring vertex values for enclose
  37639. if (j === 0) {
  37640. ringFirstVertex.copyFrom(ringVertex);
  37641. ringFirstNormal.copyFrom(ringNormal);
  37642. }
  37643. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37644. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37645. if (hasRings) {
  37646. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37647. }
  37648. else {
  37649. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37650. }
  37651. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37652. if (faceColors) {
  37653. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37654. }
  37655. }
  37656. // if enclose, add four vertices and their dedicated normals
  37657. if (arc !== 1 && enclose) {
  37658. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37659. positions.push(0, ringVertex.y, 0);
  37660. positions.push(0, ringVertex.y, 0);
  37661. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37662. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37663. quadNormal.normalize();
  37664. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37665. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37666. quadNormal.normalize();
  37667. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37668. if (hasRings) {
  37669. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37670. }
  37671. else {
  37672. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37673. }
  37674. uvs.push(faceUV[s + 1].x, v);
  37675. uvs.push(faceUV[s + 1].z, v);
  37676. if (hasRings) {
  37677. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37678. }
  37679. else {
  37680. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37681. }
  37682. uvs.push(faceUV[s + 2].x, v);
  37683. uvs.push(faceUV[s + 2].z, v);
  37684. if (faceColors) {
  37685. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37686. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37687. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37688. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37689. }
  37690. }
  37691. if (cs !== s) {
  37692. cs = s;
  37693. }
  37694. }
  37695. }
  37696. // indices
  37697. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37698. var s;
  37699. i = 0;
  37700. for (s = 0; s < subdivisions; s++) {
  37701. var i0 = 0;
  37702. var i1 = 0;
  37703. var i2 = 0;
  37704. var i3 = 0;
  37705. for (j = 0; j < tessellation; j++) {
  37706. i0 = i * (e + 1) + j;
  37707. i1 = (i + 1) * (e + 1) + j;
  37708. i2 = i * (e + 1) + (j + 1);
  37709. i3 = (i + 1) * (e + 1) + (j + 1);
  37710. indices.push(i0, i1, i2);
  37711. indices.push(i3, i2, i1);
  37712. }
  37713. if (arc !== 1 && enclose) { // if enclose, add two quads
  37714. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37715. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37716. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37717. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37718. }
  37719. i = (hasRings) ? (i + 2) : (i + 1);
  37720. }
  37721. // Caps
  37722. var createCylinderCap = function (isTop) {
  37723. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37724. if (radius === 0) {
  37725. return;
  37726. }
  37727. // Cap positions, normals & uvs
  37728. var angle;
  37729. var circleVector;
  37730. var i;
  37731. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37732. var c = null;
  37733. if (faceColors) {
  37734. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37735. }
  37736. // cap center
  37737. var vbase = positions.length / 3;
  37738. var offset = isTop ? height / 2 : -height / 2;
  37739. var center = new BABYLON.Vector3(0, offset, 0);
  37740. positions.push(center.x, center.y, center.z);
  37741. normals.push(0, isTop ? 1 : -1, 0);
  37742. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37743. if (c) {
  37744. colors.push(c.r, c.g, c.b, c.a);
  37745. }
  37746. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37747. for (i = 0; i <= tessellation; i++) {
  37748. angle = Math.PI * 2 * i * arc / tessellation;
  37749. var cos = Math.cos(-angle);
  37750. var sin = Math.sin(-angle);
  37751. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37752. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37753. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37754. normals.push(0, isTop ? 1 : -1, 0);
  37755. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37756. if (c) {
  37757. colors.push(c.r, c.g, c.b, c.a);
  37758. }
  37759. }
  37760. // Cap indices
  37761. for (i = 0; i < tessellation; i++) {
  37762. if (!isTop) {
  37763. indices.push(vbase);
  37764. indices.push(vbase + (i + 1));
  37765. indices.push(vbase + (i + 2));
  37766. }
  37767. else {
  37768. indices.push(vbase);
  37769. indices.push(vbase + (i + 2));
  37770. indices.push(vbase + (i + 1));
  37771. }
  37772. }
  37773. };
  37774. // add caps to geometry
  37775. createCylinderCap(false);
  37776. createCylinderCap(true);
  37777. // Sides
  37778. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37779. var vertexData = new VertexData();
  37780. vertexData.indices = indices;
  37781. vertexData.positions = positions;
  37782. vertexData.normals = normals;
  37783. vertexData.uvs = uvs;
  37784. if (faceColors) {
  37785. vertexData.colors = colors;
  37786. }
  37787. return vertexData;
  37788. };
  37789. /**
  37790. * Creates the VertexData for a torus
  37791. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37792. * * diameter the diameter of the torus, optional default 1
  37793. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37794. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37795. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37796. * * 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)
  37797. * * 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)
  37798. * @returns the VertexData of the torus
  37799. */
  37800. VertexData.CreateTorus = function (options) {
  37801. var indices = [];
  37802. var positions = [];
  37803. var normals = [];
  37804. var uvs = [];
  37805. var diameter = options.diameter || 1;
  37806. var thickness = options.thickness || 0.5;
  37807. var tessellation = options.tessellation || 16;
  37808. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37809. var stride = tessellation + 1;
  37810. for (var i = 0; i <= tessellation; i++) {
  37811. var u = i / tessellation;
  37812. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37813. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37814. for (var j = 0; j <= tessellation; j++) {
  37815. var v = 1 - j / tessellation;
  37816. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37817. var dx = Math.cos(innerAngle);
  37818. var dy = Math.sin(innerAngle);
  37819. // Create a vertex.
  37820. var normal = new BABYLON.Vector3(dx, dy, 0);
  37821. var position = normal.scale(thickness / 2);
  37822. var textureCoordinate = new BABYLON.Vector2(u, v);
  37823. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37824. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37825. positions.push(position.x, position.y, position.z);
  37826. normals.push(normal.x, normal.y, normal.z);
  37827. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37828. // And create indices for two triangles.
  37829. var nextI = (i + 1) % stride;
  37830. var nextJ = (j + 1) % stride;
  37831. indices.push(i * stride + j);
  37832. indices.push(i * stride + nextJ);
  37833. indices.push(nextI * stride + j);
  37834. indices.push(i * stride + nextJ);
  37835. indices.push(nextI * stride + nextJ);
  37836. indices.push(nextI * stride + j);
  37837. }
  37838. }
  37839. // Sides
  37840. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37841. // Result
  37842. var vertexData = new VertexData();
  37843. vertexData.indices = indices;
  37844. vertexData.positions = positions;
  37845. vertexData.normals = normals;
  37846. vertexData.uvs = uvs;
  37847. return vertexData;
  37848. };
  37849. /**
  37850. * Creates the VertexData of the LineSystem
  37851. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37852. * - lines an array of lines, each line being an array of successive Vector3
  37853. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37854. * @returns the VertexData of the LineSystem
  37855. */
  37856. VertexData.CreateLineSystem = function (options) {
  37857. var indices = [];
  37858. var positions = [];
  37859. var lines = options.lines;
  37860. var colors = options.colors;
  37861. var vertexColors = [];
  37862. var idx = 0;
  37863. for (var l = 0; l < lines.length; l++) {
  37864. var points = lines[l];
  37865. for (var index = 0; index < points.length; index++) {
  37866. positions.push(points[index].x, points[index].y, points[index].z);
  37867. if (colors) {
  37868. var color = colors[l];
  37869. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37870. }
  37871. if (index > 0) {
  37872. indices.push(idx - 1);
  37873. indices.push(idx);
  37874. }
  37875. idx++;
  37876. }
  37877. }
  37878. var vertexData = new VertexData();
  37879. vertexData.indices = indices;
  37880. vertexData.positions = positions;
  37881. if (colors) {
  37882. vertexData.colors = vertexColors;
  37883. }
  37884. return vertexData;
  37885. };
  37886. /**
  37887. * Create the VertexData for a DashedLines
  37888. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37889. * - points an array successive Vector3
  37890. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37891. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37892. * - dashNb the intended total number of dashes, optional, default 200
  37893. * @returns the VertexData for the DashedLines
  37894. */
  37895. VertexData.CreateDashedLines = function (options) {
  37896. var dashSize = options.dashSize || 3;
  37897. var gapSize = options.gapSize || 1;
  37898. var dashNb = options.dashNb || 200;
  37899. var points = options.points;
  37900. var positions = new Array();
  37901. var indices = new Array();
  37902. var curvect = BABYLON.Vector3.Zero();
  37903. var lg = 0;
  37904. var nb = 0;
  37905. var shft = 0;
  37906. var dashshft = 0;
  37907. var curshft = 0;
  37908. var idx = 0;
  37909. var i = 0;
  37910. for (i = 0; i < points.length - 1; i++) {
  37911. points[i + 1].subtractToRef(points[i], curvect);
  37912. lg += curvect.length();
  37913. }
  37914. shft = lg / dashNb;
  37915. dashshft = dashSize * shft / (dashSize + gapSize);
  37916. for (i = 0; i < points.length - 1; i++) {
  37917. points[i + 1].subtractToRef(points[i], curvect);
  37918. nb = Math.floor(curvect.length() / shft);
  37919. curvect.normalize();
  37920. for (var j = 0; j < nb; j++) {
  37921. curshft = shft * j;
  37922. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37923. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37924. indices.push(idx, idx + 1);
  37925. idx += 2;
  37926. }
  37927. }
  37928. // Result
  37929. var vertexData = new VertexData();
  37930. vertexData.positions = positions;
  37931. vertexData.indices = indices;
  37932. return vertexData;
  37933. };
  37934. /**
  37935. * Creates the VertexData for a Ground
  37936. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37937. * - width the width (x direction) of the ground, optional, default 1
  37938. * - height the height (z direction) of the ground, optional, default 1
  37939. * - subdivisions the number of subdivisions per side, optional, default 1
  37940. * @returns the VertexData of the Ground
  37941. */
  37942. VertexData.CreateGround = function (options) {
  37943. var indices = [];
  37944. var positions = [];
  37945. var normals = [];
  37946. var uvs = [];
  37947. var row, col;
  37948. var width = options.width || 1;
  37949. var height = options.height || 1;
  37950. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37951. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37952. for (row = 0; row <= subdivisionsY; row++) {
  37953. for (col = 0; col <= subdivisionsX; col++) {
  37954. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37955. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37956. positions.push(position.x, position.y, position.z);
  37957. normals.push(normal.x, normal.y, normal.z);
  37958. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37959. }
  37960. }
  37961. for (row = 0; row < subdivisionsY; row++) {
  37962. for (col = 0; col < subdivisionsX; col++) {
  37963. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37964. indices.push(col + 1 + row * (subdivisionsX + 1));
  37965. indices.push(col + row * (subdivisionsX + 1));
  37966. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37967. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37968. indices.push(col + row * (subdivisionsX + 1));
  37969. }
  37970. }
  37971. // Result
  37972. var vertexData = new VertexData();
  37973. vertexData.indices = indices;
  37974. vertexData.positions = positions;
  37975. vertexData.normals = normals;
  37976. vertexData.uvs = uvs;
  37977. return vertexData;
  37978. };
  37979. /**
  37980. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37981. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37982. * * xmin the ground minimum X coordinate, optional, default -1
  37983. * * zmin the ground minimum Z coordinate, optional, default -1
  37984. * * xmax the ground maximum X coordinate, optional, default 1
  37985. * * zmax the ground maximum Z coordinate, optional, default 1
  37986. * * 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}
  37987. * * 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}
  37988. * @returns the VertexData of the TiledGround
  37989. */
  37990. VertexData.CreateTiledGround = function (options) {
  37991. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37992. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37993. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37994. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37995. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37996. var precision = options.precision || { w: 1, h: 1 };
  37997. var indices = new Array();
  37998. var positions = new Array();
  37999. var normals = new Array();
  38000. var uvs = new Array();
  38001. var row, col, tileRow, tileCol;
  38002. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38003. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38004. precision.w = (precision.w < 1) ? 1 : precision.w;
  38005. precision.h = (precision.h < 1) ? 1 : precision.h;
  38006. var tileSize = {
  38007. 'w': (xmax - xmin) / subdivisions.w,
  38008. 'h': (zmax - zmin) / subdivisions.h
  38009. };
  38010. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38011. // Indices
  38012. var base = positions.length / 3;
  38013. var rowLength = precision.w + 1;
  38014. for (row = 0; row < precision.h; row++) {
  38015. for (col = 0; col < precision.w; col++) {
  38016. var square = [
  38017. base + col + row * rowLength,
  38018. base + (col + 1) + row * rowLength,
  38019. base + (col + 1) + (row + 1) * rowLength,
  38020. base + col + (row + 1) * rowLength
  38021. ];
  38022. indices.push(square[1]);
  38023. indices.push(square[2]);
  38024. indices.push(square[3]);
  38025. indices.push(square[0]);
  38026. indices.push(square[1]);
  38027. indices.push(square[3]);
  38028. }
  38029. }
  38030. // Position, normals and uvs
  38031. var position = BABYLON.Vector3.Zero();
  38032. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38033. for (row = 0; row <= precision.h; row++) {
  38034. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38035. for (col = 0; col <= precision.w; col++) {
  38036. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38037. position.y = 0;
  38038. positions.push(position.x, position.y, position.z);
  38039. normals.push(normal.x, normal.y, normal.z);
  38040. uvs.push(col / precision.w, row / precision.h);
  38041. }
  38042. }
  38043. }
  38044. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38045. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38046. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38047. }
  38048. }
  38049. // Result
  38050. var vertexData = new VertexData();
  38051. vertexData.indices = indices;
  38052. vertexData.positions = positions;
  38053. vertexData.normals = normals;
  38054. vertexData.uvs = uvs;
  38055. return vertexData;
  38056. };
  38057. /**
  38058. * Creates the VertexData of the Ground designed from a heightmap
  38059. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38060. * * width the width (x direction) of the ground
  38061. * * height the height (z direction) of the ground
  38062. * * subdivisions the number of subdivisions per side
  38063. * * minHeight the minimum altitude on the ground, optional, default 0
  38064. * * maxHeight the maximum altitude on the ground, optional default 1
  38065. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38066. * * buffer the array holding the image color data
  38067. * * bufferWidth the width of image
  38068. * * bufferHeight the height of image
  38069. * @returns the VertexData of the Ground designed from a heightmap
  38070. */
  38071. VertexData.CreateGroundFromHeightMap = function (options) {
  38072. var indices = [];
  38073. var positions = [];
  38074. var normals = [];
  38075. var uvs = [];
  38076. var row, col;
  38077. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38078. // Vertices
  38079. for (row = 0; row <= options.subdivisions; row++) {
  38080. for (col = 0; col <= options.subdivisions; col++) {
  38081. 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));
  38082. // Compute height
  38083. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38084. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38085. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38086. var r = options.buffer[pos] / 255.0;
  38087. var g = options.buffer[pos + 1] / 255.0;
  38088. var b = options.buffer[pos + 2] / 255.0;
  38089. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38090. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38091. // Add vertex
  38092. positions.push(position.x, position.y, position.z);
  38093. normals.push(0, 0, 0);
  38094. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38095. }
  38096. }
  38097. // Indices
  38098. for (row = 0; row < options.subdivisions; row++) {
  38099. for (col = 0; col < options.subdivisions; col++) {
  38100. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38101. indices.push(col + 1 + row * (options.subdivisions + 1));
  38102. indices.push(col + row * (options.subdivisions + 1));
  38103. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38104. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38105. indices.push(col + row * (options.subdivisions + 1));
  38106. }
  38107. }
  38108. // Normals
  38109. VertexData.ComputeNormals(positions, indices, normals);
  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 for a Plane
  38120. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38121. * * size sets the width and height of the plane to the value of size, optional default 1
  38122. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38123. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  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.CreatePlane = function (options) {
  38130. var indices = [];
  38131. var positions = [];
  38132. var normals = [];
  38133. var uvs = [];
  38134. var width = options.width || options.size || 1;
  38135. var height = options.height || options.size || 1;
  38136. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38137. // Vertices
  38138. var halfWidth = width / 2.0;
  38139. var halfHeight = height / 2.0;
  38140. positions.push(-halfWidth, -halfHeight, 0);
  38141. normals.push(0, 0, -1.0);
  38142. uvs.push(0.0, 0.0);
  38143. positions.push(halfWidth, -halfHeight, 0);
  38144. normals.push(0, 0, -1.0);
  38145. uvs.push(1.0, 0.0);
  38146. positions.push(halfWidth, halfHeight, 0);
  38147. normals.push(0, 0, -1.0);
  38148. uvs.push(1.0, 1.0);
  38149. positions.push(-halfWidth, halfHeight, 0);
  38150. normals.push(0, 0, -1.0);
  38151. uvs.push(0.0, 1.0);
  38152. // Indices
  38153. indices.push(0);
  38154. indices.push(1);
  38155. indices.push(2);
  38156. indices.push(0);
  38157. indices.push(2);
  38158. indices.push(3);
  38159. // Sides
  38160. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38161. // Result
  38162. var vertexData = new VertexData();
  38163. vertexData.indices = indices;
  38164. vertexData.positions = positions;
  38165. vertexData.normals = normals;
  38166. vertexData.uvs = uvs;
  38167. return vertexData;
  38168. };
  38169. /**
  38170. * Creates the VertexData of the Disc or regular Polygon
  38171. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38172. * * radius the radius of the disc, optional default 0.5
  38173. * * tessellation the number of polygon sides, optional, default 64
  38174. * * 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
  38175. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38176. * * 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)
  38177. * * 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)
  38178. * @returns the VertexData of the box
  38179. */
  38180. VertexData.CreateDisc = function (options) {
  38181. var positions = new Array();
  38182. var indices = new Array();
  38183. var normals = new Array();
  38184. var uvs = new Array();
  38185. var radius = options.radius || 0.5;
  38186. var tessellation = options.tessellation || 64;
  38187. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38188. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38189. // positions and uvs
  38190. positions.push(0, 0, 0); // disc center first
  38191. uvs.push(0.5, 0.5);
  38192. var theta = Math.PI * 2 * arc;
  38193. var step = theta / tessellation;
  38194. for (var a = 0; a < theta; a += step) {
  38195. var x = Math.cos(a);
  38196. var y = Math.sin(a);
  38197. var u = (x + 1) / 2;
  38198. var v = (1 - y) / 2;
  38199. positions.push(radius * x, radius * y, 0);
  38200. uvs.push(u, v);
  38201. }
  38202. if (arc === 1) {
  38203. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38204. uvs.push(uvs[2], uvs[3]);
  38205. }
  38206. //indices
  38207. var vertexNb = positions.length / 3;
  38208. for (var i = 1; i < vertexNb - 1; i++) {
  38209. indices.push(i + 1, 0, i);
  38210. }
  38211. // result
  38212. VertexData.ComputeNormals(positions, indices, normals);
  38213. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38214. var vertexData = new VertexData();
  38215. vertexData.indices = indices;
  38216. vertexData.positions = positions;
  38217. vertexData.normals = normals;
  38218. vertexData.uvs = uvs;
  38219. return vertexData;
  38220. };
  38221. /**
  38222. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38223. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38224. * @param polygon a mesh built from polygonTriangulation.build()
  38225. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38226. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38227. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38228. * @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)
  38229. * @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)
  38230. * @returns the VertexData of the Polygon
  38231. */
  38232. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38233. var faceUV = fUV || new Array(3);
  38234. var faceColors = fColors;
  38235. var colors = [];
  38236. // default face colors and UV if undefined
  38237. for (var f = 0; f < 3; f++) {
  38238. if (faceUV[f] === undefined) {
  38239. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38240. }
  38241. if (faceColors && faceColors[f] === undefined) {
  38242. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38243. }
  38244. }
  38245. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38246. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38247. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38248. var indices = polygon.getIndices();
  38249. // set face colours and textures
  38250. var idx = 0;
  38251. var face = 0;
  38252. for (var index = 0; index < normals.length; index += 3) {
  38253. //Edge Face no. 1
  38254. if (Math.abs(normals[index + 1]) < 0.001) {
  38255. face = 1;
  38256. }
  38257. //Top Face no. 0
  38258. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38259. face = 0;
  38260. }
  38261. //Bottom Face no. 2
  38262. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38263. face = 2;
  38264. }
  38265. idx = index / 3;
  38266. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38267. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38268. if (faceColors) {
  38269. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38270. }
  38271. }
  38272. // sides
  38273. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38274. // Result
  38275. var vertexData = new VertexData();
  38276. vertexData.indices = indices;
  38277. vertexData.positions = positions;
  38278. vertexData.normals = normals;
  38279. vertexData.uvs = uvs;
  38280. if (faceColors) {
  38281. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38282. vertexData.colors = totalColors;
  38283. }
  38284. return vertexData;
  38285. };
  38286. /**
  38287. * Creates the VertexData of the IcoSphere
  38288. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38289. * * radius the radius of the IcoSphere, optional default 1
  38290. * * radiusX allows stretching in the x direction, optional, default radius
  38291. * * radiusY allows stretching in the y direction, optional, default radius
  38292. * * radiusZ allows stretching in the z direction, optional, default radius
  38293. * * flat when true creates a flat shaded mesh, optional, default true
  38294. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38295. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38296. * * 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)
  38297. * * 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)
  38298. * @returns the VertexData of the IcoSphere
  38299. */
  38300. VertexData.CreateIcoSphere = function (options) {
  38301. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38302. var radius = options.radius || 1;
  38303. var flat = (options.flat === undefined) ? true : options.flat;
  38304. var subdivisions = options.subdivisions || 4;
  38305. var radiusX = options.radiusX || radius;
  38306. var radiusY = options.radiusY || radius;
  38307. var radiusZ = options.radiusZ || radius;
  38308. var t = (1 + Math.sqrt(5)) / 2;
  38309. // 12 vertex x,y,z
  38310. var ico_vertices = [
  38311. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38312. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38313. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38314. ];
  38315. // index of 3 vertex makes a face of icopshere
  38316. var ico_indices = [
  38317. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38318. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38319. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38320. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38321. ];
  38322. // vertex for uv have aliased position, not for UV
  38323. var vertices_unalias_id = [
  38324. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38325. // vertex alias
  38326. 0,
  38327. 2,
  38328. 3,
  38329. 3,
  38330. 3,
  38331. 4,
  38332. 7,
  38333. 8,
  38334. 9,
  38335. 9,
  38336. 10,
  38337. 11 // 23: B + 12
  38338. ];
  38339. // uv as integer step (not pixels !)
  38340. var ico_vertexuv = [
  38341. 5, 1, 3, 1, 6, 4, 0, 0,
  38342. 5, 3, 4, 2, 2, 2, 4, 0,
  38343. 2, 0, 1, 1, 6, 0, 6, 2,
  38344. // vertex alias (for same vertex on different faces)
  38345. 0, 4,
  38346. 3, 3,
  38347. 4, 4,
  38348. 3, 1,
  38349. 4, 2,
  38350. 4, 4,
  38351. 0, 2,
  38352. 1, 1,
  38353. 2, 2,
  38354. 3, 3,
  38355. 1, 3,
  38356. 2, 4 // 23: B + 12
  38357. ];
  38358. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38359. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38360. // First island of uv mapping
  38361. // v = 4h 3+ 2
  38362. // v = 3h 9+ 4
  38363. // v = 2h 9+ 5 B
  38364. // v = 1h 9 1 0
  38365. // v = 0h 3 8 7 A
  38366. // u = 0 1 2 3 4 5 6 *a
  38367. // Second island of uv mapping
  38368. // v = 4h 0+ B+ 4+
  38369. // v = 3h A+ 2+
  38370. // v = 2h 7+ 6 3+
  38371. // v = 1h 8+ 3+
  38372. // v = 0h
  38373. // u = 0 1 2 3 4 5 6 *a
  38374. // Face layout on texture UV mapping
  38375. // ============
  38376. // \ 4 /\ 16 / ======
  38377. // \ / \ / /\ 11 /
  38378. // \/ 7 \/ / \ /
  38379. // ======= / 10 \/
  38380. // /\ 17 /\ =======
  38381. // / \ / \ \ 15 /\
  38382. // / 8 \/ 12 \ \ / \
  38383. // ============ \/ 6 \
  38384. // \ 18 /\ ============
  38385. // \ / \ \ 5 /\ 0 /
  38386. // \/ 13 \ \ / \ /
  38387. // ======= \/ 1 \/
  38388. // =============
  38389. // /\ 19 /\ 2 /\
  38390. // / \ / \ / \
  38391. // / 14 \/ 9 \/ 3 \
  38392. // ===================
  38393. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38394. var ustep = 138 / 1024;
  38395. var vstep = 239 / 1024;
  38396. var uoffset = 60 / 1024;
  38397. var voffset = 26 / 1024;
  38398. // Second island should have margin, not to touch the first island
  38399. // avoid any borderline artefact in pixel rounding
  38400. var island_u_offset = -40 / 1024;
  38401. var island_v_offset = +20 / 1024;
  38402. // face is either island 0 or 1 :
  38403. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38404. var island = [
  38405. 0, 0, 0, 0, 1,
  38406. 0, 0, 1, 1, 0,
  38407. 0, 0, 1, 1, 0,
  38408. 0, 1, 1, 1, 0 // 15 - 19
  38409. ];
  38410. var indices = new Array();
  38411. var positions = new Array();
  38412. var normals = new Array();
  38413. var uvs = new Array();
  38414. var current_indice = 0;
  38415. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38416. var face_vertex_pos = new Array(3);
  38417. var face_vertex_uv = new Array(3);
  38418. var v012;
  38419. for (v012 = 0; v012 < 3; v012++) {
  38420. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38421. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38422. }
  38423. // create all with normals
  38424. for (var face = 0; face < 20; face++) {
  38425. // 3 vertex per face
  38426. for (v012 = 0; v012 < 3; v012++) {
  38427. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38428. var v_id = ico_indices[3 * face + v012];
  38429. // vertex have 3D position (x,y,z)
  38430. 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]);
  38431. // Normalize to get normal, then scale to radius
  38432. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38433. // uv Coordinates from vertex ID
  38434. 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);
  38435. }
  38436. // Subdivide the face (interpolate pos, norm, uv)
  38437. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38438. // - norm is linear interpolation of vertex corner normal
  38439. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38440. // - uv is linear interpolation
  38441. //
  38442. // Topology is as below for sub-divide by 2
  38443. // vertex shown as v0,v1,v2
  38444. // interp index is i1 to progress in range [v0,v1[
  38445. // interp index is i2 to progress in range [v0,v2[
  38446. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38447. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38448. //
  38449. //
  38450. // i2 v2
  38451. // ^ ^
  38452. // / / \
  38453. // / / \
  38454. // / / \
  38455. // / / (0,1) \
  38456. // / #---------\
  38457. // / / \ (0,0)'/ \
  38458. // / / \ / \
  38459. // / / \ / \
  38460. // / / (0,0) \ / (1,0) \
  38461. // / #---------#---------\
  38462. // v0 v1
  38463. //
  38464. // --------------------> i1
  38465. //
  38466. // interp of (i1,i2):
  38467. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38468. // along i1 : lerp(x0,x1, i1/(S-i2))
  38469. //
  38470. // centroid of triangle is needed to get help normal computation
  38471. // (c1,c2) are used for centroid location
  38472. var interp_vertex = function (i1, i2, c1, c2) {
  38473. // vertex is interpolated from
  38474. // - face_vertex_pos[0..2]
  38475. // - face_vertex_uv[0..2]
  38476. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38477. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38478. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38479. pos_interp.normalize();
  38480. var vertex_normal;
  38481. if (flat) {
  38482. // in flat mode, recalculate normal as face centroid normal
  38483. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38484. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38485. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38486. }
  38487. else {
  38488. // in smooth mode, recalculate normal from each single vertex position
  38489. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38490. }
  38491. // Vertex normal need correction due to X,Y,Z radius scaling
  38492. vertex_normal.x /= radiusX;
  38493. vertex_normal.y /= radiusY;
  38494. vertex_normal.z /= radiusZ;
  38495. vertex_normal.normalize();
  38496. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38497. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38498. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38499. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38500. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38501. uvs.push(uv_interp.x, uv_interp.y);
  38502. // push each vertex has member of a face
  38503. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38504. indices.push(current_indice);
  38505. current_indice++;
  38506. };
  38507. for (var i2 = 0; i2 < subdivisions; i2++) {
  38508. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38509. // face : (i1,i2) for /\ :
  38510. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38511. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38512. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38513. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38514. if (i1 + i2 + 1 < subdivisions) {
  38515. // face : (i1,i2)' for \/ :
  38516. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38517. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38518. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38519. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38520. }
  38521. }
  38522. }
  38523. }
  38524. // Sides
  38525. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38526. // Result
  38527. var vertexData = new VertexData();
  38528. vertexData.indices = indices;
  38529. vertexData.positions = positions;
  38530. vertexData.normals = normals;
  38531. vertexData.uvs = uvs;
  38532. return vertexData;
  38533. };
  38534. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38535. /**
  38536. * Creates the VertexData for a Polyhedron
  38537. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38538. * * type provided types are:
  38539. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38540. * * 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)
  38541. * * size the size of the IcoSphere, optional default 1
  38542. * * sizeX allows stretching in the x direction, optional, default size
  38543. * * sizeY allows stretching in the y direction, optional, default size
  38544. * * sizeZ allows stretching in the z direction, optional, default size
  38545. * * 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
  38546. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38547. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38548. * * flat when true creates a flat shaded mesh, optional, default true
  38549. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38550. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38551. * * 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)
  38552. * * 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)
  38553. * @returns the VertexData of the Polyhedron
  38554. */
  38555. VertexData.CreatePolyhedron = function (options) {
  38556. // provided polyhedron types :
  38557. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38558. // 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)
  38559. var polyhedra = [];
  38560. 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]] };
  38561. 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]] };
  38562. polyhedra[2] = {
  38563. 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]],
  38564. 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]]
  38565. };
  38566. polyhedra[3] = {
  38567. 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]],
  38568. 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]]
  38569. };
  38570. polyhedra[4] = {
  38571. 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]],
  38572. 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]]
  38573. };
  38574. 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]] };
  38575. 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]] };
  38576. 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]] };
  38577. 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]] };
  38578. 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]] };
  38579. 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]] };
  38580. 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]] };
  38581. 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]] };
  38582. 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]] };
  38583. polyhedra[14] = {
  38584. 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]],
  38585. 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]]
  38586. };
  38587. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38588. var size = options.size;
  38589. var sizeX = options.sizeX || size || 1;
  38590. var sizeY = options.sizeY || size || 1;
  38591. var sizeZ = options.sizeZ || size || 1;
  38592. var data = options.custom || polyhedra[type];
  38593. var nbfaces = data.face.length;
  38594. var faceUV = options.faceUV || new Array(nbfaces);
  38595. var faceColors = options.faceColors;
  38596. var flat = (options.flat === undefined) ? true : options.flat;
  38597. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38598. var positions = new Array();
  38599. var indices = new Array();
  38600. var normals = new Array();
  38601. var uvs = new Array();
  38602. var colors = new Array();
  38603. var index = 0;
  38604. var faceIdx = 0; // face cursor in the array "indexes"
  38605. var indexes = new Array();
  38606. var i = 0;
  38607. var f = 0;
  38608. var u, v, ang, x, y, tmp;
  38609. // default face colors and UV if undefined
  38610. if (flat) {
  38611. for (f = 0; f < nbfaces; f++) {
  38612. if (faceColors && faceColors[f] === undefined) {
  38613. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38614. }
  38615. if (faceUV && faceUV[f] === undefined) {
  38616. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38617. }
  38618. }
  38619. }
  38620. if (!flat) {
  38621. for (i = 0; i < data.vertex.length; i++) {
  38622. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38623. uvs.push(0, 0);
  38624. }
  38625. for (f = 0; f < nbfaces; f++) {
  38626. for (i = 0; i < data.face[f].length - 2; i++) {
  38627. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38628. }
  38629. }
  38630. }
  38631. else {
  38632. for (f = 0; f < nbfaces; f++) {
  38633. var fl = data.face[f].length; // number of vertices of the current face
  38634. ang = 2 * Math.PI / fl;
  38635. x = 0.5 * Math.tan(ang / 2);
  38636. y = 0.5;
  38637. // positions, uvs, colors
  38638. for (i = 0; i < fl; i++) {
  38639. // positions
  38640. 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);
  38641. indexes.push(index);
  38642. index++;
  38643. // uvs
  38644. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38645. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38646. uvs.push(u, v);
  38647. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38648. y = x * Math.sin(ang) + y * Math.cos(ang);
  38649. x = tmp;
  38650. // colors
  38651. if (faceColors) {
  38652. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38653. }
  38654. }
  38655. // indices from indexes
  38656. for (i = 0; i < fl - 2; i++) {
  38657. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38658. }
  38659. faceIdx += fl;
  38660. }
  38661. }
  38662. VertexData.ComputeNormals(positions, indices, normals);
  38663. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38664. var vertexData = new VertexData();
  38665. vertexData.positions = positions;
  38666. vertexData.indices = indices;
  38667. vertexData.normals = normals;
  38668. vertexData.uvs = uvs;
  38669. if (faceColors && flat) {
  38670. vertexData.colors = colors;
  38671. }
  38672. return vertexData;
  38673. };
  38674. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38675. /**
  38676. * Creates the VertexData for a TorusKnot
  38677. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38678. * * radius the radius of the torus knot, optional, default 2
  38679. * * tube the thickness of the tube, optional, default 0.5
  38680. * * radialSegments the number of sides on each tube segments, optional, default 32
  38681. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38682. * * p the number of windings around the z axis, optional, default 2
  38683. * * q the number of windings around the x axis, optional, default 3
  38684. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38685. * * 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)
  38686. * * 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)
  38687. * @returns the VertexData of the Torus Knot
  38688. */
  38689. VertexData.CreateTorusKnot = function (options) {
  38690. var indices = new Array();
  38691. var positions = new Array();
  38692. var normals = new Array();
  38693. var uvs = new Array();
  38694. var radius = options.radius || 2;
  38695. var tube = options.tube || 0.5;
  38696. var radialSegments = options.radialSegments || 32;
  38697. var tubularSegments = options.tubularSegments || 32;
  38698. var p = options.p || 2;
  38699. var q = options.q || 3;
  38700. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38701. // Helper
  38702. var getPos = function (angle) {
  38703. var cu = Math.cos(angle);
  38704. var su = Math.sin(angle);
  38705. var quOverP = q / p * angle;
  38706. var cs = Math.cos(quOverP);
  38707. var tx = radius * (2 + cs) * 0.5 * cu;
  38708. var ty = radius * (2 + cs) * su * 0.5;
  38709. var tz = radius * Math.sin(quOverP) * 0.5;
  38710. return new BABYLON.Vector3(tx, ty, tz);
  38711. };
  38712. // Vertices
  38713. var i;
  38714. var j;
  38715. for (i = 0; i <= radialSegments; i++) {
  38716. var modI = i % radialSegments;
  38717. var u = modI / radialSegments * 2 * p * Math.PI;
  38718. var p1 = getPos(u);
  38719. var p2 = getPos(u + 0.01);
  38720. var tang = p2.subtract(p1);
  38721. var n = p2.add(p1);
  38722. var bitan = BABYLON.Vector3.Cross(tang, n);
  38723. n = BABYLON.Vector3.Cross(bitan, tang);
  38724. bitan.normalize();
  38725. n.normalize();
  38726. for (j = 0; j < tubularSegments; j++) {
  38727. var modJ = j % tubularSegments;
  38728. var v = modJ / tubularSegments * 2 * Math.PI;
  38729. var cx = -tube * Math.cos(v);
  38730. var cy = tube * Math.sin(v);
  38731. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38732. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38733. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38734. uvs.push(i / radialSegments);
  38735. uvs.push(j / tubularSegments);
  38736. }
  38737. }
  38738. for (i = 0; i < radialSegments; i++) {
  38739. for (j = 0; j < tubularSegments; j++) {
  38740. var jNext = (j + 1) % tubularSegments;
  38741. var a = i * tubularSegments + j;
  38742. var b = (i + 1) * tubularSegments + j;
  38743. var c = (i + 1) * tubularSegments + jNext;
  38744. var d = i * tubularSegments + jNext;
  38745. indices.push(d);
  38746. indices.push(b);
  38747. indices.push(a);
  38748. indices.push(d);
  38749. indices.push(c);
  38750. indices.push(b);
  38751. }
  38752. }
  38753. // Normals
  38754. VertexData.ComputeNormals(positions, indices, normals);
  38755. // Sides
  38756. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38757. // Result
  38758. var vertexData = new VertexData();
  38759. vertexData.indices = indices;
  38760. vertexData.positions = positions;
  38761. vertexData.normals = normals;
  38762. vertexData.uvs = uvs;
  38763. return vertexData;
  38764. };
  38765. // Tools
  38766. /**
  38767. * Compute normals for given positions and indices
  38768. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38769. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38770. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38771. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38772. * * facetNormals : optional array of facet normals (vector3)
  38773. * * facetPositions : optional array of facet positions (vector3)
  38774. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38775. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38776. * * bInfo : optional bounding info, required for facetPartitioning computation
  38777. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38778. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38779. * * useRightHandedSystem: optional boolean to for right handed system computation
  38780. * * depthSort : optional boolean to enable the facet depth sort computation
  38781. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38782. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38783. */
  38784. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38785. // temporary scalar variables
  38786. var index = 0; // facet index
  38787. var p1p2x = 0.0; // p1p2 vector x coordinate
  38788. var p1p2y = 0.0; // p1p2 vector y coordinate
  38789. var p1p2z = 0.0; // p1p2 vector z coordinate
  38790. var p3p2x = 0.0; // p3p2 vector x coordinate
  38791. var p3p2y = 0.0; // p3p2 vector y coordinate
  38792. var p3p2z = 0.0; // p3p2 vector z coordinate
  38793. var faceNormalx = 0.0; // facet normal x coordinate
  38794. var faceNormaly = 0.0; // facet normal y coordinate
  38795. var faceNormalz = 0.0; // facet normal z coordinate
  38796. var length = 0.0; // facet normal length before normalization
  38797. var v1x = 0; // vector1 x index in the positions array
  38798. var v1y = 0; // vector1 y index in the positions array
  38799. var v1z = 0; // vector1 z index in the positions array
  38800. var v2x = 0; // vector2 x index in the positions array
  38801. var v2y = 0; // vector2 y index in the positions array
  38802. var v2z = 0; // vector2 z index in the positions array
  38803. var v3x = 0; // vector3 x index in the positions array
  38804. var v3y = 0; // vector3 y index in the positions array
  38805. var v3z = 0; // vector3 z index in the positions array
  38806. var computeFacetNormals = false;
  38807. var computeFacetPositions = false;
  38808. var computeFacetPartitioning = false;
  38809. var computeDepthSort = false;
  38810. var faceNormalSign = 1;
  38811. var ratio = 0;
  38812. var distanceTo = null;
  38813. if (options) {
  38814. computeFacetNormals = (options.facetNormals) ? true : false;
  38815. computeFacetPositions = (options.facetPositions) ? true : false;
  38816. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38817. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38818. ratio = options.ratio || 0;
  38819. computeDepthSort = (options.depthSort) ? true : false;
  38820. distanceTo = (options.distanceTo);
  38821. if (computeDepthSort) {
  38822. if (distanceTo === undefined) {
  38823. distanceTo = BABYLON.Vector3.Zero();
  38824. }
  38825. var depthSortedFacets = options.depthSortedFacets;
  38826. }
  38827. }
  38828. // facetPartitioning reinit if needed
  38829. var xSubRatio = 0;
  38830. var ySubRatio = 0;
  38831. var zSubRatio = 0;
  38832. var subSq = 0;
  38833. if (computeFacetPartitioning && options && options.bbSize) {
  38834. var ox = 0; // X partitioning index for facet position
  38835. var oy = 0; // Y partinioning index for facet position
  38836. var oz = 0; // Z partinioning index for facet position
  38837. var b1x = 0; // X partitioning index for facet v1 vertex
  38838. var b1y = 0; // Y partitioning index for facet v1 vertex
  38839. var b1z = 0; // z partitioning index for facet v1 vertex
  38840. var b2x = 0; // X partitioning index for facet v2 vertex
  38841. var b2y = 0; // Y partitioning index for facet v2 vertex
  38842. var b2z = 0; // Z partitioning index for facet v2 vertex
  38843. var b3x = 0; // X partitioning index for facet v3 vertex
  38844. var b3y = 0; // Y partitioning index for facet v3 vertex
  38845. var b3z = 0; // Z partitioning index for facet v3 vertex
  38846. var block_idx_o = 0; // facet barycenter block index
  38847. var block_idx_v1 = 0; // v1 vertex block index
  38848. var block_idx_v2 = 0; // v2 vertex block index
  38849. var block_idx_v3 = 0; // v3 vertex block index
  38850. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38851. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38852. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38853. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38854. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38855. subSq = options.subDiv.max * options.subDiv.max;
  38856. options.facetPartitioning.length = 0;
  38857. }
  38858. // reset the normals
  38859. for (index = 0; index < positions.length; index++) {
  38860. normals[index] = 0.0;
  38861. }
  38862. // Loop : 1 indice triplet = 1 facet
  38863. var nbFaces = (indices.length / 3) | 0;
  38864. for (index = 0; index < nbFaces; index++) {
  38865. // get the indexes of the coordinates of each vertex of the facet
  38866. v1x = indices[index * 3] * 3;
  38867. v1y = v1x + 1;
  38868. v1z = v1x + 2;
  38869. v2x = indices[index * 3 + 1] * 3;
  38870. v2y = v2x + 1;
  38871. v2z = v2x + 2;
  38872. v3x = indices[index * 3 + 2] * 3;
  38873. v3y = v3x + 1;
  38874. v3z = v3x + 2;
  38875. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38876. p1p2y = positions[v1y] - positions[v2y];
  38877. p1p2z = positions[v1z] - positions[v2z];
  38878. p3p2x = positions[v3x] - positions[v2x];
  38879. p3p2y = positions[v3y] - positions[v2y];
  38880. p3p2z = positions[v3z] - positions[v2z];
  38881. // compute the face normal with the cross product
  38882. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38883. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38884. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38885. // normalize this normal and store it in the array facetData
  38886. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38887. length = (length === 0) ? 1.0 : length;
  38888. faceNormalx /= length;
  38889. faceNormaly /= length;
  38890. faceNormalz /= length;
  38891. if (computeFacetNormals && options) {
  38892. options.facetNormals[index].x = faceNormalx;
  38893. options.facetNormals[index].y = faceNormaly;
  38894. options.facetNormals[index].z = faceNormalz;
  38895. }
  38896. if (computeFacetPositions && options) {
  38897. // compute and the facet barycenter coordinates in the array facetPositions
  38898. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38899. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38900. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38901. }
  38902. if (computeFacetPartitioning && options) {
  38903. // store the facet indexes in arrays in the main facetPartitioning array :
  38904. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38905. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38906. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38907. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38908. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38909. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38910. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38911. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38912. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38913. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38914. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38915. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38916. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38917. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38918. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38919. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38920. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38921. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38922. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38923. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38924. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38925. // push each facet index in each block containing the vertex
  38926. options.facetPartitioning[block_idx_v1].push(index);
  38927. if (block_idx_v2 != block_idx_v1) {
  38928. options.facetPartitioning[block_idx_v2].push(index);
  38929. }
  38930. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38931. options.facetPartitioning[block_idx_v3].push(index);
  38932. }
  38933. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38934. options.facetPartitioning[block_idx_o].push(index);
  38935. }
  38936. }
  38937. if (computeDepthSort && options && options.facetPositions) {
  38938. var dsf = depthSortedFacets[index];
  38939. dsf.ind = index * 3;
  38940. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38941. }
  38942. // compute the normals anyway
  38943. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38944. normals[v1y] += faceNormaly;
  38945. normals[v1z] += faceNormalz;
  38946. normals[v2x] += faceNormalx;
  38947. normals[v2y] += faceNormaly;
  38948. normals[v2z] += faceNormalz;
  38949. normals[v3x] += faceNormalx;
  38950. normals[v3y] += faceNormaly;
  38951. normals[v3z] += faceNormalz;
  38952. }
  38953. // last normalization of each normal
  38954. for (index = 0; index < normals.length / 3; index++) {
  38955. faceNormalx = normals[index * 3];
  38956. faceNormaly = normals[index * 3 + 1];
  38957. faceNormalz = normals[index * 3 + 2];
  38958. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38959. length = (length === 0) ? 1.0 : length;
  38960. faceNormalx /= length;
  38961. faceNormaly /= length;
  38962. faceNormalz /= length;
  38963. normals[index * 3] = faceNormalx;
  38964. normals[index * 3 + 1] = faceNormaly;
  38965. normals[index * 3 + 2] = faceNormalz;
  38966. }
  38967. };
  38968. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38969. var li = indices.length;
  38970. var ln = normals.length;
  38971. var i;
  38972. var n;
  38973. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38974. switch (sideOrientation) {
  38975. case BABYLON.Mesh.FRONTSIDE:
  38976. // nothing changed
  38977. break;
  38978. case BABYLON.Mesh.BACKSIDE:
  38979. var tmp;
  38980. // indices
  38981. for (i = 0; i < li; i += 3) {
  38982. tmp = indices[i];
  38983. indices[i] = indices[i + 2];
  38984. indices[i + 2] = tmp;
  38985. }
  38986. // normals
  38987. for (n = 0; n < ln; n++) {
  38988. normals[n] = -normals[n];
  38989. }
  38990. break;
  38991. case BABYLON.Mesh.DOUBLESIDE:
  38992. // positions
  38993. var lp = positions.length;
  38994. var l = lp / 3;
  38995. for (var p = 0; p < lp; p++) {
  38996. positions[lp + p] = positions[p];
  38997. }
  38998. // indices
  38999. for (i = 0; i < li; i += 3) {
  39000. indices[i + li] = indices[i + 2] + l;
  39001. indices[i + 1 + li] = indices[i + 1] + l;
  39002. indices[i + 2 + li] = indices[i] + l;
  39003. }
  39004. // normals
  39005. for (n = 0; n < ln; n++) {
  39006. normals[ln + n] = -normals[n];
  39007. }
  39008. // uvs
  39009. var lu = uvs.length;
  39010. var u = 0;
  39011. for (u = 0; u < lu; u++) {
  39012. uvs[u + lu] = uvs[u];
  39013. }
  39014. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39015. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39016. u = 0;
  39017. for (i = 0; i < lu / 2; i++) {
  39018. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39019. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39020. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39021. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39022. u += 2;
  39023. }
  39024. break;
  39025. }
  39026. };
  39027. /**
  39028. * Applies VertexData created from the imported parameters to the geometry
  39029. * @param parsedVertexData the parsed data from an imported file
  39030. * @param geometry the geometry to apply the VertexData to
  39031. */
  39032. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39033. var vertexData = new VertexData();
  39034. // positions
  39035. var positions = parsedVertexData.positions;
  39036. if (positions) {
  39037. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39038. }
  39039. // normals
  39040. var normals = parsedVertexData.normals;
  39041. if (normals) {
  39042. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39043. }
  39044. // tangents
  39045. var tangents = parsedVertexData.tangents;
  39046. if (tangents) {
  39047. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39048. }
  39049. // uvs
  39050. var uvs = parsedVertexData.uvs;
  39051. if (uvs) {
  39052. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39053. }
  39054. // uv2s
  39055. var uv2s = parsedVertexData.uv2s;
  39056. if (uv2s) {
  39057. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39058. }
  39059. // uv3s
  39060. var uv3s = parsedVertexData.uv3s;
  39061. if (uv3s) {
  39062. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39063. }
  39064. // uv4s
  39065. var uv4s = parsedVertexData.uv4s;
  39066. if (uv4s) {
  39067. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39068. }
  39069. // uv5s
  39070. var uv5s = parsedVertexData.uv5s;
  39071. if (uv5s) {
  39072. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39073. }
  39074. // uv6s
  39075. var uv6s = parsedVertexData.uv6s;
  39076. if (uv6s) {
  39077. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39078. }
  39079. // colors
  39080. var colors = parsedVertexData.colors;
  39081. if (colors) {
  39082. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39083. }
  39084. // matricesIndices
  39085. var matricesIndices = parsedVertexData.matricesIndices;
  39086. if (matricesIndices) {
  39087. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39088. }
  39089. // matricesWeights
  39090. var matricesWeights = parsedVertexData.matricesWeights;
  39091. if (matricesWeights) {
  39092. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39093. }
  39094. // indices
  39095. var indices = parsedVertexData.indices;
  39096. if (indices) {
  39097. vertexData.indices = indices;
  39098. }
  39099. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39100. };
  39101. return VertexData;
  39102. }());
  39103. BABYLON.VertexData = VertexData;
  39104. })(BABYLON || (BABYLON = {}));
  39105. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39106. var BABYLON;
  39107. (function (BABYLON) {
  39108. /**
  39109. * Class used to store geometry data (vertex buffers + index buffer)
  39110. */
  39111. var Geometry = /** @class */ (function () {
  39112. /**
  39113. * Creates a new geometry
  39114. * @param id defines the unique ID
  39115. * @param scene defines the hosting scene
  39116. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39117. * @param updatable defines if geometry must be updatable (false by default)
  39118. * @param mesh defines the mesh that will be associated with the geometry
  39119. */
  39120. function Geometry(id, scene, vertexData, updatable, mesh) {
  39121. if (updatable === void 0) { updatable = false; }
  39122. if (mesh === void 0) { mesh = null; }
  39123. /**
  39124. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39125. */
  39126. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39127. this._totalVertices = 0;
  39128. this._isDisposed = false;
  39129. this._indexBufferIsUpdatable = false;
  39130. this.id = id;
  39131. this._engine = scene.getEngine();
  39132. this._meshes = [];
  39133. this._scene = scene;
  39134. //Init vertex buffer cache
  39135. this._vertexBuffers = {};
  39136. this._indices = [];
  39137. this._updatable = updatable;
  39138. // vertexData
  39139. if (vertexData) {
  39140. this.setAllVerticesData(vertexData, updatable);
  39141. }
  39142. else {
  39143. this._totalVertices = 0;
  39144. this._indices = [];
  39145. }
  39146. if (this._engine.getCaps().vertexArrayObject) {
  39147. this._vertexArrayObjects = {};
  39148. }
  39149. // applyToMesh
  39150. if (mesh) {
  39151. if (mesh.getClassName() === "LinesMesh") {
  39152. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39153. this._updateExtend();
  39154. }
  39155. this.applyToMesh(mesh);
  39156. mesh.computeWorldMatrix(true);
  39157. }
  39158. }
  39159. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39160. /**
  39161. * 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
  39162. */
  39163. get: function () {
  39164. return this._boundingBias;
  39165. },
  39166. /**
  39167. * 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
  39168. */
  39169. set: function (value) {
  39170. if (this._boundingBias && this._boundingBias.equals(value)) {
  39171. return;
  39172. }
  39173. this._boundingBias = value.clone();
  39174. this._updateBoundingInfo(true, null);
  39175. },
  39176. enumerable: true,
  39177. configurable: true
  39178. });
  39179. /**
  39180. * Static function used to attach a new empty geometry to a mesh
  39181. * @param mesh defines the mesh to attach the geometry to
  39182. * @returns the new {BABYLON.Geometry}
  39183. */
  39184. Geometry.CreateGeometryForMesh = function (mesh) {
  39185. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39186. geometry.applyToMesh(mesh);
  39187. return geometry;
  39188. };
  39189. Object.defineProperty(Geometry.prototype, "extend", {
  39190. /**
  39191. * Gets the current extend of the geometry
  39192. */
  39193. get: function () {
  39194. return this._extend;
  39195. },
  39196. enumerable: true,
  39197. configurable: true
  39198. });
  39199. /**
  39200. * Gets the hosting scene
  39201. * @returns the hosting {BABYLON.Scene}
  39202. */
  39203. Geometry.prototype.getScene = function () {
  39204. return this._scene;
  39205. };
  39206. /**
  39207. * Gets the hosting engine
  39208. * @returns the hosting {BABYLON.Engine}
  39209. */
  39210. Geometry.prototype.getEngine = function () {
  39211. return this._engine;
  39212. };
  39213. /**
  39214. * Defines if the geometry is ready to use
  39215. * @returns true if the geometry is ready to be used
  39216. */
  39217. Geometry.prototype.isReady = function () {
  39218. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39219. };
  39220. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39221. /**
  39222. * Gets a value indicating that the geometry should not be serialized
  39223. */
  39224. get: function () {
  39225. for (var index = 0; index < this._meshes.length; index++) {
  39226. if (!this._meshes[index].doNotSerialize) {
  39227. return false;
  39228. }
  39229. }
  39230. return true;
  39231. },
  39232. enumerable: true,
  39233. configurable: true
  39234. });
  39235. /** @hidden */
  39236. Geometry.prototype._rebuild = function () {
  39237. if (this._vertexArrayObjects) {
  39238. this._vertexArrayObjects = {};
  39239. }
  39240. // Index buffer
  39241. if (this._meshes.length !== 0 && this._indices) {
  39242. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39243. }
  39244. // Vertex buffers
  39245. for (var key in this._vertexBuffers) {
  39246. var vertexBuffer = this._vertexBuffers[key];
  39247. vertexBuffer._rebuild();
  39248. }
  39249. };
  39250. /**
  39251. * Affects all geometry data in one call
  39252. * @param vertexData defines the geometry data
  39253. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39254. */
  39255. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39256. vertexData.applyToGeometry(this, updatable);
  39257. this.notifyUpdate();
  39258. };
  39259. /**
  39260. * Set specific vertex data
  39261. * @param kind defines the data kind (Position, normal, etc...)
  39262. * @param data defines the vertex data to use
  39263. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39264. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39265. */
  39266. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39267. if (updatable === void 0) { updatable = false; }
  39268. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39269. this.setVerticesBuffer(buffer);
  39270. };
  39271. /**
  39272. * Removes a specific vertex data
  39273. * @param kind defines the data kind (Position, normal, etc...)
  39274. */
  39275. Geometry.prototype.removeVerticesData = function (kind) {
  39276. if (this._vertexBuffers[kind]) {
  39277. this._vertexBuffers[kind].dispose();
  39278. delete this._vertexBuffers[kind];
  39279. }
  39280. };
  39281. /**
  39282. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39283. * @param buffer defines the vertex buffer to use
  39284. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39285. */
  39286. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39287. if (totalVertices === void 0) { totalVertices = null; }
  39288. var kind = buffer.getKind();
  39289. if (this._vertexBuffers[kind]) {
  39290. this._vertexBuffers[kind].dispose();
  39291. }
  39292. this._vertexBuffers[kind] = buffer;
  39293. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39294. var data = buffer.getData();
  39295. if (totalVertices != null) {
  39296. this._totalVertices = totalVertices;
  39297. }
  39298. else {
  39299. if (data != null) {
  39300. this._totalVertices = data.length / (buffer.byteStride / 4);
  39301. }
  39302. }
  39303. this._updateExtend(data);
  39304. this._resetPointsArrayCache();
  39305. var meshes = this._meshes;
  39306. var numOfMeshes = meshes.length;
  39307. for (var index = 0; index < numOfMeshes; index++) {
  39308. var mesh = meshes[index];
  39309. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39310. mesh._createGlobalSubMesh(false);
  39311. mesh.computeWorldMatrix(true);
  39312. }
  39313. }
  39314. this.notifyUpdate(kind);
  39315. if (this._vertexArrayObjects) {
  39316. this._disposeVertexArrayObjects();
  39317. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39318. }
  39319. };
  39320. /**
  39321. * Update a specific vertex buffer
  39322. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39323. * It will do nothing if the buffer is not updatable
  39324. * @param kind defines the data kind (Position, normal, etc...)
  39325. * @param data defines the data to use
  39326. * @param offset defines the offset in the target buffer where to store the data
  39327. * @param useBytes set to true if the offset is in bytes
  39328. */
  39329. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39330. if (useBytes === void 0) { useBytes = false; }
  39331. var vertexBuffer = this.getVertexBuffer(kind);
  39332. if (!vertexBuffer) {
  39333. return;
  39334. }
  39335. vertexBuffer.updateDirectly(data, offset, useBytes);
  39336. this.notifyUpdate(kind);
  39337. };
  39338. /**
  39339. * Update a specific vertex buffer
  39340. * This function will create a new buffer if the current one is not updatable
  39341. * @param kind defines the data kind (Position, normal, etc...)
  39342. * @param data defines the data to use
  39343. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39344. */
  39345. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39346. if (updateExtends === void 0) { updateExtends = false; }
  39347. var vertexBuffer = this.getVertexBuffer(kind);
  39348. if (!vertexBuffer) {
  39349. return;
  39350. }
  39351. vertexBuffer.update(data);
  39352. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39353. this._updateBoundingInfo(updateExtends, data);
  39354. }
  39355. this.notifyUpdate(kind);
  39356. };
  39357. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39358. if (updateExtends) {
  39359. this._updateExtend(data);
  39360. }
  39361. var meshes = this._meshes;
  39362. var numOfMeshes = meshes.length;
  39363. this._resetPointsArrayCache();
  39364. for (var index = 0; index < numOfMeshes; index++) {
  39365. var mesh = meshes[index];
  39366. if (updateExtends) {
  39367. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39368. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39369. var subMesh = mesh.subMeshes[subIndex];
  39370. subMesh.refreshBoundingInfo();
  39371. }
  39372. }
  39373. }
  39374. };
  39375. /** @hidden */
  39376. Geometry.prototype._bind = function (effect, indexToBind) {
  39377. if (!effect) {
  39378. return;
  39379. }
  39380. if (indexToBind === undefined) {
  39381. indexToBind = this._indexBuffer;
  39382. }
  39383. var vbs = this.getVertexBuffers();
  39384. if (!vbs) {
  39385. return;
  39386. }
  39387. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39388. this._engine.bindBuffers(vbs, indexToBind, effect);
  39389. return;
  39390. }
  39391. // Using VAO
  39392. if (!this._vertexArrayObjects[effect.key]) {
  39393. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39394. }
  39395. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39396. };
  39397. /**
  39398. * Gets total number of vertices
  39399. * @returns the total number of vertices
  39400. */
  39401. Geometry.prototype.getTotalVertices = function () {
  39402. if (!this.isReady()) {
  39403. return 0;
  39404. }
  39405. return this._totalVertices;
  39406. };
  39407. /**
  39408. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39409. * @param kind defines the data kind (Position, normal, etc...)
  39410. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39411. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39412. * @returns a float array containing vertex data
  39413. */
  39414. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39415. var vertexBuffer = this.getVertexBuffer(kind);
  39416. if (!vertexBuffer) {
  39417. return null;
  39418. }
  39419. var data = vertexBuffer.getData();
  39420. if (!data) {
  39421. return null;
  39422. }
  39423. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39424. var count = this._totalVertices * vertexBuffer.getSize();
  39425. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39426. var copy_1 = new Array(count);
  39427. vertexBuffer.forEach(count, function (value, index) {
  39428. copy_1[index] = value;
  39429. });
  39430. return copy_1;
  39431. }
  39432. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39433. if (data instanceof Array) {
  39434. var offset = vertexBuffer.byteOffset / 4;
  39435. return BABYLON.Tools.Slice(data, offset, offset + count);
  39436. }
  39437. else if (data instanceof ArrayBuffer) {
  39438. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39439. }
  39440. else {
  39441. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39442. }
  39443. }
  39444. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39445. return BABYLON.Tools.Slice(data);
  39446. }
  39447. return data;
  39448. };
  39449. /**
  39450. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39451. * @param kind defines the data kind (Position, normal, etc...)
  39452. * @returns true if the vertex buffer with the specified kind is updatable
  39453. */
  39454. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39455. var vb = this._vertexBuffers[kind];
  39456. if (!vb) {
  39457. return false;
  39458. }
  39459. return vb.isUpdatable();
  39460. };
  39461. /**
  39462. * Gets a specific vertex buffer
  39463. * @param kind defines the data kind (Position, normal, etc...)
  39464. * @returns a {BABYLON.VertexBuffer}
  39465. */
  39466. Geometry.prototype.getVertexBuffer = function (kind) {
  39467. if (!this.isReady()) {
  39468. return null;
  39469. }
  39470. return this._vertexBuffers[kind];
  39471. };
  39472. /**
  39473. * Returns all vertex buffers
  39474. * @return an object holding all vertex buffers indexed by kind
  39475. */
  39476. Geometry.prototype.getVertexBuffers = function () {
  39477. if (!this.isReady()) {
  39478. return null;
  39479. }
  39480. return this._vertexBuffers;
  39481. };
  39482. /**
  39483. * Gets a boolean indicating if specific vertex buffer is present
  39484. * @param kind defines the data kind (Position, normal, etc...)
  39485. * @returns true if data is present
  39486. */
  39487. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39488. if (!this._vertexBuffers) {
  39489. if (this._delayInfo) {
  39490. return this._delayInfo.indexOf(kind) !== -1;
  39491. }
  39492. return false;
  39493. }
  39494. return this._vertexBuffers[kind] !== undefined;
  39495. };
  39496. /**
  39497. * Gets a list of all attached data kinds (Position, normal, etc...)
  39498. * @returns a list of string containing all kinds
  39499. */
  39500. Geometry.prototype.getVerticesDataKinds = function () {
  39501. var result = [];
  39502. var kind;
  39503. if (!this._vertexBuffers && this._delayInfo) {
  39504. for (kind in this._delayInfo) {
  39505. result.push(kind);
  39506. }
  39507. }
  39508. else {
  39509. for (kind in this._vertexBuffers) {
  39510. result.push(kind);
  39511. }
  39512. }
  39513. return result;
  39514. };
  39515. /**
  39516. * Update index buffer
  39517. * @param indices defines the indices to store in the index buffer
  39518. * @param offset defines the offset in the target buffer where to store the data
  39519. */
  39520. Geometry.prototype.updateIndices = function (indices, offset) {
  39521. if (!this._indexBuffer) {
  39522. return;
  39523. }
  39524. if (!this._indexBufferIsUpdatable) {
  39525. this.setIndices(indices, null, true);
  39526. }
  39527. else {
  39528. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39529. }
  39530. };
  39531. /**
  39532. * Creates a new index buffer
  39533. * @param indices defines the indices to store in the index buffer
  39534. * @param totalVertices defines the total number of vertices (could be null)
  39535. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39536. */
  39537. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39538. if (totalVertices === void 0) { totalVertices = null; }
  39539. if (updatable === void 0) { updatable = false; }
  39540. if (this._indexBuffer) {
  39541. this._engine._releaseBuffer(this._indexBuffer);
  39542. }
  39543. this._disposeVertexArrayObjects();
  39544. this._indices = indices;
  39545. this._indexBufferIsUpdatable = updatable;
  39546. if (this._meshes.length !== 0 && this._indices) {
  39547. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39548. }
  39549. if (totalVertices != undefined) { // including null and undefined
  39550. this._totalVertices = totalVertices;
  39551. }
  39552. var meshes = this._meshes;
  39553. var numOfMeshes = meshes.length;
  39554. for (var index = 0; index < numOfMeshes; index++) {
  39555. meshes[index]._createGlobalSubMesh(true);
  39556. }
  39557. this.notifyUpdate();
  39558. };
  39559. /**
  39560. * Return the total number of indices
  39561. * @returns the total number of indices
  39562. */
  39563. Geometry.prototype.getTotalIndices = function () {
  39564. if (!this.isReady()) {
  39565. return 0;
  39566. }
  39567. return this._indices.length;
  39568. };
  39569. /**
  39570. * Gets the index buffer array
  39571. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39572. * @returns the index buffer array
  39573. */
  39574. Geometry.prototype.getIndices = function (copyWhenShared) {
  39575. if (!this.isReady()) {
  39576. return null;
  39577. }
  39578. var orig = this._indices;
  39579. if (!copyWhenShared || this._meshes.length === 1) {
  39580. return orig;
  39581. }
  39582. else {
  39583. var len = orig.length;
  39584. var copy = [];
  39585. for (var i = 0; i < len; i++) {
  39586. copy.push(orig[i]);
  39587. }
  39588. return copy;
  39589. }
  39590. };
  39591. /**
  39592. * Gets the index buffer
  39593. * @return the index buffer
  39594. */
  39595. Geometry.prototype.getIndexBuffer = function () {
  39596. if (!this.isReady()) {
  39597. return null;
  39598. }
  39599. return this._indexBuffer;
  39600. };
  39601. /** @hidden */
  39602. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39603. if (effect === void 0) { effect = null; }
  39604. if (!effect || !this._vertexArrayObjects) {
  39605. return;
  39606. }
  39607. if (this._vertexArrayObjects[effect.key]) {
  39608. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39609. delete this._vertexArrayObjects[effect.key];
  39610. }
  39611. };
  39612. /**
  39613. * Release the associated resources for a specific mesh
  39614. * @param mesh defines the source mesh
  39615. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39616. */
  39617. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39618. var meshes = this._meshes;
  39619. var index = meshes.indexOf(mesh);
  39620. if (index === -1) {
  39621. return;
  39622. }
  39623. meshes.splice(index, 1);
  39624. mesh._geometry = null;
  39625. if (meshes.length === 0 && shouldDispose) {
  39626. this.dispose();
  39627. }
  39628. };
  39629. /**
  39630. * Apply current geometry to a given mesh
  39631. * @param mesh defines the mesh to apply geometry to
  39632. */
  39633. Geometry.prototype.applyToMesh = function (mesh) {
  39634. if (mesh._geometry === this) {
  39635. return;
  39636. }
  39637. var previousGeometry = mesh._geometry;
  39638. if (previousGeometry) {
  39639. previousGeometry.releaseForMesh(mesh);
  39640. }
  39641. var meshes = this._meshes;
  39642. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39643. mesh._geometry = this;
  39644. this._scene.pushGeometry(this);
  39645. meshes.push(mesh);
  39646. if (this.isReady()) {
  39647. this._applyToMesh(mesh);
  39648. }
  39649. else {
  39650. mesh._boundingInfo = this._boundingInfo;
  39651. }
  39652. };
  39653. Geometry.prototype._updateExtend = function (data) {
  39654. if (data === void 0) { data = null; }
  39655. if (!data) {
  39656. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39657. }
  39658. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39659. };
  39660. Geometry.prototype._applyToMesh = function (mesh) {
  39661. var numOfMeshes = this._meshes.length;
  39662. // vertexBuffers
  39663. for (var kind in this._vertexBuffers) {
  39664. if (numOfMeshes === 1) {
  39665. this._vertexBuffers[kind].create();
  39666. }
  39667. var buffer = this._vertexBuffers[kind].getBuffer();
  39668. if (buffer)
  39669. buffer.references = numOfMeshes;
  39670. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39671. if (!this._extend) {
  39672. this._updateExtend();
  39673. }
  39674. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39675. mesh._createGlobalSubMesh(false);
  39676. //bounding info was just created again, world matrix should be applied again.
  39677. mesh._updateBoundingInfo();
  39678. }
  39679. }
  39680. // indexBuffer
  39681. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39682. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39683. }
  39684. if (this._indexBuffer) {
  39685. this._indexBuffer.references = numOfMeshes;
  39686. }
  39687. };
  39688. Geometry.prototype.notifyUpdate = function (kind) {
  39689. if (this.onGeometryUpdated) {
  39690. this.onGeometryUpdated(this, kind);
  39691. }
  39692. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39693. var mesh = _a[_i];
  39694. mesh._markSubMeshesAsAttributesDirty();
  39695. }
  39696. };
  39697. /**
  39698. * Load the geometry if it was flagged as delay loaded
  39699. * @param scene defines the hosting scene
  39700. * @param onLoaded defines a callback called when the geometry is loaded
  39701. */
  39702. Geometry.prototype.load = function (scene, onLoaded) {
  39703. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39704. return;
  39705. }
  39706. if (this.isReady()) {
  39707. if (onLoaded) {
  39708. onLoaded();
  39709. }
  39710. return;
  39711. }
  39712. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39713. this._queueLoad(scene, onLoaded);
  39714. };
  39715. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39716. var _this = this;
  39717. if (!this.delayLoadingFile) {
  39718. return;
  39719. }
  39720. scene._addPendingData(this);
  39721. scene._loadFile(this.delayLoadingFile, function (data) {
  39722. if (!_this._delayLoadingFunction) {
  39723. return;
  39724. }
  39725. _this._delayLoadingFunction(JSON.parse(data), _this);
  39726. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39727. _this._delayInfo = [];
  39728. scene._removePendingData(_this);
  39729. var meshes = _this._meshes;
  39730. var numOfMeshes = meshes.length;
  39731. for (var index = 0; index < numOfMeshes; index++) {
  39732. _this._applyToMesh(meshes[index]);
  39733. }
  39734. if (onLoaded) {
  39735. onLoaded();
  39736. }
  39737. }, undefined, true);
  39738. };
  39739. /**
  39740. * Invert the geometry to move from a right handed system to a left handed one.
  39741. */
  39742. Geometry.prototype.toLeftHanded = function () {
  39743. // Flip faces
  39744. var tIndices = this.getIndices(false);
  39745. if (tIndices != null && tIndices.length > 0) {
  39746. for (var i = 0; i < tIndices.length; i += 3) {
  39747. var tTemp = tIndices[i + 0];
  39748. tIndices[i + 0] = tIndices[i + 2];
  39749. tIndices[i + 2] = tTemp;
  39750. }
  39751. this.setIndices(tIndices);
  39752. }
  39753. // Negate position.z
  39754. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39755. if (tPositions != null && tPositions.length > 0) {
  39756. for (var i = 0; i < tPositions.length; i += 3) {
  39757. tPositions[i + 2] = -tPositions[i + 2];
  39758. }
  39759. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39760. }
  39761. // Negate normal.z
  39762. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39763. if (tNormals != null && tNormals.length > 0) {
  39764. for (var i = 0; i < tNormals.length; i += 3) {
  39765. tNormals[i + 2] = -tNormals[i + 2];
  39766. }
  39767. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39768. }
  39769. };
  39770. // Cache
  39771. /** @hidden */
  39772. Geometry.prototype._resetPointsArrayCache = function () {
  39773. this._positions = null;
  39774. };
  39775. /** @hidden */
  39776. Geometry.prototype._generatePointsArray = function () {
  39777. if (this._positions)
  39778. return true;
  39779. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39780. if (!data || data.length === 0) {
  39781. return false;
  39782. }
  39783. this._positions = [];
  39784. for (var index = 0; index < data.length; index += 3) {
  39785. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39786. }
  39787. return true;
  39788. };
  39789. /**
  39790. * Gets a value indicating if the geometry is disposed
  39791. * @returns true if the geometry was disposed
  39792. */
  39793. Geometry.prototype.isDisposed = function () {
  39794. return this._isDisposed;
  39795. };
  39796. Geometry.prototype._disposeVertexArrayObjects = function () {
  39797. if (this._vertexArrayObjects) {
  39798. for (var kind in this._vertexArrayObjects) {
  39799. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39800. }
  39801. this._vertexArrayObjects = {};
  39802. }
  39803. };
  39804. /**
  39805. * Free all associated resources
  39806. */
  39807. Geometry.prototype.dispose = function () {
  39808. var meshes = this._meshes;
  39809. var numOfMeshes = meshes.length;
  39810. var index;
  39811. for (index = 0; index < numOfMeshes; index++) {
  39812. this.releaseForMesh(meshes[index]);
  39813. }
  39814. this._meshes = [];
  39815. this._disposeVertexArrayObjects();
  39816. for (var kind in this._vertexBuffers) {
  39817. this._vertexBuffers[kind].dispose();
  39818. }
  39819. this._vertexBuffers = {};
  39820. this._totalVertices = 0;
  39821. if (this._indexBuffer) {
  39822. this._engine._releaseBuffer(this._indexBuffer);
  39823. }
  39824. this._indexBuffer = null;
  39825. this._indices = [];
  39826. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39827. this.delayLoadingFile = null;
  39828. this._delayLoadingFunction = null;
  39829. this._delayInfo = [];
  39830. this._boundingInfo = null;
  39831. this._scene.removeGeometry(this);
  39832. this._isDisposed = true;
  39833. };
  39834. /**
  39835. * Clone the current geometry into a new geometry
  39836. * @param id defines the unique ID of the new geometry
  39837. * @returns a new geometry object
  39838. */
  39839. Geometry.prototype.copy = function (id) {
  39840. var vertexData = new BABYLON.VertexData();
  39841. vertexData.indices = [];
  39842. var indices = this.getIndices();
  39843. if (indices) {
  39844. for (var index = 0; index < indices.length; index++) {
  39845. vertexData.indices.push(indices[index]);
  39846. }
  39847. }
  39848. var updatable = false;
  39849. var stopChecking = false;
  39850. var kind;
  39851. for (kind in this._vertexBuffers) {
  39852. // using slice() to make a copy of the array and not just reference it
  39853. var data = this.getVerticesData(kind);
  39854. if (data instanceof Float32Array) {
  39855. vertexData.set(new Float32Array(data), kind);
  39856. }
  39857. else {
  39858. vertexData.set(data.slice(0), kind);
  39859. }
  39860. if (!stopChecking) {
  39861. var vb = this.getVertexBuffer(kind);
  39862. if (vb) {
  39863. updatable = vb.isUpdatable();
  39864. stopChecking = !updatable;
  39865. }
  39866. }
  39867. }
  39868. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39869. geometry.delayLoadState = this.delayLoadState;
  39870. geometry.delayLoadingFile = this.delayLoadingFile;
  39871. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39872. for (kind in this._delayInfo) {
  39873. geometry._delayInfo = geometry._delayInfo || [];
  39874. geometry._delayInfo.push(kind);
  39875. }
  39876. // Bounding info
  39877. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39878. return geometry;
  39879. };
  39880. /**
  39881. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39882. * @return a JSON representation of the current geometry data (without the vertices data)
  39883. */
  39884. Geometry.prototype.serialize = function () {
  39885. var serializationObject = {};
  39886. serializationObject.id = this.id;
  39887. serializationObject.updatable = this._updatable;
  39888. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39889. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39890. }
  39891. return serializationObject;
  39892. };
  39893. Geometry.prototype.toNumberArray = function (origin) {
  39894. if (Array.isArray(origin)) {
  39895. return origin;
  39896. }
  39897. else {
  39898. return Array.prototype.slice.call(origin);
  39899. }
  39900. };
  39901. /**
  39902. * Serialize all vertices data into a JSON oject
  39903. * @returns a JSON representation of the current geometry data
  39904. */
  39905. Geometry.prototype.serializeVerticeData = function () {
  39906. var serializationObject = this.serialize();
  39907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39908. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39909. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39910. serializationObject.positions._updatable = true;
  39911. }
  39912. }
  39913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39914. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39916. serializationObject.normals._updatable = true;
  39917. }
  39918. }
  39919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39920. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39922. serializationObject.tangets._updatable = true;
  39923. }
  39924. }
  39925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39926. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39928. serializationObject.uvs._updatable = true;
  39929. }
  39930. }
  39931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39932. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39934. serializationObject.uv2s._updatable = true;
  39935. }
  39936. }
  39937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39938. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39940. serializationObject.uv3s._updatable = true;
  39941. }
  39942. }
  39943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39944. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39946. serializationObject.uv4s._updatable = true;
  39947. }
  39948. }
  39949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39950. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39952. serializationObject.uv5s._updatable = true;
  39953. }
  39954. }
  39955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39956. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39958. serializationObject.uv6s._updatable = true;
  39959. }
  39960. }
  39961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39962. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39963. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39964. serializationObject.colors._updatable = true;
  39965. }
  39966. }
  39967. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39968. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39969. serializationObject.matricesIndices._isExpanded = true;
  39970. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39971. serializationObject.matricesIndices._updatable = true;
  39972. }
  39973. }
  39974. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39975. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39976. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39977. serializationObject.matricesWeights._updatable = true;
  39978. }
  39979. }
  39980. serializationObject.indices = this.toNumberArray(this.getIndices());
  39981. return serializationObject;
  39982. };
  39983. // Statics
  39984. /**
  39985. * Extracts a clone of a mesh geometry
  39986. * @param mesh defines the source mesh
  39987. * @param id defines the unique ID of the new geometry object
  39988. * @returns the new geometry object
  39989. */
  39990. Geometry.ExtractFromMesh = function (mesh, id) {
  39991. var geometry = mesh._geometry;
  39992. if (!geometry) {
  39993. return null;
  39994. }
  39995. return geometry.copy(id);
  39996. };
  39997. /**
  39998. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39999. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40000. * Be aware Math.random() could cause collisions, but:
  40001. * "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"
  40002. * @returns a string containing a new GUID
  40003. */
  40004. Geometry.RandomId = function () {
  40005. return BABYLON.Tools.RandomId();
  40006. };
  40007. /** @hidden */
  40008. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40009. var scene = mesh.getScene();
  40010. // Geometry
  40011. var geometryId = parsedGeometry.geometryId;
  40012. if (geometryId) {
  40013. var geometry = scene.getGeometryByID(geometryId);
  40014. if (geometry) {
  40015. geometry.applyToMesh(mesh);
  40016. }
  40017. }
  40018. else if (parsedGeometry instanceof ArrayBuffer) {
  40019. var binaryInfo = mesh._binaryInfo;
  40020. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40021. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40022. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40023. }
  40024. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40025. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40026. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40027. }
  40028. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40029. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40030. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40031. }
  40032. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40033. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40034. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40035. }
  40036. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40037. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40038. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40039. }
  40040. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40041. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40042. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40043. }
  40044. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40045. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40046. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40047. }
  40048. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40049. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40050. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40051. }
  40052. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40053. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40054. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40055. }
  40056. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40057. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40058. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40059. }
  40060. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40061. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40062. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  40063. }
  40064. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40065. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40066. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40067. }
  40068. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40069. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40070. mesh.setIndices(indicesData, null);
  40071. }
  40072. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40073. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40074. mesh.subMeshes = [];
  40075. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40076. var materialIndex = subMeshesData[(i * 5) + 0];
  40077. var verticesStart = subMeshesData[(i * 5) + 1];
  40078. var verticesCount = subMeshesData[(i * 5) + 2];
  40079. var indexStart = subMeshesData[(i * 5) + 3];
  40080. var indexCount = subMeshesData[(i * 5) + 4];
  40081. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40082. }
  40083. }
  40084. }
  40085. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40086. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40087. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40088. if (parsedGeometry.tangents) {
  40089. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40090. }
  40091. if (parsedGeometry.uvs) {
  40092. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40093. }
  40094. if (parsedGeometry.uvs2) {
  40095. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40096. }
  40097. if (parsedGeometry.uvs3) {
  40098. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40099. }
  40100. if (parsedGeometry.uvs4) {
  40101. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40102. }
  40103. if (parsedGeometry.uvs5) {
  40104. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40105. }
  40106. if (parsedGeometry.uvs6) {
  40107. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40108. }
  40109. if (parsedGeometry.colors) {
  40110. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40111. }
  40112. if (parsedGeometry.matricesIndices) {
  40113. if (!parsedGeometry.matricesIndices._isExpanded) {
  40114. var floatIndices = [];
  40115. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40116. var matricesIndex = parsedGeometry.matricesIndices[i];
  40117. floatIndices.push(matricesIndex & 0x000000FF);
  40118. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40119. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40120. floatIndices.push(matricesIndex >> 24);
  40121. }
  40122. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40123. }
  40124. else {
  40125. delete parsedGeometry.matricesIndices._isExpanded;
  40126. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40127. }
  40128. }
  40129. if (parsedGeometry.matricesIndicesExtra) {
  40130. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40131. var floatIndices = [];
  40132. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40133. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40134. floatIndices.push(matricesIndex & 0x000000FF);
  40135. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40136. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40137. floatIndices.push(matricesIndex >> 24);
  40138. }
  40139. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40140. }
  40141. else {
  40142. delete parsedGeometry.matricesIndices._isExpanded;
  40143. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40144. }
  40145. }
  40146. if (parsedGeometry.matricesWeights) {
  40147. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40148. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40149. }
  40150. if (parsedGeometry.matricesWeightsExtra) {
  40151. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40152. }
  40153. mesh.setIndices(parsedGeometry.indices, null);
  40154. }
  40155. // SubMeshes
  40156. if (parsedGeometry.subMeshes) {
  40157. mesh.subMeshes = [];
  40158. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40159. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40160. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40161. }
  40162. }
  40163. // Flat shading
  40164. if (mesh._shouldGenerateFlatShading) {
  40165. mesh.convertToFlatShadedMesh();
  40166. delete mesh._shouldGenerateFlatShading;
  40167. }
  40168. // Update
  40169. mesh.computeWorldMatrix(true);
  40170. // Octree
  40171. var sceneOctree = scene.selectionOctree;
  40172. if (sceneOctree !== undefined && sceneOctree !== null) {
  40173. sceneOctree.addMesh(mesh);
  40174. }
  40175. };
  40176. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40177. var epsilon = 1e-3;
  40178. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40179. return;
  40180. }
  40181. var noInfluenceBoneIndex = 0.0;
  40182. if (parsedGeometry.skeletonId > -1) {
  40183. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40184. if (!skeleton) {
  40185. return;
  40186. }
  40187. noInfluenceBoneIndex = skeleton.bones.length;
  40188. }
  40189. else {
  40190. return;
  40191. }
  40192. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40193. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40194. var matricesWeights = parsedGeometry.matricesWeights;
  40195. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40196. var influencers = parsedGeometry.numBoneInfluencer;
  40197. var size = matricesWeights.length;
  40198. for (var i = 0; i < size; i += 4) {
  40199. var weight = 0.0;
  40200. var firstZeroWeight = -1;
  40201. for (var j = 0; j < 4; j++) {
  40202. var w = matricesWeights[i + j];
  40203. weight += w;
  40204. if (w < epsilon && firstZeroWeight < 0) {
  40205. firstZeroWeight = j;
  40206. }
  40207. }
  40208. if (matricesWeightsExtra) {
  40209. for (var j = 0; j < 4; j++) {
  40210. var w = matricesWeightsExtra[i + j];
  40211. weight += w;
  40212. if (w < epsilon && firstZeroWeight < 0) {
  40213. firstZeroWeight = j + 4;
  40214. }
  40215. }
  40216. }
  40217. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40218. firstZeroWeight = influencers - 1;
  40219. }
  40220. if (weight > epsilon) {
  40221. var mweight = 1.0 / weight;
  40222. for (var j = 0; j < 4; j++) {
  40223. matricesWeights[i + j] *= mweight;
  40224. }
  40225. if (matricesWeightsExtra) {
  40226. for (var j = 0; j < 4; j++) {
  40227. matricesWeightsExtra[i + j] *= mweight;
  40228. }
  40229. }
  40230. }
  40231. else {
  40232. if (firstZeroWeight >= 4) {
  40233. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40234. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40235. }
  40236. else {
  40237. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40238. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40239. }
  40240. }
  40241. }
  40242. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40243. if (parsedGeometry.matricesWeightsExtra) {
  40244. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40245. }
  40246. };
  40247. /**
  40248. * Create a new geometry from persisted data (Using .babylon file format)
  40249. * @param parsedVertexData defines the persisted data
  40250. * @param scene defines the hosting scene
  40251. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40252. * @returns the new geometry object
  40253. */
  40254. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40255. if (scene.getGeometryByID(parsedVertexData.id)) {
  40256. return null; // null since geometry could be something else than a box...
  40257. }
  40258. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40259. if (BABYLON.Tags) {
  40260. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40261. }
  40262. if (parsedVertexData.delayLoadingFile) {
  40263. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40264. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40265. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40266. geometry._delayInfo = [];
  40267. if (parsedVertexData.hasUVs) {
  40268. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40269. }
  40270. if (parsedVertexData.hasUVs2) {
  40271. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40272. }
  40273. if (parsedVertexData.hasUVs3) {
  40274. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40275. }
  40276. if (parsedVertexData.hasUVs4) {
  40277. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40278. }
  40279. if (parsedVertexData.hasUVs5) {
  40280. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40281. }
  40282. if (parsedVertexData.hasUVs6) {
  40283. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40284. }
  40285. if (parsedVertexData.hasColors) {
  40286. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40287. }
  40288. if (parsedVertexData.hasMatricesIndices) {
  40289. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40290. }
  40291. if (parsedVertexData.hasMatricesWeights) {
  40292. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40293. }
  40294. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40295. }
  40296. else {
  40297. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40298. }
  40299. scene.pushGeometry(geometry, true);
  40300. return geometry;
  40301. };
  40302. return Geometry;
  40303. }());
  40304. BABYLON.Geometry = Geometry;
  40305. // Primitives
  40306. /// Abstract class
  40307. /**
  40308. * Abstract class used to provide common services for all typed geometries
  40309. * @hidden
  40310. */
  40311. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40312. __extends(_PrimitiveGeometry, _super);
  40313. /**
  40314. * Creates a new typed geometry
  40315. * @param id defines the unique ID of the geometry
  40316. * @param scene defines the hosting scene
  40317. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40318. * @param mesh defines the hosting mesh (can be null)
  40319. */
  40320. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40321. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40322. if (mesh === void 0) { mesh = null; }
  40323. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40324. _this._canBeRegenerated = _canBeRegenerated;
  40325. _this._beingRegenerated = true;
  40326. _this.regenerate();
  40327. _this._beingRegenerated = false;
  40328. return _this;
  40329. }
  40330. /**
  40331. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40332. * @returns true if the geometry can be regenerated
  40333. */
  40334. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40335. return this._canBeRegenerated;
  40336. };
  40337. /**
  40338. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40339. */
  40340. _PrimitiveGeometry.prototype.regenerate = function () {
  40341. if (!this._canBeRegenerated) {
  40342. return;
  40343. }
  40344. this._beingRegenerated = true;
  40345. this.setAllVerticesData(this._regenerateVertexData(), false);
  40346. this._beingRegenerated = false;
  40347. };
  40348. /**
  40349. * Clone the geometry
  40350. * @param id defines the unique ID of the new geometry
  40351. * @returns the new geometry
  40352. */
  40353. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40354. return _super.prototype.copy.call(this, id);
  40355. };
  40356. // overrides
  40357. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40358. if (!this._beingRegenerated) {
  40359. return;
  40360. }
  40361. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40362. };
  40363. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40364. if (!this._beingRegenerated) {
  40365. return;
  40366. }
  40367. _super.prototype.setVerticesData.call(this, kind, data, false);
  40368. };
  40369. // to override
  40370. /** @hidden */
  40371. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40372. throw new Error("Abstract method");
  40373. };
  40374. _PrimitiveGeometry.prototype.copy = function (id) {
  40375. throw new Error("Must be overriden in sub-classes.");
  40376. };
  40377. _PrimitiveGeometry.prototype.serialize = function () {
  40378. var serializationObject = _super.prototype.serialize.call(this);
  40379. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40380. return serializationObject;
  40381. };
  40382. return _PrimitiveGeometry;
  40383. }(Geometry));
  40384. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40385. /**
  40386. * Creates a ribbon geometry
  40387. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40388. */
  40389. var RibbonGeometry = /** @class */ (function (_super) {
  40390. __extends(RibbonGeometry, _super);
  40391. /**
  40392. * Creates a ribbon geometry
  40393. * @param id defines the unique ID of the geometry
  40394. * @param scene defines the hosting scene
  40395. * @param pathArray defines the array of paths to use
  40396. * @param closeArray defines if the last path and the first path must be joined
  40397. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40398. * @param offset defines the offset between points
  40399. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40400. * @param mesh defines the hosting mesh (can be null)
  40401. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40402. */
  40403. function RibbonGeometry(id, scene,
  40404. /**
  40405. * Defines the array of paths to use
  40406. */
  40407. pathArray,
  40408. /**
  40409. * Defines if the last and first points of each path in your pathArray must be joined
  40410. */
  40411. closeArray,
  40412. /**
  40413. * Defines if the last and first points of each path in your pathArray must be joined
  40414. */
  40415. closePath,
  40416. /**
  40417. * Defines the offset between points
  40418. */
  40419. offset, canBeRegenerated, mesh,
  40420. /**
  40421. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40422. */
  40423. side) {
  40424. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40425. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40426. _this.pathArray = pathArray;
  40427. _this.closeArray = closeArray;
  40428. _this.closePath = closePath;
  40429. _this.offset = offset;
  40430. _this.side = side;
  40431. return _this;
  40432. }
  40433. /** @hidden */
  40434. RibbonGeometry.prototype._regenerateVertexData = function () {
  40435. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40436. };
  40437. RibbonGeometry.prototype.copy = function (id) {
  40438. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40439. };
  40440. return RibbonGeometry;
  40441. }(_PrimitiveGeometry));
  40442. BABYLON.RibbonGeometry = RibbonGeometry;
  40443. /**
  40444. * Creates a box geometry
  40445. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40446. */
  40447. var BoxGeometry = /** @class */ (function (_super) {
  40448. __extends(BoxGeometry, _super);
  40449. /**
  40450. * Creates a box geometry
  40451. * @param id defines the unique ID of the geometry
  40452. * @param scene defines the hosting scene
  40453. * @param size defines the zise of the box (width, height and depth are the same)
  40454. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40455. * @param mesh defines the hosting mesh (can be null)
  40456. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40457. */
  40458. function BoxGeometry(id, scene,
  40459. /**
  40460. * Defines the zise of the box (width, height and depth are the same)
  40461. */
  40462. size, canBeRegenerated, mesh,
  40463. /**
  40464. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40465. */
  40466. side) {
  40467. if (mesh === void 0) { mesh = null; }
  40468. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40469. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40470. _this.size = size;
  40471. _this.side = side;
  40472. return _this;
  40473. }
  40474. BoxGeometry.prototype._regenerateVertexData = function () {
  40475. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40476. };
  40477. BoxGeometry.prototype.copy = function (id) {
  40478. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40479. };
  40480. BoxGeometry.prototype.serialize = function () {
  40481. var serializationObject = _super.prototype.serialize.call(this);
  40482. serializationObject.size = this.size;
  40483. return serializationObject;
  40484. };
  40485. BoxGeometry.Parse = function (parsedBox, scene) {
  40486. if (scene.getGeometryByID(parsedBox.id)) {
  40487. return null; // null since geometry could be something else than a box...
  40488. }
  40489. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40490. if (BABYLON.Tags) {
  40491. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40492. }
  40493. scene.pushGeometry(box, true);
  40494. return box;
  40495. };
  40496. return BoxGeometry;
  40497. }(_PrimitiveGeometry));
  40498. BABYLON.BoxGeometry = BoxGeometry;
  40499. /**
  40500. * Creates a sphere geometry
  40501. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40502. */
  40503. var SphereGeometry = /** @class */ (function (_super) {
  40504. __extends(SphereGeometry, _super);
  40505. /**
  40506. * Create a new sphere geometry
  40507. * @param id defines the unique ID of the geometry
  40508. * @param scene defines the hosting scene
  40509. * @param segments defines the number of segments to use to create the sphere
  40510. * @param diameter defines the diameter of the sphere
  40511. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40512. * @param mesh defines the hosting mesh (can be null)
  40513. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40514. */
  40515. function SphereGeometry(id, scene,
  40516. /**
  40517. * Defines the number of segments to use to create the sphere
  40518. */
  40519. segments,
  40520. /**
  40521. * Defines the diameter of the sphere
  40522. */
  40523. diameter, canBeRegenerated, mesh,
  40524. /**
  40525. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40526. */
  40527. side) {
  40528. if (mesh === void 0) { mesh = null; }
  40529. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40530. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40531. _this.segments = segments;
  40532. _this.diameter = diameter;
  40533. _this.side = side;
  40534. return _this;
  40535. }
  40536. SphereGeometry.prototype._regenerateVertexData = function () {
  40537. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40538. };
  40539. SphereGeometry.prototype.copy = function (id) {
  40540. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40541. };
  40542. SphereGeometry.prototype.serialize = function () {
  40543. var serializationObject = _super.prototype.serialize.call(this);
  40544. serializationObject.segments = this.segments;
  40545. serializationObject.diameter = this.diameter;
  40546. return serializationObject;
  40547. };
  40548. SphereGeometry.Parse = function (parsedSphere, scene) {
  40549. if (scene.getGeometryByID(parsedSphere.id)) {
  40550. return null; // null since geometry could be something else than a sphere...
  40551. }
  40552. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40553. if (BABYLON.Tags) {
  40554. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40555. }
  40556. scene.pushGeometry(sphere, true);
  40557. return sphere;
  40558. };
  40559. return SphereGeometry;
  40560. }(_PrimitiveGeometry));
  40561. BABYLON.SphereGeometry = SphereGeometry;
  40562. /**
  40563. * Creates a disc geometry
  40564. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40565. */
  40566. var DiscGeometry = /** @class */ (function (_super) {
  40567. __extends(DiscGeometry, _super);
  40568. /**
  40569. * Creates a new disc geometry
  40570. * @param id defines the unique ID of the geometry
  40571. * @param scene defines the hosting scene
  40572. * @param radius defines the radius of the disc
  40573. * @param tessellation defines the tesselation factor to apply to the disc
  40574. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40575. * @param mesh defines the hosting mesh (can be null)
  40576. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40577. */
  40578. function DiscGeometry(id, scene,
  40579. /**
  40580. * Defines the radius of the disc
  40581. */
  40582. radius,
  40583. /**
  40584. * Defines the tesselation factor to apply to the disc
  40585. */
  40586. tessellation, canBeRegenerated, mesh,
  40587. /**
  40588. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40589. */
  40590. side) {
  40591. if (mesh === void 0) { mesh = null; }
  40592. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40593. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40594. _this.radius = radius;
  40595. _this.tessellation = tessellation;
  40596. _this.side = side;
  40597. return _this;
  40598. }
  40599. DiscGeometry.prototype._regenerateVertexData = function () {
  40600. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40601. };
  40602. DiscGeometry.prototype.copy = function (id) {
  40603. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40604. };
  40605. return DiscGeometry;
  40606. }(_PrimitiveGeometry));
  40607. BABYLON.DiscGeometry = DiscGeometry;
  40608. /**
  40609. * Creates a new cylinder geometry
  40610. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40611. */
  40612. var CylinderGeometry = /** @class */ (function (_super) {
  40613. __extends(CylinderGeometry, _super);
  40614. /**
  40615. * Creates a new cylinder geometry
  40616. * @param id defines the unique ID of the geometry
  40617. * @param scene defines the hosting scene
  40618. * @param height defines the height of the cylinder
  40619. * @param diameterTop defines the diameter of the cylinder's top cap
  40620. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40621. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40622. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40623. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40624. * @param mesh defines the hosting mesh (can be null)
  40625. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40626. */
  40627. function CylinderGeometry(id, scene,
  40628. /**
  40629. * Defines the height of the cylinder
  40630. */
  40631. height,
  40632. /**
  40633. * Defines the diameter of the cylinder's top cap
  40634. */
  40635. diameterTop,
  40636. /**
  40637. * Defines the diameter of the cylinder's bottom cap
  40638. */
  40639. diameterBottom,
  40640. /**
  40641. * Defines the tessellation factor to apply to the cylinder
  40642. */
  40643. tessellation,
  40644. /**
  40645. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40646. */
  40647. subdivisions, canBeRegenerated, mesh,
  40648. /**
  40649. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40650. */
  40651. side) {
  40652. if (subdivisions === void 0) { subdivisions = 1; }
  40653. if (mesh === void 0) { mesh = null; }
  40654. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40655. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40656. _this.height = height;
  40657. _this.diameterTop = diameterTop;
  40658. _this.diameterBottom = diameterBottom;
  40659. _this.tessellation = tessellation;
  40660. _this.subdivisions = subdivisions;
  40661. _this.side = side;
  40662. return _this;
  40663. }
  40664. CylinderGeometry.prototype._regenerateVertexData = function () {
  40665. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40666. };
  40667. CylinderGeometry.prototype.copy = function (id) {
  40668. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40669. };
  40670. CylinderGeometry.prototype.serialize = function () {
  40671. var serializationObject = _super.prototype.serialize.call(this);
  40672. serializationObject.height = this.height;
  40673. serializationObject.diameterTop = this.diameterTop;
  40674. serializationObject.diameterBottom = this.diameterBottom;
  40675. serializationObject.tessellation = this.tessellation;
  40676. return serializationObject;
  40677. };
  40678. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40679. if (scene.getGeometryByID(parsedCylinder.id)) {
  40680. return null; // null since geometry could be something else than a cylinder...
  40681. }
  40682. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40683. if (BABYLON.Tags) {
  40684. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40685. }
  40686. scene.pushGeometry(cylinder, true);
  40687. return cylinder;
  40688. };
  40689. return CylinderGeometry;
  40690. }(_PrimitiveGeometry));
  40691. BABYLON.CylinderGeometry = CylinderGeometry;
  40692. /**
  40693. * Creates a new torus geometry
  40694. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40695. */
  40696. var TorusGeometry = /** @class */ (function (_super) {
  40697. __extends(TorusGeometry, _super);
  40698. /**
  40699. * Creates a new torus geometry
  40700. * @param id defines the unique ID of the geometry
  40701. * @param scene defines the hosting scene
  40702. * @param diameter defines the diameter of the torus
  40703. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40704. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40705. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40706. * @param mesh defines the hosting mesh (can be null)
  40707. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40708. */
  40709. function TorusGeometry(id, scene,
  40710. /**
  40711. * Defines the diameter of the torus
  40712. */
  40713. diameter,
  40714. /**
  40715. * Defines the thickness of the torus (ie. internal diameter)
  40716. */
  40717. thickness,
  40718. /**
  40719. * Defines the tesselation factor to apply to the torus
  40720. */
  40721. tessellation, canBeRegenerated, mesh,
  40722. /**
  40723. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40724. */
  40725. side) {
  40726. if (mesh === void 0) { mesh = null; }
  40727. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40728. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40729. _this.diameter = diameter;
  40730. _this.thickness = thickness;
  40731. _this.tessellation = tessellation;
  40732. _this.side = side;
  40733. return _this;
  40734. }
  40735. TorusGeometry.prototype._regenerateVertexData = function () {
  40736. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40737. };
  40738. TorusGeometry.prototype.copy = function (id) {
  40739. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40740. };
  40741. TorusGeometry.prototype.serialize = function () {
  40742. var serializationObject = _super.prototype.serialize.call(this);
  40743. serializationObject.diameter = this.diameter;
  40744. serializationObject.thickness = this.thickness;
  40745. serializationObject.tessellation = this.tessellation;
  40746. return serializationObject;
  40747. };
  40748. TorusGeometry.Parse = function (parsedTorus, scene) {
  40749. if (scene.getGeometryByID(parsedTorus.id)) {
  40750. return null; // null since geometry could be something else than a torus...
  40751. }
  40752. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40753. if (BABYLON.Tags) {
  40754. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40755. }
  40756. scene.pushGeometry(torus, true);
  40757. return torus;
  40758. };
  40759. return TorusGeometry;
  40760. }(_PrimitiveGeometry));
  40761. BABYLON.TorusGeometry = TorusGeometry;
  40762. /**
  40763. * Creates a new ground geometry
  40764. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40765. */
  40766. var GroundGeometry = /** @class */ (function (_super) {
  40767. __extends(GroundGeometry, _super);
  40768. /**
  40769. * Creates a new ground geometry
  40770. * @param id defines the unique ID of the geometry
  40771. * @param scene defines the hosting scene
  40772. * @param width defines the width of the ground
  40773. * @param height defines the height of the ground
  40774. * @param subdivisions defines the subdivisions to apply to the ground
  40775. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40776. * @param mesh defines the hosting mesh (can be null)
  40777. */
  40778. function GroundGeometry(id, scene,
  40779. /**
  40780. * Defines the width of the ground
  40781. */
  40782. width,
  40783. /**
  40784. * Defines the height of the ground
  40785. */
  40786. height,
  40787. /**
  40788. * Defines the subdivisions to apply to the ground
  40789. */
  40790. subdivisions, canBeRegenerated, mesh) {
  40791. if (mesh === void 0) { mesh = null; }
  40792. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40793. _this.width = width;
  40794. _this.height = height;
  40795. _this.subdivisions = subdivisions;
  40796. return _this;
  40797. }
  40798. GroundGeometry.prototype._regenerateVertexData = function () {
  40799. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40800. };
  40801. GroundGeometry.prototype.copy = function (id) {
  40802. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40803. };
  40804. GroundGeometry.prototype.serialize = function () {
  40805. var serializationObject = _super.prototype.serialize.call(this);
  40806. serializationObject.width = this.width;
  40807. serializationObject.height = this.height;
  40808. serializationObject.subdivisions = this.subdivisions;
  40809. return serializationObject;
  40810. };
  40811. GroundGeometry.Parse = function (parsedGround, scene) {
  40812. if (scene.getGeometryByID(parsedGround.id)) {
  40813. return null; // null since geometry could be something else than a ground...
  40814. }
  40815. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40816. if (BABYLON.Tags) {
  40817. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40818. }
  40819. scene.pushGeometry(ground, true);
  40820. return ground;
  40821. };
  40822. return GroundGeometry;
  40823. }(_PrimitiveGeometry));
  40824. BABYLON.GroundGeometry = GroundGeometry;
  40825. /**
  40826. * Creates a tiled ground geometry
  40827. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40828. */
  40829. var TiledGroundGeometry = /** @class */ (function (_super) {
  40830. __extends(TiledGroundGeometry, _super);
  40831. /**
  40832. * Creates a tiled ground geometry
  40833. * @param id defines the unique ID of the geometry
  40834. * @param scene defines the hosting scene
  40835. * @param xmin defines the minimum value on X axis
  40836. * @param zmin defines the minimum value on Z axis
  40837. * @param xmax defines the maximum value on X axis
  40838. * @param zmax defines the maximum value on Z axis
  40839. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40840. * @param precision defines the precision to use when computing the tiles
  40841. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40842. * @param mesh defines the hosting mesh (can be null)
  40843. */
  40844. function TiledGroundGeometry(id, scene,
  40845. /**
  40846. * Defines the minimum value on X axis
  40847. */
  40848. xmin,
  40849. /**
  40850. * Defines the minimum value on Z axis
  40851. */
  40852. zmin,
  40853. /**
  40854. * Defines the maximum value on X axis
  40855. */
  40856. xmax,
  40857. /**
  40858. * Defines the maximum value on Z axis
  40859. */
  40860. zmax,
  40861. /**
  40862. * Defines the subdivisions to apply to the ground
  40863. */
  40864. subdivisions,
  40865. /**
  40866. * Defines the precision to use when computing the tiles
  40867. */
  40868. precision, canBeRegenerated, mesh) {
  40869. if (mesh === void 0) { mesh = null; }
  40870. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40871. _this.xmin = xmin;
  40872. _this.zmin = zmin;
  40873. _this.xmax = xmax;
  40874. _this.zmax = zmax;
  40875. _this.subdivisions = subdivisions;
  40876. _this.precision = precision;
  40877. return _this;
  40878. }
  40879. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40880. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40881. };
  40882. TiledGroundGeometry.prototype.copy = function (id) {
  40883. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40884. };
  40885. return TiledGroundGeometry;
  40886. }(_PrimitiveGeometry));
  40887. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40888. /**
  40889. * Creates a plane geometry
  40890. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40891. */
  40892. var PlaneGeometry = /** @class */ (function (_super) {
  40893. __extends(PlaneGeometry, _super);
  40894. /**
  40895. * Creates a plane geometry
  40896. * @param id defines the unique ID of the geometry
  40897. * @param scene defines the hosting scene
  40898. * @param size defines the size of the plane (width === height)
  40899. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40900. * @param mesh defines the hosting mesh (can be null)
  40901. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40902. */
  40903. function PlaneGeometry(id, scene,
  40904. /**
  40905. * Defines the size of the plane (width === height)
  40906. */
  40907. size, canBeRegenerated, mesh,
  40908. /**
  40909. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40910. */
  40911. side) {
  40912. if (mesh === void 0) { mesh = null; }
  40913. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40914. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40915. _this.size = size;
  40916. _this.side = side;
  40917. return _this;
  40918. }
  40919. PlaneGeometry.prototype._regenerateVertexData = function () {
  40920. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40921. };
  40922. PlaneGeometry.prototype.copy = function (id) {
  40923. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40924. };
  40925. PlaneGeometry.prototype.serialize = function () {
  40926. var serializationObject = _super.prototype.serialize.call(this);
  40927. serializationObject.size = this.size;
  40928. return serializationObject;
  40929. };
  40930. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40931. if (scene.getGeometryByID(parsedPlane.id)) {
  40932. return null; // null since geometry could be something else than a ground...
  40933. }
  40934. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40935. if (BABYLON.Tags) {
  40936. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40937. }
  40938. scene.pushGeometry(plane, true);
  40939. return plane;
  40940. };
  40941. return PlaneGeometry;
  40942. }(_PrimitiveGeometry));
  40943. BABYLON.PlaneGeometry = PlaneGeometry;
  40944. /**
  40945. * Creates a torus knot geometry
  40946. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40947. */
  40948. var TorusKnotGeometry = /** @class */ (function (_super) {
  40949. __extends(TorusKnotGeometry, _super);
  40950. /**
  40951. * Creates a torus knot geometry
  40952. * @param id defines the unique ID of the geometry
  40953. * @param scene defines the hosting scene
  40954. * @param radius defines the radius of the torus knot
  40955. * @param tube defines the thickness of the torus knot tube
  40956. * @param radialSegments defines the number of radial segments
  40957. * @param tubularSegments defines the number of tubular segments
  40958. * @param p defines the first number of windings
  40959. * @param q defines the second number of windings
  40960. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40961. * @param mesh defines the hosting mesh (can be null)
  40962. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40963. */
  40964. function TorusKnotGeometry(id, scene,
  40965. /**
  40966. * Defines the radius of the torus knot
  40967. */
  40968. radius,
  40969. /**
  40970. * Defines the thickness of the torus knot tube
  40971. */
  40972. tube,
  40973. /**
  40974. * Defines the number of radial segments
  40975. */
  40976. radialSegments,
  40977. /**
  40978. * Defines the number of tubular segments
  40979. */
  40980. tubularSegments,
  40981. /**
  40982. * Defines the first number of windings
  40983. */
  40984. p,
  40985. /**
  40986. * Defines the second number of windings
  40987. */
  40988. q, canBeRegenerated, mesh,
  40989. /**
  40990. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40991. */
  40992. side) {
  40993. if (mesh === void 0) { mesh = null; }
  40994. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40995. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40996. _this.radius = radius;
  40997. _this.tube = tube;
  40998. _this.radialSegments = radialSegments;
  40999. _this.tubularSegments = tubularSegments;
  41000. _this.p = p;
  41001. _this.q = q;
  41002. _this.side = side;
  41003. return _this;
  41004. }
  41005. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41006. 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 });
  41007. };
  41008. TorusKnotGeometry.prototype.copy = function (id) {
  41009. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41010. };
  41011. TorusKnotGeometry.prototype.serialize = function () {
  41012. var serializationObject = _super.prototype.serialize.call(this);
  41013. serializationObject.radius = this.radius;
  41014. serializationObject.tube = this.tube;
  41015. serializationObject.radialSegments = this.radialSegments;
  41016. serializationObject.tubularSegments = this.tubularSegments;
  41017. serializationObject.p = this.p;
  41018. serializationObject.q = this.q;
  41019. return serializationObject;
  41020. };
  41021. ;
  41022. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41023. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41024. return null; // null since geometry could be something else than a ground...
  41025. }
  41026. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41027. if (BABYLON.Tags) {
  41028. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41029. }
  41030. scene.pushGeometry(torusKnot, true);
  41031. return torusKnot;
  41032. };
  41033. return TorusKnotGeometry;
  41034. }(_PrimitiveGeometry));
  41035. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41036. //}
  41037. })(BABYLON || (BABYLON = {}));
  41038. //# sourceMappingURL=babylon.geometry.js.map
  41039. var BABYLON;
  41040. (function (BABYLON) {
  41041. /**
  41042. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41043. */
  41044. var PerformanceMonitor = /** @class */ (function () {
  41045. /**
  41046. * constructor
  41047. * @param frameSampleSize The number of samples required to saturate the sliding window
  41048. */
  41049. function PerformanceMonitor(frameSampleSize) {
  41050. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41051. this._enabled = true;
  41052. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41053. }
  41054. /**
  41055. * Samples current frame
  41056. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41057. */
  41058. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41059. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41060. if (!this._enabled)
  41061. return;
  41062. if (this._lastFrameTimeMs != null) {
  41063. var dt = timeMs - this._lastFrameTimeMs;
  41064. this._rollingFrameTime.add(dt);
  41065. }
  41066. this._lastFrameTimeMs = timeMs;
  41067. };
  41068. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41069. /**
  41070. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41071. * @return Average frame time in milliseconds
  41072. */
  41073. get: function () {
  41074. return this._rollingFrameTime.average;
  41075. },
  41076. enumerable: true,
  41077. configurable: true
  41078. });
  41079. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41080. /**
  41081. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41082. * @return Frame time variance in milliseconds squared
  41083. */
  41084. get: function () {
  41085. return this._rollingFrameTime.variance;
  41086. },
  41087. enumerable: true,
  41088. configurable: true
  41089. });
  41090. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41091. /**
  41092. * Returns the frame time of the most recent frame
  41093. * @return Frame time in milliseconds
  41094. */
  41095. get: function () {
  41096. return this._rollingFrameTime.history(0);
  41097. },
  41098. enumerable: true,
  41099. configurable: true
  41100. });
  41101. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41102. /**
  41103. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41104. * @return Framerate in frames per second
  41105. */
  41106. get: function () {
  41107. return 1000.0 / this._rollingFrameTime.average;
  41108. },
  41109. enumerable: true,
  41110. configurable: true
  41111. });
  41112. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41113. /**
  41114. * Returns the average framerate in frames per second using the most recent frame time
  41115. * @return Framerate in frames per second
  41116. */
  41117. get: function () {
  41118. var history = this._rollingFrameTime.history(0);
  41119. if (history === 0) {
  41120. return 0;
  41121. }
  41122. return 1000.0 / history;
  41123. },
  41124. enumerable: true,
  41125. configurable: true
  41126. });
  41127. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41128. /**
  41129. * Returns true if enough samples have been taken to completely fill the sliding window
  41130. * @return true if saturated
  41131. */
  41132. get: function () {
  41133. return this._rollingFrameTime.isSaturated();
  41134. },
  41135. enumerable: true,
  41136. configurable: true
  41137. });
  41138. /**
  41139. * Enables contributions to the sliding window sample set
  41140. */
  41141. PerformanceMonitor.prototype.enable = function () {
  41142. this._enabled = true;
  41143. };
  41144. /**
  41145. * Disables contributions to the sliding window sample set
  41146. * Samples will not be interpolated over the disabled period
  41147. */
  41148. PerformanceMonitor.prototype.disable = function () {
  41149. this._enabled = false;
  41150. //clear last sample to avoid interpolating over the disabled period when next enabled
  41151. this._lastFrameTimeMs = null;
  41152. };
  41153. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41154. /**
  41155. * Returns true if sampling is enabled
  41156. * @return true if enabled
  41157. */
  41158. get: function () {
  41159. return this._enabled;
  41160. },
  41161. enumerable: true,
  41162. configurable: true
  41163. });
  41164. /**
  41165. * Resets performance monitor
  41166. */
  41167. PerformanceMonitor.prototype.reset = function () {
  41168. //clear last sample to avoid interpolating over the disabled period when next enabled
  41169. this._lastFrameTimeMs = null;
  41170. //wipe record
  41171. this._rollingFrameTime.reset();
  41172. };
  41173. return PerformanceMonitor;
  41174. }());
  41175. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41176. /**
  41177. * RollingAverage
  41178. *
  41179. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41180. */
  41181. var RollingAverage = /** @class */ (function () {
  41182. /**
  41183. * constructor
  41184. * @param length The number of samples required to saturate the sliding window
  41185. */
  41186. function RollingAverage(length) {
  41187. this._samples = new Array(length);
  41188. this.reset();
  41189. }
  41190. /**
  41191. * Adds a sample to the sample set
  41192. * @param v The sample value
  41193. */
  41194. RollingAverage.prototype.add = function (v) {
  41195. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41196. var delta;
  41197. //we need to check if we've already wrapped round
  41198. if (this.isSaturated()) {
  41199. //remove bottom of stack from mean
  41200. var bottomValue = this._samples[this._pos];
  41201. delta = bottomValue - this.average;
  41202. this.average -= delta / (this._sampleCount - 1);
  41203. this._m2 -= delta * (bottomValue - this.average);
  41204. }
  41205. else {
  41206. this._sampleCount++;
  41207. }
  41208. //add new value to mean
  41209. delta = v - this.average;
  41210. this.average += delta / (this._sampleCount);
  41211. this._m2 += delta * (v - this.average);
  41212. //set the new variance
  41213. this.variance = this._m2 / (this._sampleCount - 1);
  41214. this._samples[this._pos] = v;
  41215. this._pos++;
  41216. this._pos %= this._samples.length; //positive wrap around
  41217. };
  41218. /**
  41219. * Returns previously added values or null if outside of history or outside the sliding window domain
  41220. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41221. * @return Value previously recorded with add() or null if outside of range
  41222. */
  41223. RollingAverage.prototype.history = function (i) {
  41224. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41225. return 0;
  41226. }
  41227. var i0 = this._wrapPosition(this._pos - 1.0);
  41228. return this._samples[this._wrapPosition(i0 - i)];
  41229. };
  41230. /**
  41231. * Returns true if enough samples have been taken to completely fill the sliding window
  41232. * @return true if sample-set saturated
  41233. */
  41234. RollingAverage.prototype.isSaturated = function () {
  41235. return this._sampleCount >= this._samples.length;
  41236. };
  41237. /**
  41238. * Resets the rolling average (equivalent to 0 samples taken so far)
  41239. */
  41240. RollingAverage.prototype.reset = function () {
  41241. this.average = 0;
  41242. this.variance = 0;
  41243. this._sampleCount = 0;
  41244. this._pos = 0;
  41245. this._m2 = 0;
  41246. };
  41247. /**
  41248. * Wraps a value around the sample range boundaries
  41249. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41250. * @return Wrapped position in sample range
  41251. */
  41252. RollingAverage.prototype._wrapPosition = function (i) {
  41253. var max = this._samples.length;
  41254. return ((i % max) + max) % max;
  41255. };
  41256. return RollingAverage;
  41257. }());
  41258. BABYLON.RollingAverage = RollingAverage;
  41259. })(BABYLON || (BABYLON = {}));
  41260. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41261. var BABYLON;
  41262. (function (BABYLON) {
  41263. /**
  41264. * "Static Class" containing the most commonly used helper while dealing with material for
  41265. * rendering purpose.
  41266. *
  41267. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41268. *
  41269. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41270. */
  41271. var MaterialHelper = /** @class */ (function () {
  41272. function MaterialHelper() {
  41273. }
  41274. /**
  41275. * Bind the current view position to an effect.
  41276. * @param effect The effect to be bound
  41277. * @param scene The scene the eyes position is used from
  41278. */
  41279. MaterialHelper.BindEyePosition = function (effect, scene) {
  41280. if (scene._forcedViewPosition) {
  41281. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41282. return;
  41283. }
  41284. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41285. };
  41286. /**
  41287. * Helps preparing the defines values about the UVs in used in the effect.
  41288. * UVs are shared as much as we can accross chanels in the shaders.
  41289. * @param texture The texture we are preparing the UVs for
  41290. * @param defines The defines to update
  41291. * @param key The chanel key "diffuse", "specular"... used in the shader
  41292. */
  41293. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41294. defines._needUVs = true;
  41295. defines[key] = true;
  41296. if (texture.getTextureMatrix().isIdentity(true)) {
  41297. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41298. if (texture.coordinatesIndex === 0) {
  41299. defines["MAINUV1"] = true;
  41300. }
  41301. else {
  41302. defines["MAINUV2"] = true;
  41303. }
  41304. }
  41305. else {
  41306. defines[key + "DIRECTUV"] = 0;
  41307. }
  41308. };
  41309. /**
  41310. * Binds a texture matrix value to its corrsponding uniform
  41311. * @param texture The texture to bind the matrix for
  41312. * @param uniformBuffer The uniform buffer receivin the data
  41313. * @param key The chanel key "diffuse", "specular"... used in the shader
  41314. */
  41315. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41316. var matrix = texture.getTextureMatrix();
  41317. if (!matrix.isIdentity(true)) {
  41318. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41319. }
  41320. };
  41321. /**
  41322. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41323. * @param mesh defines the current mesh
  41324. * @param scene defines the current scene
  41325. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41326. * @param pointsCloud defines if point cloud rendering has to be turned on
  41327. * @param fogEnabled defines if fog has to be turned on
  41328. * @param alphaTest defines if alpha testing has to be turned on
  41329. * @param defines defines the current list of defines
  41330. */
  41331. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41332. if (defines._areMiscDirty) {
  41333. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41334. defines["POINTSIZE"] = pointsCloud;
  41335. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41336. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41337. defines["ALPHATEST"] = alphaTest;
  41338. }
  41339. };
  41340. /**
  41341. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41342. * @param scene defines the current scene
  41343. * @param engine defines the current engine
  41344. * @param defines specifies the list of active defines
  41345. * @param useInstances defines if instances have to be turned on
  41346. * @param useClipPlane defines if clip plane have to be turned on
  41347. */
  41348. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41349. if (useClipPlane === void 0) { useClipPlane = null; }
  41350. var changed = false;
  41351. if (useClipPlane == null) {
  41352. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41353. }
  41354. if (defines["CLIPPLANE"] !== useClipPlane) {
  41355. defines["CLIPPLANE"] = useClipPlane;
  41356. changed = true;
  41357. }
  41358. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41359. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41360. changed = true;
  41361. }
  41362. if (defines["INSTANCES"] !== useInstances) {
  41363. defines["INSTANCES"] = useInstances;
  41364. changed = true;
  41365. }
  41366. if (changed) {
  41367. defines.markAsUnprocessed();
  41368. }
  41369. };
  41370. /**
  41371. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41372. * @param mesh The mesh containing the geometry data we will draw
  41373. * @param defines The defines to update
  41374. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41375. * @param useBones Precise whether bones should be used or not (override mesh info)
  41376. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41377. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41378. * @returns false if defines are considered not dirty and have not been checked
  41379. */
  41380. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41381. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41382. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41383. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41384. return false;
  41385. }
  41386. defines._normals = defines._needNormals;
  41387. defines._uvs = defines._needUVs;
  41388. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41389. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41390. defines["TANGENT"] = true;
  41391. }
  41392. if (defines._needUVs) {
  41393. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41394. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41395. }
  41396. else {
  41397. defines["UV1"] = false;
  41398. defines["UV2"] = false;
  41399. }
  41400. if (useVertexColor) {
  41401. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41402. defines["VERTEXCOLOR"] = hasVertexColors;
  41403. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41404. }
  41405. if (useBones) {
  41406. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41407. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41408. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41409. }
  41410. else {
  41411. defines["NUM_BONE_INFLUENCERS"] = 0;
  41412. defines["BonesPerMesh"] = 0;
  41413. }
  41414. }
  41415. if (useMorphTargets) {
  41416. var manager = mesh.morphTargetManager;
  41417. if (manager) {
  41418. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41419. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41420. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41421. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41422. }
  41423. else {
  41424. defines["MORPHTARGETS_TANGENT"] = false;
  41425. defines["MORPHTARGETS_NORMAL"] = false;
  41426. defines["MORPHTARGETS"] = false;
  41427. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41428. }
  41429. }
  41430. return true;
  41431. };
  41432. /**
  41433. * Prepares the defines related to the light information passed in parameter
  41434. * @param scene The scene we are intending to draw
  41435. * @param mesh The mesh the effect is compiling for
  41436. * @param defines The defines to update
  41437. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41438. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41439. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41440. * @returns true if normals will be required for the rest of the effect
  41441. */
  41442. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41443. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41444. if (disableLighting === void 0) { disableLighting = false; }
  41445. if (!defines._areLightsDirty) {
  41446. return defines._needNormals;
  41447. }
  41448. var lightIndex = 0;
  41449. var needNormals = false;
  41450. var needRebuild = false;
  41451. var lightmapMode = false;
  41452. var shadowEnabled = false;
  41453. var specularEnabled = false;
  41454. if (scene.lightsEnabled && !disableLighting) {
  41455. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41456. var light = _a[_i];
  41457. needNormals = true;
  41458. if (defines["LIGHT" + lightIndex] === undefined) {
  41459. needRebuild = true;
  41460. }
  41461. defines["LIGHT" + lightIndex] = true;
  41462. defines["SPOTLIGHT" + lightIndex] = false;
  41463. defines["HEMILIGHT" + lightIndex] = false;
  41464. defines["POINTLIGHT" + lightIndex] = false;
  41465. defines["DIRLIGHT" + lightIndex] = false;
  41466. var type;
  41467. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41468. type = "SPOTLIGHT" + lightIndex;
  41469. var spotLight = light;
  41470. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41471. }
  41472. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41473. type = "HEMILIGHT" + lightIndex;
  41474. }
  41475. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41476. type = "POINTLIGHT" + lightIndex;
  41477. }
  41478. else {
  41479. type = "DIRLIGHT" + lightIndex;
  41480. }
  41481. defines[type] = true;
  41482. // Specular
  41483. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41484. specularEnabled = true;
  41485. }
  41486. // Shadows
  41487. defines["SHADOW" + lightIndex] = false;
  41488. defines["SHADOWPCF" + lightIndex] = false;
  41489. defines["SHADOWPCSS" + lightIndex] = false;
  41490. defines["SHADOWPOISSON" + lightIndex] = false;
  41491. defines["SHADOWESM" + lightIndex] = false;
  41492. defines["SHADOWCUBE" + lightIndex] = false;
  41493. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41494. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41495. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41496. var shadowGenerator = light.getShadowGenerator();
  41497. if (shadowGenerator) {
  41498. shadowEnabled = true;
  41499. shadowGenerator.prepareDefines(defines, lightIndex);
  41500. }
  41501. }
  41502. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41503. lightmapMode = true;
  41504. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41505. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41506. }
  41507. else {
  41508. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41509. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41510. }
  41511. lightIndex++;
  41512. if (lightIndex === maxSimultaneousLights)
  41513. break;
  41514. }
  41515. }
  41516. defines["SPECULARTERM"] = specularEnabled;
  41517. defines["SHADOWS"] = shadowEnabled;
  41518. // Resetting all other lights if any
  41519. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41520. if (defines["LIGHT" + index] !== undefined) {
  41521. defines["LIGHT" + index] = false;
  41522. defines["HEMILIGHT" + lightIndex] = false;
  41523. defines["POINTLIGHT" + lightIndex] = false;
  41524. defines["DIRLIGHT" + lightIndex] = false;
  41525. defines["SPOTLIGHT" + lightIndex] = false;
  41526. defines["SHADOW" + lightIndex] = false;
  41527. }
  41528. }
  41529. var caps = scene.getEngine().getCaps();
  41530. if (defines["SHADOWFLOAT"] === undefined) {
  41531. needRebuild = true;
  41532. }
  41533. defines["SHADOWFLOAT"] = shadowEnabled &&
  41534. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41535. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41536. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41537. if (needRebuild) {
  41538. defines.rebuild();
  41539. }
  41540. return needNormals;
  41541. };
  41542. /**
  41543. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41544. * that won t be acctive due to defines being turned off.
  41545. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41546. * @param samplersList The samplers list
  41547. * @param defines The defines helping in the list generation
  41548. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41549. */
  41550. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41551. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41552. var uniformsList;
  41553. var uniformBuffersList = null;
  41554. if (uniformsListOrOptions.uniformsNames) {
  41555. var options = uniformsListOrOptions;
  41556. uniformsList = options.uniformsNames;
  41557. uniformBuffersList = options.uniformBuffersNames;
  41558. samplersList = options.samplers;
  41559. defines = options.defines;
  41560. maxSimultaneousLights = options.maxSimultaneousLights;
  41561. }
  41562. else {
  41563. uniformsList = uniformsListOrOptions;
  41564. if (!samplersList) {
  41565. samplersList = [];
  41566. }
  41567. }
  41568. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41569. if (!defines["LIGHT" + lightIndex]) {
  41570. break;
  41571. }
  41572. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41573. if (uniformBuffersList) {
  41574. uniformBuffersList.push("Light" + lightIndex);
  41575. }
  41576. samplersList.push("shadowSampler" + lightIndex);
  41577. samplersList.push("depthSampler" + lightIndex);
  41578. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41579. samplersList.push("projectionLightSampler" + lightIndex);
  41580. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41581. }
  41582. }
  41583. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41584. uniformsList.push("morphTargetInfluences");
  41585. }
  41586. };
  41587. /**
  41588. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41589. * @param defines The defines to update while falling back
  41590. * @param fallbacks The authorized effect fallbacks
  41591. * @param maxSimultaneousLights The maximum number of lights allowed
  41592. * @param rank the current rank of the Effect
  41593. * @returns The newly affected rank
  41594. */
  41595. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41596. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41597. if (rank === void 0) { rank = 0; }
  41598. var lightFallbackRank = 0;
  41599. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41600. if (!defines["LIGHT" + lightIndex]) {
  41601. break;
  41602. }
  41603. if (lightIndex > 0) {
  41604. lightFallbackRank = rank + lightIndex;
  41605. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41606. }
  41607. if (!defines["SHADOWS"]) {
  41608. if (defines["SHADOW" + lightIndex]) {
  41609. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41610. }
  41611. if (defines["SHADOWPCF" + lightIndex]) {
  41612. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41613. }
  41614. if (defines["SHADOWPCSS" + lightIndex]) {
  41615. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41616. }
  41617. if (defines["SHADOWPOISSON" + lightIndex]) {
  41618. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41619. }
  41620. if (defines["SHADOWESM" + lightIndex]) {
  41621. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41622. }
  41623. }
  41624. }
  41625. return lightFallbackRank++;
  41626. };
  41627. /**
  41628. * Prepares the list of attributes required for morph targets according to the effect defines.
  41629. * @param attribs The current list of supported attribs
  41630. * @param mesh The mesh to prepare the morph targets attributes for
  41631. * @param defines The current Defines of the effect
  41632. */
  41633. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41634. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41635. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41636. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41637. var manager = mesh.morphTargetManager;
  41638. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41639. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41640. for (var index = 0; index < influencers; index++) {
  41641. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41642. if (normal) {
  41643. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41644. }
  41645. if (tangent) {
  41646. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41647. }
  41648. if (attribs.length > maxAttributesCount) {
  41649. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41650. }
  41651. }
  41652. }
  41653. };
  41654. /**
  41655. * Prepares the list of attributes required for bones according to the effect defines.
  41656. * @param attribs The current list of supported attribs
  41657. * @param mesh The mesh to prepare the bones attributes for
  41658. * @param defines The current Defines of the effect
  41659. * @param fallbacks The current efffect fallback strategy
  41660. */
  41661. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41662. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41663. fallbacks.addCPUSkinningFallback(0, mesh);
  41664. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41665. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41666. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41667. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41668. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41669. }
  41670. }
  41671. };
  41672. /**
  41673. * Prepares the list of attributes required for instances according to the effect defines.
  41674. * @param attribs The current list of supported attribs
  41675. * @param defines The current Defines of the effect
  41676. */
  41677. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41678. if (defines["INSTANCES"]) {
  41679. attribs.push("world0");
  41680. attribs.push("world1");
  41681. attribs.push("world2");
  41682. attribs.push("world3");
  41683. }
  41684. };
  41685. /**
  41686. * Binds the light shadow information to the effect for the given mesh.
  41687. * @param light The light containing the generator
  41688. * @param scene The scene the lights belongs to
  41689. * @param mesh The mesh we are binding the information to render
  41690. * @param lightIndex The light index in the effect used to render the mesh
  41691. * @param effect The effect we are binding the data to
  41692. */
  41693. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41694. if (light.shadowEnabled && mesh.receiveShadows) {
  41695. var shadowGenerator = light.getShadowGenerator();
  41696. if (shadowGenerator) {
  41697. shadowGenerator.bindShadowLight(lightIndex, effect);
  41698. }
  41699. }
  41700. };
  41701. /**
  41702. * Binds the light information to the effect.
  41703. * @param light The light containing the generator
  41704. * @param effect The effect we are binding the data to
  41705. * @param lightIndex The light index in the effect used to render
  41706. */
  41707. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41708. light.transferToEffect(effect, lightIndex + "");
  41709. };
  41710. /**
  41711. * Binds the lights information from the scene to the effect for the given mesh.
  41712. * @param scene The scene the lights belongs to
  41713. * @param mesh The mesh we are binding the information to render
  41714. * @param effect The effect we are binding the data to
  41715. * @param defines The generated defines for the effect
  41716. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41717. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41718. */
  41719. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41720. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41721. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41722. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41723. for (var i = 0; i < len; i++) {
  41724. var light = mesh._lightSources[i];
  41725. var iAsString = i.toString();
  41726. var scaledIntensity = light.getScaledIntensity();
  41727. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41728. MaterialHelper.BindLightProperties(light, effect, i);
  41729. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41730. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41731. if (defines["SPECULARTERM"]) {
  41732. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41733. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41734. }
  41735. // Shadows
  41736. if (scene.shadowsEnabled) {
  41737. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41738. }
  41739. light._uniformBuffer.update();
  41740. }
  41741. };
  41742. /**
  41743. * Binds the fog information from the scene to the effect for the given mesh.
  41744. * @param scene The scene the lights belongs to
  41745. * @param mesh The mesh we are binding the information to render
  41746. * @param effect The effect we are binding the data to
  41747. */
  41748. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41749. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41750. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41751. effect.setColor3("vFogColor", scene.fogColor);
  41752. }
  41753. };
  41754. /**
  41755. * Binds the bones information from the mesh to the effect.
  41756. * @param mesh The mesh we are binding the information to render
  41757. * @param effect The effect we are binding the data to
  41758. */
  41759. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41760. if (!effect || !mesh) {
  41761. return;
  41762. }
  41763. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41764. mesh.computeBonesUsingShaders = false;
  41765. }
  41766. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41767. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41768. if (matrices) {
  41769. effect.setMatrices("mBones", matrices);
  41770. }
  41771. }
  41772. };
  41773. /**
  41774. * Binds the morph targets information from the mesh to the effect.
  41775. * @param abstractMesh The mesh we are binding the information to render
  41776. * @param effect The effect we are binding the data to
  41777. */
  41778. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41779. var manager = abstractMesh.morphTargetManager;
  41780. if (!abstractMesh || !manager) {
  41781. return;
  41782. }
  41783. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41784. };
  41785. /**
  41786. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41787. * @param defines The generated defines used in the effect
  41788. * @param effect The effect we are binding the data to
  41789. * @param scene The scene we are willing to render with logarithmic scale for
  41790. */
  41791. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41792. if (defines["LOGARITHMICDEPTH"]) {
  41793. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41794. }
  41795. };
  41796. /**
  41797. * Binds the clip plane information from the scene to the effect.
  41798. * @param scene The scene the clip plane information are extracted from
  41799. * @param effect The effect we are binding the data to
  41800. */
  41801. MaterialHelper.BindClipPlane = function (effect, scene) {
  41802. if (scene.clipPlane) {
  41803. var clipPlane = scene.clipPlane;
  41804. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41805. }
  41806. };
  41807. return MaterialHelper;
  41808. }());
  41809. BABYLON.MaterialHelper = MaterialHelper;
  41810. })(BABYLON || (BABYLON = {}));
  41811. //# sourceMappingURL=babylon.materialHelper.js.map
  41812. var BABYLON;
  41813. (function (BABYLON) {
  41814. var PushMaterial = /** @class */ (function (_super) {
  41815. __extends(PushMaterial, _super);
  41816. function PushMaterial(name, scene) {
  41817. var _this = _super.call(this, name, scene) || this;
  41818. _this._normalMatrix = new BABYLON.Matrix();
  41819. _this.storeEffectOnSubMeshes = true;
  41820. return _this;
  41821. }
  41822. PushMaterial.prototype.getEffect = function () {
  41823. return this._activeEffect;
  41824. };
  41825. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41826. if (!mesh) {
  41827. return false;
  41828. }
  41829. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41830. return true;
  41831. }
  41832. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41833. };
  41834. /**
  41835. * Binds the given world matrix to the active effect
  41836. *
  41837. * @param world the matrix to bind
  41838. */
  41839. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41840. this._activeEffect.setMatrix("world", world);
  41841. };
  41842. /**
  41843. * Binds the given normal matrix to the active effect
  41844. *
  41845. * @param normalMatrix the matrix to bind
  41846. */
  41847. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41848. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41849. };
  41850. PushMaterial.prototype.bind = function (world, mesh) {
  41851. if (!mesh) {
  41852. return;
  41853. }
  41854. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41855. };
  41856. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41857. if (effect === void 0) { effect = null; }
  41858. _super.prototype._afterBind.call(this, mesh);
  41859. this.getScene()._cachedEffect = effect;
  41860. };
  41861. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41862. if (visibility === void 0) { visibility = 1; }
  41863. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41864. };
  41865. return PushMaterial;
  41866. }(BABYLON.Material));
  41867. BABYLON.PushMaterial = PushMaterial;
  41868. })(BABYLON || (BABYLON = {}));
  41869. //# sourceMappingURL=babylon.pushMaterial.js.map
  41870. var BABYLON;
  41871. (function (BABYLON) {
  41872. /** @hidden */
  41873. var StandardMaterialDefines = /** @class */ (function (_super) {
  41874. __extends(StandardMaterialDefines, _super);
  41875. function StandardMaterialDefines() {
  41876. var _this = _super.call(this) || this;
  41877. _this.MAINUV1 = false;
  41878. _this.MAINUV2 = false;
  41879. _this.DIFFUSE = false;
  41880. _this.DIFFUSEDIRECTUV = 0;
  41881. _this.AMBIENT = false;
  41882. _this.AMBIENTDIRECTUV = 0;
  41883. _this.OPACITY = false;
  41884. _this.OPACITYDIRECTUV = 0;
  41885. _this.OPACITYRGB = false;
  41886. _this.REFLECTION = false;
  41887. _this.EMISSIVE = false;
  41888. _this.EMISSIVEDIRECTUV = 0;
  41889. _this.SPECULAR = false;
  41890. _this.SPECULARDIRECTUV = 0;
  41891. _this.BUMP = false;
  41892. _this.BUMPDIRECTUV = 0;
  41893. _this.PARALLAX = false;
  41894. _this.PARALLAXOCCLUSION = false;
  41895. _this.SPECULAROVERALPHA = false;
  41896. _this.CLIPPLANE = false;
  41897. _this.ALPHATEST = false;
  41898. _this.DEPTHPREPASS = false;
  41899. _this.ALPHAFROMDIFFUSE = false;
  41900. _this.POINTSIZE = false;
  41901. _this.FOG = false;
  41902. _this.SPECULARTERM = false;
  41903. _this.DIFFUSEFRESNEL = false;
  41904. _this.OPACITYFRESNEL = false;
  41905. _this.REFLECTIONFRESNEL = false;
  41906. _this.REFRACTIONFRESNEL = false;
  41907. _this.EMISSIVEFRESNEL = false;
  41908. _this.FRESNEL = false;
  41909. _this.NORMAL = false;
  41910. _this.UV1 = false;
  41911. _this.UV2 = false;
  41912. _this.VERTEXCOLOR = false;
  41913. _this.VERTEXALPHA = false;
  41914. _this.NUM_BONE_INFLUENCERS = 0;
  41915. _this.BonesPerMesh = 0;
  41916. _this.INSTANCES = false;
  41917. _this.GLOSSINESS = false;
  41918. _this.ROUGHNESS = false;
  41919. _this.EMISSIVEASILLUMINATION = false;
  41920. _this.LINKEMISSIVEWITHDIFFUSE = false;
  41921. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  41922. _this.LIGHTMAP = false;
  41923. _this.LIGHTMAPDIRECTUV = 0;
  41924. _this.OBJECTSPACE_NORMALMAP = false;
  41925. _this.USELIGHTMAPASSHADOWMAP = false;
  41926. _this.REFLECTIONMAP_3D = false;
  41927. _this.REFLECTIONMAP_SPHERICAL = false;
  41928. _this.REFLECTIONMAP_PLANAR = false;
  41929. _this.REFLECTIONMAP_CUBIC = false;
  41930. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41931. _this.REFLECTIONMAP_PROJECTION = false;
  41932. _this.REFLECTIONMAP_SKYBOX = false;
  41933. _this.REFLECTIONMAP_EXPLICIT = false;
  41934. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41935. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41936. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41937. _this.INVERTCUBICMAP = false;
  41938. _this.LOGARITHMICDEPTH = false;
  41939. _this.REFRACTION = false;
  41940. _this.REFRACTIONMAP_3D = false;
  41941. _this.REFLECTIONOVERALPHA = false;
  41942. _this.TWOSIDEDLIGHTING = false;
  41943. _this.SHADOWFLOAT = false;
  41944. _this.MORPHTARGETS = false;
  41945. _this.MORPHTARGETS_NORMAL = false;
  41946. _this.MORPHTARGETS_TANGENT = false;
  41947. _this.NUM_MORPH_INFLUENCERS = 0;
  41948. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  41949. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  41950. _this.IMAGEPROCESSING = false;
  41951. _this.VIGNETTE = false;
  41952. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  41953. _this.VIGNETTEBLENDMODEOPAQUE = false;
  41954. _this.TONEMAPPING = false;
  41955. _this.CONTRAST = false;
  41956. _this.COLORCURVES = false;
  41957. _this.COLORGRADING = false;
  41958. _this.COLORGRADING3D = false;
  41959. _this.SAMPLER3DGREENDEPTH = false;
  41960. _this.SAMPLER3DBGRMAP = false;
  41961. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  41962. /**
  41963. * If the reflection texture on this material is in linear color space
  41964. * @hidden
  41965. */
  41966. _this.IS_REFLECTION_LINEAR = false;
  41967. /**
  41968. * If the refraction texture on this material is in linear color space
  41969. * @hidden
  41970. */
  41971. _this.IS_REFRACTION_LINEAR = false;
  41972. _this.EXPOSURE = false;
  41973. _this.rebuild();
  41974. return _this;
  41975. }
  41976. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  41977. var modes = [
  41978. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  41979. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  41980. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  41981. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  41982. ];
  41983. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  41984. var mode = modes_1[_i];
  41985. this[mode] = (mode === modeToEnable);
  41986. }
  41987. };
  41988. return StandardMaterialDefines;
  41989. }(BABYLON.MaterialDefines));
  41990. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  41991. var StandardMaterial = /** @class */ (function (_super) {
  41992. __extends(StandardMaterial, _super);
  41993. function StandardMaterial(name, scene) {
  41994. var _this = _super.call(this, name, scene) || this;
  41995. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41996. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  41997. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  41998. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41999. _this.specularPower = 64;
  42000. _this._useAlphaFromDiffuseTexture = false;
  42001. _this._useEmissiveAsIllumination = false;
  42002. _this._linkEmissiveWithDiffuse = false;
  42003. _this._useSpecularOverAlpha = false;
  42004. _this._useReflectionOverAlpha = false;
  42005. _this._disableLighting = false;
  42006. _this._useObjectSpaceNormalMap = false;
  42007. _this._useParallax = false;
  42008. _this._useParallaxOcclusion = false;
  42009. _this.parallaxScaleBias = 0.05;
  42010. _this._roughness = 0;
  42011. _this.indexOfRefraction = 0.98;
  42012. _this.invertRefractionY = true;
  42013. /**
  42014. * Defines the alpha limits in alpha test mode
  42015. */
  42016. _this.alphaCutOff = 0.4;
  42017. _this._useLightmapAsShadowmap = false;
  42018. _this._useReflectionFresnelFromSpecular = false;
  42019. _this._useGlossinessFromSpecularMapAlpha = false;
  42020. _this._maxSimultaneousLights = 4;
  42021. /**
  42022. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42023. */
  42024. _this._invertNormalMapX = false;
  42025. /**
  42026. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42027. */
  42028. _this._invertNormalMapY = false;
  42029. /**
  42030. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42031. */
  42032. _this._twoSidedLighting = false;
  42033. _this._renderTargets = new BABYLON.SmartArray(16);
  42034. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42035. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42036. // Setup the default processing configuration to the scene.
  42037. _this._attachImageProcessingConfiguration(null);
  42038. _this.getRenderTargetTextures = function () {
  42039. _this._renderTargets.reset();
  42040. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42041. _this._renderTargets.push(_this._reflectionTexture);
  42042. }
  42043. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42044. _this._renderTargets.push(_this._refractionTexture);
  42045. }
  42046. return _this._renderTargets;
  42047. };
  42048. return _this;
  42049. }
  42050. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42051. /**
  42052. * Gets the image processing configuration used either in this material.
  42053. */
  42054. get: function () {
  42055. return this._imageProcessingConfiguration;
  42056. },
  42057. /**
  42058. * Sets the Default image processing configuration used either in the this material.
  42059. *
  42060. * If sets to null, the scene one is in use.
  42061. */
  42062. set: function (value) {
  42063. this._attachImageProcessingConfiguration(value);
  42064. // Ensure the effect will be rebuilt.
  42065. this._markAllSubMeshesAsTexturesDirty();
  42066. },
  42067. enumerable: true,
  42068. configurable: true
  42069. });
  42070. /**
  42071. * Attaches a new image processing configuration to the Standard Material.
  42072. * @param configuration
  42073. */
  42074. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42075. var _this = this;
  42076. if (configuration === this._imageProcessingConfiguration) {
  42077. return;
  42078. }
  42079. // Detaches observer.
  42080. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42081. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42082. }
  42083. // Pick the scene configuration if needed.
  42084. if (!configuration) {
  42085. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42086. }
  42087. else {
  42088. this._imageProcessingConfiguration = configuration;
  42089. }
  42090. // Attaches observer.
  42091. if (this._imageProcessingConfiguration) {
  42092. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42093. _this._markAllSubMeshesAsImageProcessingDirty();
  42094. });
  42095. }
  42096. };
  42097. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42098. /**
  42099. * Gets wether the color curves effect is enabled.
  42100. */
  42101. get: function () {
  42102. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42103. },
  42104. /**
  42105. * Sets wether the color curves effect is enabled.
  42106. */
  42107. set: function (value) {
  42108. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42109. },
  42110. enumerable: true,
  42111. configurable: true
  42112. });
  42113. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42114. /**
  42115. * Gets wether the color grading effect is enabled.
  42116. */
  42117. get: function () {
  42118. return this.imageProcessingConfiguration.colorGradingEnabled;
  42119. },
  42120. /**
  42121. * Gets wether the color grading effect is enabled.
  42122. */
  42123. set: function (value) {
  42124. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42125. },
  42126. enumerable: true,
  42127. configurable: true
  42128. });
  42129. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42130. /**
  42131. * Gets wether tonemapping is enabled or not.
  42132. */
  42133. get: function () {
  42134. return this._imageProcessingConfiguration.toneMappingEnabled;
  42135. },
  42136. /**
  42137. * Sets wether tonemapping is enabled or not
  42138. */
  42139. set: function (value) {
  42140. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42141. },
  42142. enumerable: true,
  42143. configurable: true
  42144. });
  42145. ;
  42146. ;
  42147. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42148. /**
  42149. * The camera exposure used on this material.
  42150. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42151. * This corresponds to a photographic exposure.
  42152. */
  42153. get: function () {
  42154. return this._imageProcessingConfiguration.exposure;
  42155. },
  42156. /**
  42157. * The camera exposure used on this material.
  42158. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42159. * This corresponds to a photographic exposure.
  42160. */
  42161. set: function (value) {
  42162. this._imageProcessingConfiguration.exposure = value;
  42163. },
  42164. enumerable: true,
  42165. configurable: true
  42166. });
  42167. ;
  42168. ;
  42169. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42170. /**
  42171. * Gets The camera contrast used on this material.
  42172. */
  42173. get: function () {
  42174. return this._imageProcessingConfiguration.contrast;
  42175. },
  42176. /**
  42177. * Sets The camera contrast used on this material.
  42178. */
  42179. set: function (value) {
  42180. this._imageProcessingConfiguration.contrast = value;
  42181. },
  42182. enumerable: true,
  42183. configurable: true
  42184. });
  42185. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42186. /**
  42187. * Gets the Color Grading 2D Lookup Texture.
  42188. */
  42189. get: function () {
  42190. return this._imageProcessingConfiguration.colorGradingTexture;
  42191. },
  42192. /**
  42193. * Sets the Color Grading 2D Lookup Texture.
  42194. */
  42195. set: function (value) {
  42196. this._imageProcessingConfiguration.colorGradingTexture = value;
  42197. },
  42198. enumerable: true,
  42199. configurable: true
  42200. });
  42201. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42202. /**
  42203. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42204. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42205. * 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;
  42206. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42207. */
  42208. get: function () {
  42209. return this._imageProcessingConfiguration.colorCurves;
  42210. },
  42211. /**
  42212. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42213. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42214. * 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;
  42215. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42216. */
  42217. set: function (value) {
  42218. this._imageProcessingConfiguration.colorCurves = value;
  42219. },
  42220. enumerable: true,
  42221. configurable: true
  42222. });
  42223. StandardMaterial.prototype.getClassName = function () {
  42224. return "StandardMaterial";
  42225. };
  42226. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42227. get: function () {
  42228. return this._useLogarithmicDepth;
  42229. },
  42230. set: function (value) {
  42231. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42232. this._markAllSubMeshesAsMiscDirty();
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. StandardMaterial.prototype.needAlphaBlending = function () {
  42238. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42239. };
  42240. StandardMaterial.prototype.needAlphaTesting = function () {
  42241. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42242. };
  42243. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42244. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42245. };
  42246. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42247. return this._diffuseTexture;
  42248. };
  42249. /**
  42250. * Child classes can use it to update shaders
  42251. */
  42252. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42253. if (useInstances === void 0) { useInstances = false; }
  42254. if (subMesh.effect && this.isFrozen) {
  42255. if (this._wasPreviouslyReady && subMesh.effect) {
  42256. return true;
  42257. }
  42258. }
  42259. if (!subMesh._materialDefines) {
  42260. subMesh._materialDefines = new StandardMaterialDefines();
  42261. }
  42262. var scene = this.getScene();
  42263. var defines = subMesh._materialDefines;
  42264. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42265. if (defines._renderId === scene.getRenderId()) {
  42266. return true;
  42267. }
  42268. }
  42269. var engine = scene.getEngine();
  42270. // Lights
  42271. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42272. // Textures
  42273. if (defines._areTexturesDirty) {
  42274. defines._needUVs = false;
  42275. defines.MAINUV1 = false;
  42276. defines.MAINUV2 = false;
  42277. if (scene.texturesEnabled) {
  42278. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42279. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42280. return false;
  42281. }
  42282. else {
  42283. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42284. }
  42285. }
  42286. else {
  42287. defines.DIFFUSE = false;
  42288. }
  42289. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42290. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42291. return false;
  42292. }
  42293. else {
  42294. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42295. }
  42296. }
  42297. else {
  42298. defines.AMBIENT = false;
  42299. }
  42300. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42301. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42302. return false;
  42303. }
  42304. else {
  42305. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42306. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42307. }
  42308. }
  42309. else {
  42310. defines.OPACITY = false;
  42311. }
  42312. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42313. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42314. return false;
  42315. }
  42316. else {
  42317. defines._needNormals = true;
  42318. defines.REFLECTION = true;
  42319. defines.ROUGHNESS = (this._roughness > 0);
  42320. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42321. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42322. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42323. switch (this._reflectionTexture.coordinatesMode) {
  42324. case BABYLON.Texture.EXPLICIT_MODE:
  42325. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42326. break;
  42327. case BABYLON.Texture.PLANAR_MODE:
  42328. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42329. break;
  42330. case BABYLON.Texture.PROJECTION_MODE:
  42331. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42332. break;
  42333. case BABYLON.Texture.SKYBOX_MODE:
  42334. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42335. break;
  42336. case BABYLON.Texture.SPHERICAL_MODE:
  42337. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42338. break;
  42339. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42340. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42341. break;
  42342. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42343. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42344. break;
  42345. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42346. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42347. break;
  42348. case BABYLON.Texture.CUBIC_MODE:
  42349. case BABYLON.Texture.INVCUBIC_MODE:
  42350. default:
  42351. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42352. break;
  42353. }
  42354. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42355. }
  42356. }
  42357. else {
  42358. defines.REFLECTION = false;
  42359. }
  42360. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42361. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42362. return false;
  42363. }
  42364. else {
  42365. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42366. }
  42367. }
  42368. else {
  42369. defines.EMISSIVE = false;
  42370. }
  42371. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42372. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42373. return false;
  42374. }
  42375. else {
  42376. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42377. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42378. }
  42379. }
  42380. else {
  42381. defines.LIGHTMAP = false;
  42382. }
  42383. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42384. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42385. return false;
  42386. }
  42387. else {
  42388. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42389. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42390. }
  42391. }
  42392. else {
  42393. defines.SPECULAR = false;
  42394. }
  42395. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42396. // Bump texure can not be not blocking.
  42397. if (!this._bumpTexture.isReady()) {
  42398. return false;
  42399. }
  42400. else {
  42401. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42402. defines.PARALLAX = this._useParallax;
  42403. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42404. }
  42405. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42406. }
  42407. else {
  42408. defines.BUMP = false;
  42409. }
  42410. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42411. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42412. return false;
  42413. }
  42414. else {
  42415. defines._needUVs = true;
  42416. defines.REFRACTION = true;
  42417. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42418. }
  42419. }
  42420. else {
  42421. defines.REFRACTION = false;
  42422. }
  42423. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42424. }
  42425. else {
  42426. defines.DIFFUSE = false;
  42427. defines.AMBIENT = false;
  42428. defines.OPACITY = false;
  42429. defines.REFLECTION = false;
  42430. defines.EMISSIVE = false;
  42431. defines.LIGHTMAP = false;
  42432. defines.BUMP = false;
  42433. defines.REFRACTION = false;
  42434. }
  42435. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42436. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42437. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42438. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42439. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42440. }
  42441. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42442. if (!this._imageProcessingConfiguration.isReady()) {
  42443. return false;
  42444. }
  42445. this._imageProcessingConfiguration.prepareDefines(defines);
  42446. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42447. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42448. }
  42449. if (defines._areFresnelDirty) {
  42450. if (StandardMaterial.FresnelEnabled) {
  42451. // Fresnel
  42452. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42453. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42454. this._reflectionFresnelParameters) {
  42455. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42456. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42457. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42458. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42459. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42460. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42461. defines._needNormals = true;
  42462. defines.FRESNEL = true;
  42463. }
  42464. }
  42465. else {
  42466. defines.FRESNEL = false;
  42467. }
  42468. }
  42469. // Misc.
  42470. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42471. // Attribs
  42472. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42473. // Values that need to be evaluated on every frame
  42474. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42475. // Get correct effect
  42476. if (defines.isDirty) {
  42477. defines.markAsProcessed();
  42478. scene.resetCachedMaterial();
  42479. // Fallbacks
  42480. var fallbacks = new BABYLON.EffectFallbacks();
  42481. if (defines.REFLECTION) {
  42482. fallbacks.addFallback(0, "REFLECTION");
  42483. }
  42484. if (defines.SPECULAR) {
  42485. fallbacks.addFallback(0, "SPECULAR");
  42486. }
  42487. if (defines.BUMP) {
  42488. fallbacks.addFallback(0, "BUMP");
  42489. }
  42490. if (defines.PARALLAX) {
  42491. fallbacks.addFallback(1, "PARALLAX");
  42492. }
  42493. if (defines.PARALLAXOCCLUSION) {
  42494. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42495. }
  42496. if (defines.SPECULAROVERALPHA) {
  42497. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42498. }
  42499. if (defines.FOG) {
  42500. fallbacks.addFallback(1, "FOG");
  42501. }
  42502. if (defines.POINTSIZE) {
  42503. fallbacks.addFallback(0, "POINTSIZE");
  42504. }
  42505. if (defines.LOGARITHMICDEPTH) {
  42506. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42507. }
  42508. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42509. if (defines.SPECULARTERM) {
  42510. fallbacks.addFallback(0, "SPECULARTERM");
  42511. }
  42512. if (defines.DIFFUSEFRESNEL) {
  42513. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42514. }
  42515. if (defines.OPACITYFRESNEL) {
  42516. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42517. }
  42518. if (defines.REFLECTIONFRESNEL) {
  42519. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42520. }
  42521. if (defines.EMISSIVEFRESNEL) {
  42522. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42523. }
  42524. if (defines.FRESNEL) {
  42525. fallbacks.addFallback(4, "FRESNEL");
  42526. }
  42527. //Attributes
  42528. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42529. if (defines.NORMAL) {
  42530. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42531. }
  42532. if (defines.UV1) {
  42533. attribs.push(BABYLON.VertexBuffer.UVKind);
  42534. }
  42535. if (defines.UV2) {
  42536. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42537. }
  42538. if (defines.VERTEXCOLOR) {
  42539. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42540. }
  42541. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42542. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42543. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42544. var shaderName = "default";
  42545. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42546. "vFogInfos", "vFogColor", "pointSize",
  42547. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42548. "mBones",
  42549. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42550. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42551. "vReflectionPosition", "vReflectionSize",
  42552. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42553. ];
  42554. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42555. var uniformBuffers = ["Material", "Scene"];
  42556. if (BABYLON.ImageProcessingConfiguration) {
  42557. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42558. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42559. }
  42560. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42561. uniformsNames: uniforms,
  42562. uniformBuffersNames: uniformBuffers,
  42563. samplers: samplers,
  42564. defines: defines,
  42565. maxSimultaneousLights: this._maxSimultaneousLights
  42566. });
  42567. if (this.customShaderNameResolve) {
  42568. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42569. }
  42570. var join = defines.toString();
  42571. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42572. attributes: attribs,
  42573. uniformsNames: uniforms,
  42574. uniformBuffersNames: uniformBuffers,
  42575. samplers: samplers,
  42576. defines: join,
  42577. fallbacks: fallbacks,
  42578. onCompiled: this.onCompiled,
  42579. onError: this.onError,
  42580. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42581. }, engine), defines);
  42582. this.buildUniformLayout();
  42583. }
  42584. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42585. return false;
  42586. }
  42587. defines._renderId = scene.getRenderId();
  42588. this._wasPreviouslyReady = true;
  42589. return true;
  42590. };
  42591. StandardMaterial.prototype.buildUniformLayout = function () {
  42592. // Order is important !
  42593. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42594. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42595. this._uniformBuffer.addUniform("opacityParts", 4);
  42596. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42597. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42598. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42599. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42600. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42601. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42602. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42603. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42604. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42605. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42606. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42607. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42608. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42609. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42610. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42611. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42612. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42613. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42614. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42615. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42616. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42617. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42618. this._uniformBuffer.addUniform("specularMatrix", 16);
  42619. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42620. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42621. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42622. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42623. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42624. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42625. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42626. this._uniformBuffer.addUniform("pointSize", 1);
  42627. this._uniformBuffer.create();
  42628. };
  42629. StandardMaterial.prototype.unbind = function () {
  42630. if (this._activeEffect) {
  42631. var needFlag = false;
  42632. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42633. this._activeEffect.setTexture("reflection2DSampler", null);
  42634. needFlag = true;
  42635. }
  42636. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42637. this._activeEffect.setTexture("refraction2DSampler", null);
  42638. needFlag = true;
  42639. }
  42640. if (needFlag) {
  42641. this._markAllSubMeshesAsTexturesDirty();
  42642. }
  42643. }
  42644. _super.prototype.unbind.call(this);
  42645. };
  42646. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42647. var scene = this.getScene();
  42648. var defines = subMesh._materialDefines;
  42649. if (!defines) {
  42650. return;
  42651. }
  42652. var effect = subMesh.effect;
  42653. if (!effect) {
  42654. return;
  42655. }
  42656. this._activeEffect = effect;
  42657. // Matrices
  42658. this.bindOnlyWorldMatrix(world);
  42659. // Normal Matrix
  42660. if (defines.OBJECTSPACE_NORMALMAP) {
  42661. world.toNormalMatrix(this._normalMatrix);
  42662. this.bindOnlyNormalMatrix(this._normalMatrix);
  42663. }
  42664. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42665. // Bones
  42666. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42667. if (mustRebind) {
  42668. this._uniformBuffer.bindToEffect(effect, "Material");
  42669. this.bindViewProjection(effect);
  42670. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42671. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42672. // Fresnel
  42673. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42674. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42675. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42676. }
  42677. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42678. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42679. }
  42680. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42681. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42682. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42683. }
  42684. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42685. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42686. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42687. }
  42688. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42689. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42690. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42691. }
  42692. }
  42693. // Textures
  42694. if (scene.texturesEnabled) {
  42695. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42696. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42697. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42698. if (this._diffuseTexture.hasAlpha) {
  42699. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42700. }
  42701. }
  42702. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42703. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42704. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42705. }
  42706. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42707. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42708. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42709. }
  42710. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42711. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42712. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42713. if (this._reflectionTexture.boundingBoxSize) {
  42714. var cubeTexture = this._reflectionTexture;
  42715. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42716. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42717. }
  42718. }
  42719. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42720. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42721. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42722. }
  42723. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42724. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42725. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42726. }
  42727. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42728. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42729. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42730. }
  42731. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42732. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42733. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42734. if (scene._mirroredCameraPosition) {
  42735. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42736. }
  42737. else {
  42738. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42739. }
  42740. }
  42741. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42742. var depth = 1.0;
  42743. if (!this._refractionTexture.isCube) {
  42744. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42745. if (this._refractionTexture.depth) {
  42746. depth = this._refractionTexture.depth;
  42747. }
  42748. }
  42749. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42750. }
  42751. }
  42752. // Point size
  42753. if (this.pointsCloud) {
  42754. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42755. }
  42756. if (defines.SPECULARTERM) {
  42757. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42758. }
  42759. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42760. // Diffuse
  42761. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42762. }
  42763. // Textures
  42764. if (scene.texturesEnabled) {
  42765. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42766. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42767. }
  42768. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42769. effect.setTexture("ambientSampler", this._ambientTexture);
  42770. }
  42771. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42772. effect.setTexture("opacitySampler", this._opacityTexture);
  42773. }
  42774. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42775. if (this._reflectionTexture.isCube) {
  42776. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42777. }
  42778. else {
  42779. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42780. }
  42781. }
  42782. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42783. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42784. }
  42785. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42786. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42787. }
  42788. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42789. effect.setTexture("specularSampler", this._specularTexture);
  42790. }
  42791. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42792. effect.setTexture("bumpSampler", this._bumpTexture);
  42793. }
  42794. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42795. var depth = 1.0;
  42796. if (this._refractionTexture.isCube) {
  42797. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42798. }
  42799. else {
  42800. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42801. }
  42802. }
  42803. }
  42804. // Clip plane
  42805. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42806. // Colors
  42807. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42808. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42809. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42810. }
  42811. if (mustRebind || !this.isFrozen) {
  42812. // Lights
  42813. if (scene.lightsEnabled && !this._disableLighting) {
  42814. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42815. }
  42816. // View
  42817. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42818. this.bindView(effect);
  42819. }
  42820. // Fog
  42821. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42822. // Morph targets
  42823. if (defines.NUM_MORPH_INFLUENCERS) {
  42824. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42825. }
  42826. // Log. depth
  42827. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42828. // image processing
  42829. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42830. this._imageProcessingConfiguration.bind(this._activeEffect);
  42831. }
  42832. }
  42833. this._uniformBuffer.update();
  42834. this._afterBind(mesh, this._activeEffect);
  42835. };
  42836. StandardMaterial.prototype.getAnimatables = function () {
  42837. var results = [];
  42838. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42839. results.push(this._diffuseTexture);
  42840. }
  42841. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42842. results.push(this._ambientTexture);
  42843. }
  42844. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42845. results.push(this._opacityTexture);
  42846. }
  42847. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42848. results.push(this._reflectionTexture);
  42849. }
  42850. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42851. results.push(this._emissiveTexture);
  42852. }
  42853. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42854. results.push(this._specularTexture);
  42855. }
  42856. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42857. results.push(this._bumpTexture);
  42858. }
  42859. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42860. results.push(this._lightmapTexture);
  42861. }
  42862. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42863. results.push(this._refractionTexture);
  42864. }
  42865. return results;
  42866. };
  42867. StandardMaterial.prototype.getActiveTextures = function () {
  42868. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42869. if (this._diffuseTexture) {
  42870. activeTextures.push(this._diffuseTexture);
  42871. }
  42872. if (this._ambientTexture) {
  42873. activeTextures.push(this._ambientTexture);
  42874. }
  42875. if (this._opacityTexture) {
  42876. activeTextures.push(this._opacityTexture);
  42877. }
  42878. if (this._reflectionTexture) {
  42879. activeTextures.push(this._reflectionTexture);
  42880. }
  42881. if (this._emissiveTexture) {
  42882. activeTextures.push(this._emissiveTexture);
  42883. }
  42884. if (this._specularTexture) {
  42885. activeTextures.push(this._specularTexture);
  42886. }
  42887. if (this._bumpTexture) {
  42888. activeTextures.push(this._bumpTexture);
  42889. }
  42890. if (this._lightmapTexture) {
  42891. activeTextures.push(this._lightmapTexture);
  42892. }
  42893. if (this._refractionTexture) {
  42894. activeTextures.push(this._refractionTexture);
  42895. }
  42896. return activeTextures;
  42897. };
  42898. StandardMaterial.prototype.hasTexture = function (texture) {
  42899. if (_super.prototype.hasTexture.call(this, texture)) {
  42900. return true;
  42901. }
  42902. if (this._diffuseTexture === texture) {
  42903. return true;
  42904. }
  42905. if (this._ambientTexture === texture) {
  42906. return true;
  42907. }
  42908. if (this._opacityTexture === texture) {
  42909. return true;
  42910. }
  42911. if (this._reflectionTexture === texture) {
  42912. return true;
  42913. }
  42914. if (this._emissiveTexture === texture) {
  42915. return true;
  42916. }
  42917. if (this._specularTexture === texture) {
  42918. return true;
  42919. }
  42920. if (this._bumpTexture === texture) {
  42921. return true;
  42922. }
  42923. if (this._lightmapTexture === texture) {
  42924. return true;
  42925. }
  42926. if (this._refractionTexture === texture) {
  42927. return true;
  42928. }
  42929. return false;
  42930. };
  42931. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42932. if (forceDisposeTextures) {
  42933. if (this._diffuseTexture) {
  42934. this._diffuseTexture.dispose();
  42935. }
  42936. if (this._ambientTexture) {
  42937. this._ambientTexture.dispose();
  42938. }
  42939. if (this._opacityTexture) {
  42940. this._opacityTexture.dispose();
  42941. }
  42942. if (this._reflectionTexture) {
  42943. this._reflectionTexture.dispose();
  42944. }
  42945. if (this._emissiveTexture) {
  42946. this._emissiveTexture.dispose();
  42947. }
  42948. if (this._specularTexture) {
  42949. this._specularTexture.dispose();
  42950. }
  42951. if (this._bumpTexture) {
  42952. this._bumpTexture.dispose();
  42953. }
  42954. if (this._lightmapTexture) {
  42955. this._lightmapTexture.dispose();
  42956. }
  42957. if (this._refractionTexture) {
  42958. this._refractionTexture.dispose();
  42959. }
  42960. }
  42961. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42962. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42963. }
  42964. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42965. };
  42966. StandardMaterial.prototype.clone = function (name) {
  42967. var _this = this;
  42968. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  42969. result.name = name;
  42970. result.id = name;
  42971. return result;
  42972. };
  42973. StandardMaterial.prototype.serialize = function () {
  42974. return BABYLON.SerializationHelper.Serialize(this);
  42975. };
  42976. // Statics
  42977. StandardMaterial.Parse = function (source, scene, rootUrl) {
  42978. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  42979. };
  42980. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  42981. get: function () {
  42982. return StandardMaterial._DiffuseTextureEnabled;
  42983. },
  42984. set: function (value) {
  42985. if (StandardMaterial._DiffuseTextureEnabled === value) {
  42986. return;
  42987. }
  42988. StandardMaterial._DiffuseTextureEnabled = value;
  42989. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  42990. },
  42991. enumerable: true,
  42992. configurable: true
  42993. });
  42994. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  42995. get: function () {
  42996. return StandardMaterial._AmbientTextureEnabled;
  42997. },
  42998. set: function (value) {
  42999. if (StandardMaterial._AmbientTextureEnabled === value) {
  43000. return;
  43001. }
  43002. StandardMaterial._AmbientTextureEnabled = value;
  43003. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43004. },
  43005. enumerable: true,
  43006. configurable: true
  43007. });
  43008. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43009. get: function () {
  43010. return StandardMaterial._OpacityTextureEnabled;
  43011. },
  43012. set: function (value) {
  43013. if (StandardMaterial._OpacityTextureEnabled === value) {
  43014. return;
  43015. }
  43016. StandardMaterial._OpacityTextureEnabled = value;
  43017. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43018. },
  43019. enumerable: true,
  43020. configurable: true
  43021. });
  43022. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43023. get: function () {
  43024. return StandardMaterial._ReflectionTextureEnabled;
  43025. },
  43026. set: function (value) {
  43027. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43028. return;
  43029. }
  43030. StandardMaterial._ReflectionTextureEnabled = value;
  43031. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43032. },
  43033. enumerable: true,
  43034. configurable: true
  43035. });
  43036. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43037. get: function () {
  43038. return StandardMaterial._EmissiveTextureEnabled;
  43039. },
  43040. set: function (value) {
  43041. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43042. return;
  43043. }
  43044. StandardMaterial._EmissiveTextureEnabled = value;
  43045. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43046. },
  43047. enumerable: true,
  43048. configurable: true
  43049. });
  43050. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43051. get: function () {
  43052. return StandardMaterial._SpecularTextureEnabled;
  43053. },
  43054. set: function (value) {
  43055. if (StandardMaterial._SpecularTextureEnabled === value) {
  43056. return;
  43057. }
  43058. StandardMaterial._SpecularTextureEnabled = value;
  43059. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43060. },
  43061. enumerable: true,
  43062. configurable: true
  43063. });
  43064. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43065. get: function () {
  43066. return StandardMaterial._BumpTextureEnabled;
  43067. },
  43068. set: function (value) {
  43069. if (StandardMaterial._BumpTextureEnabled === value) {
  43070. return;
  43071. }
  43072. StandardMaterial._BumpTextureEnabled = value;
  43073. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43074. },
  43075. enumerable: true,
  43076. configurable: true
  43077. });
  43078. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43079. get: function () {
  43080. return StandardMaterial._LightmapTextureEnabled;
  43081. },
  43082. set: function (value) {
  43083. if (StandardMaterial._LightmapTextureEnabled === value) {
  43084. return;
  43085. }
  43086. StandardMaterial._LightmapTextureEnabled = value;
  43087. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43088. },
  43089. enumerable: true,
  43090. configurable: true
  43091. });
  43092. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43093. get: function () {
  43094. return StandardMaterial._RefractionTextureEnabled;
  43095. },
  43096. set: function (value) {
  43097. if (StandardMaterial._RefractionTextureEnabled === value) {
  43098. return;
  43099. }
  43100. StandardMaterial._RefractionTextureEnabled = value;
  43101. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43102. },
  43103. enumerable: true,
  43104. configurable: true
  43105. });
  43106. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43107. get: function () {
  43108. return StandardMaterial._ColorGradingTextureEnabled;
  43109. },
  43110. set: function (value) {
  43111. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43112. return;
  43113. }
  43114. StandardMaterial._ColorGradingTextureEnabled = value;
  43115. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43116. },
  43117. enumerable: true,
  43118. configurable: true
  43119. });
  43120. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43121. get: function () {
  43122. return StandardMaterial._FresnelEnabled;
  43123. },
  43124. set: function (value) {
  43125. if (StandardMaterial._FresnelEnabled === value) {
  43126. return;
  43127. }
  43128. StandardMaterial._FresnelEnabled = value;
  43129. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43130. },
  43131. enumerable: true,
  43132. configurable: true
  43133. });
  43134. // Flags used to enable or disable a type of texture for all Standard Materials
  43135. StandardMaterial._DiffuseTextureEnabled = true;
  43136. StandardMaterial._AmbientTextureEnabled = true;
  43137. StandardMaterial._OpacityTextureEnabled = true;
  43138. StandardMaterial._ReflectionTextureEnabled = true;
  43139. StandardMaterial._EmissiveTextureEnabled = true;
  43140. StandardMaterial._SpecularTextureEnabled = true;
  43141. StandardMaterial._BumpTextureEnabled = true;
  43142. StandardMaterial._LightmapTextureEnabled = true;
  43143. StandardMaterial._RefractionTextureEnabled = true;
  43144. StandardMaterial._ColorGradingTextureEnabled = true;
  43145. StandardMaterial._FresnelEnabled = true;
  43146. __decorate([
  43147. BABYLON.serializeAsTexture("diffuseTexture")
  43148. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43149. __decorate([
  43150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43151. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43152. __decorate([
  43153. BABYLON.serializeAsTexture("ambientTexture")
  43154. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43155. __decorate([
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43158. __decorate([
  43159. BABYLON.serializeAsTexture("opacityTexture")
  43160. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43161. __decorate([
  43162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43163. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43164. __decorate([
  43165. BABYLON.serializeAsTexture("reflectionTexture")
  43166. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43167. __decorate([
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43169. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43170. __decorate([
  43171. BABYLON.serializeAsTexture("emissiveTexture")
  43172. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43173. __decorate([
  43174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43175. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43176. __decorate([
  43177. BABYLON.serializeAsTexture("specularTexture")
  43178. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43179. __decorate([
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43181. ], StandardMaterial.prototype, "specularTexture", void 0);
  43182. __decorate([
  43183. BABYLON.serializeAsTexture("bumpTexture")
  43184. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43185. __decorate([
  43186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43187. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43188. __decorate([
  43189. BABYLON.serializeAsTexture("lightmapTexture")
  43190. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43191. __decorate([
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43193. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43194. __decorate([
  43195. BABYLON.serializeAsTexture("refractionTexture")
  43196. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43197. __decorate([
  43198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43199. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43200. __decorate([
  43201. BABYLON.serializeAsColor3("ambient")
  43202. ], StandardMaterial.prototype, "ambientColor", void 0);
  43203. __decorate([
  43204. BABYLON.serializeAsColor3("diffuse")
  43205. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43206. __decorate([
  43207. BABYLON.serializeAsColor3("specular")
  43208. ], StandardMaterial.prototype, "specularColor", void 0);
  43209. __decorate([
  43210. BABYLON.serializeAsColor3("emissive")
  43211. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43212. __decorate([
  43213. BABYLON.serialize()
  43214. ], StandardMaterial.prototype, "specularPower", void 0);
  43215. __decorate([
  43216. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43217. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43218. __decorate([
  43219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43220. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43221. __decorate([
  43222. BABYLON.serialize("useEmissiveAsIllumination")
  43223. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43224. __decorate([
  43225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43226. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43227. __decorate([
  43228. BABYLON.serialize("linkEmissiveWithDiffuse")
  43229. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43230. __decorate([
  43231. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43232. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43233. __decorate([
  43234. BABYLON.serialize("useSpecularOverAlpha")
  43235. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43236. __decorate([
  43237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43238. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43239. __decorate([
  43240. BABYLON.serialize("useReflectionOverAlpha")
  43241. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43242. __decorate([
  43243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43244. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43245. __decorate([
  43246. BABYLON.serialize("disableLighting")
  43247. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43248. __decorate([
  43249. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43250. ], StandardMaterial.prototype, "disableLighting", void 0);
  43251. __decorate([
  43252. BABYLON.serialize("useObjectSpaceNormalMap")
  43253. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43254. __decorate([
  43255. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43256. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43257. __decorate([
  43258. BABYLON.serialize("useParallax")
  43259. ], StandardMaterial.prototype, "_useParallax", void 0);
  43260. __decorate([
  43261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43262. ], StandardMaterial.prototype, "useParallax", void 0);
  43263. __decorate([
  43264. BABYLON.serialize("useParallaxOcclusion")
  43265. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43266. __decorate([
  43267. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43268. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43269. __decorate([
  43270. BABYLON.serialize()
  43271. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43272. __decorate([
  43273. BABYLON.serialize("roughness")
  43274. ], StandardMaterial.prototype, "_roughness", void 0);
  43275. __decorate([
  43276. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43277. ], StandardMaterial.prototype, "roughness", void 0);
  43278. __decorate([
  43279. BABYLON.serialize()
  43280. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43281. __decorate([
  43282. BABYLON.serialize()
  43283. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43284. __decorate([
  43285. BABYLON.serialize()
  43286. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43287. __decorate([
  43288. BABYLON.serialize("useLightmapAsShadowmap")
  43289. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43290. __decorate([
  43291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43292. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43293. __decorate([
  43294. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43295. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43296. __decorate([
  43297. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43298. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43299. __decorate([
  43300. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43301. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43302. __decorate([
  43303. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43304. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43305. __decorate([
  43306. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43307. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43308. __decorate([
  43309. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43310. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43311. __decorate([
  43312. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43313. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43314. __decorate([
  43315. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43316. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43317. __decorate([
  43318. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43319. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43320. __decorate([
  43321. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43322. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43323. __decorate([
  43324. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43325. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43326. __decorate([
  43327. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43328. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43329. __decorate([
  43330. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43331. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43332. __decorate([
  43333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43334. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43335. __decorate([
  43336. BABYLON.serialize("maxSimultaneousLights")
  43337. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43338. __decorate([
  43339. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43340. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43341. __decorate([
  43342. BABYLON.serialize("invertNormalMapX")
  43343. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43344. __decorate([
  43345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43346. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43347. __decorate([
  43348. BABYLON.serialize("invertNormalMapY")
  43349. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43350. __decorate([
  43351. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43352. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43353. __decorate([
  43354. BABYLON.serialize("twoSidedLighting")
  43355. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43356. __decorate([
  43357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43358. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43359. __decorate([
  43360. BABYLON.serialize()
  43361. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43362. return StandardMaterial;
  43363. }(BABYLON.PushMaterial));
  43364. BABYLON.StandardMaterial = StandardMaterial;
  43365. })(BABYLON || (BABYLON = {}));
  43366. //# sourceMappingURL=babylon.standardMaterial.js.map
  43367. var BABYLON;
  43368. (function (BABYLON) {
  43369. /**
  43370. * Manages the defines for the PBR Material.
  43371. * @hiddenChildren
  43372. */
  43373. var PBRMaterialDefines = /** @class */ (function (_super) {
  43374. __extends(PBRMaterialDefines, _super);
  43375. /**
  43376. * Initializes the PBR Material defines.
  43377. */
  43378. function PBRMaterialDefines() {
  43379. var _this = _super.call(this) || this;
  43380. _this.PBR = true;
  43381. _this.MAINUV1 = false;
  43382. _this.MAINUV2 = false;
  43383. _this.UV1 = false;
  43384. _this.UV2 = false;
  43385. _this.ALBEDO = false;
  43386. _this.ALBEDODIRECTUV = 0;
  43387. _this.VERTEXCOLOR = false;
  43388. _this.AMBIENT = false;
  43389. _this.AMBIENTDIRECTUV = 0;
  43390. _this.AMBIENTINGRAYSCALE = false;
  43391. _this.OPACITY = false;
  43392. _this.VERTEXALPHA = false;
  43393. _this.OPACITYDIRECTUV = 0;
  43394. _this.OPACITYRGB = false;
  43395. _this.ALPHATEST = false;
  43396. _this.DEPTHPREPASS = false;
  43397. _this.ALPHABLEND = false;
  43398. _this.ALPHAFROMALBEDO = false;
  43399. _this.ALPHATESTVALUE = "0.5";
  43400. _this.SPECULAROVERALPHA = false;
  43401. _this.RADIANCEOVERALPHA = false;
  43402. _this.ALPHAFRESNEL = false;
  43403. _this.LINEARALPHAFRESNEL = false;
  43404. _this.PREMULTIPLYALPHA = false;
  43405. _this.EMISSIVE = false;
  43406. _this.EMISSIVEDIRECTUV = 0;
  43407. _this.REFLECTIVITY = false;
  43408. _this.REFLECTIVITYDIRECTUV = 0;
  43409. _this.SPECULARTERM = false;
  43410. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43411. _this.MICROSURFACEAUTOMATIC = false;
  43412. _this.LODBASEDMICROSFURACE = false;
  43413. _this.MICROSURFACEMAP = false;
  43414. _this.MICROSURFACEMAPDIRECTUV = 0;
  43415. _this.METALLICWORKFLOW = false;
  43416. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43417. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43418. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43419. _this.AOSTOREINMETALMAPRED = false;
  43420. _this.ENVIRONMENTBRDF = false;
  43421. _this.NORMAL = false;
  43422. _this.TANGENT = false;
  43423. _this.BUMP = false;
  43424. _this.BUMPDIRECTUV = 0;
  43425. _this.OBJECTSPACE_NORMALMAP = false;
  43426. _this.PARALLAX = false;
  43427. _this.PARALLAXOCCLUSION = false;
  43428. _this.NORMALXYSCALE = true;
  43429. _this.LIGHTMAP = false;
  43430. _this.LIGHTMAPDIRECTUV = 0;
  43431. _this.USELIGHTMAPASSHADOWMAP = false;
  43432. _this.GAMMALIGHTMAP = false;
  43433. _this.REFLECTION = false;
  43434. _this.REFLECTIONMAP_3D = false;
  43435. _this.REFLECTIONMAP_SPHERICAL = false;
  43436. _this.REFLECTIONMAP_PLANAR = false;
  43437. _this.REFLECTIONMAP_CUBIC = false;
  43438. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43439. _this.REFLECTIONMAP_PROJECTION = false;
  43440. _this.REFLECTIONMAP_SKYBOX = false;
  43441. _this.REFLECTIONMAP_EXPLICIT = false;
  43442. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43443. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43444. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43445. _this.INVERTCUBICMAP = false;
  43446. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43447. _this.USESPHERICALINVERTEX = false;
  43448. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43449. _this.LODINREFLECTIONALPHA = false;
  43450. _this.GAMMAREFLECTION = false;
  43451. _this.RGBDREFLECTION = false;
  43452. _this.RADIANCEOCCLUSION = false;
  43453. _this.HORIZONOCCLUSION = false;
  43454. _this.REFRACTION = false;
  43455. _this.REFRACTIONMAP_3D = false;
  43456. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43457. _this.LODINREFRACTIONALPHA = false;
  43458. _this.GAMMAREFRACTION = false;
  43459. _this.RGBDREFRACTION = false;
  43460. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43461. _this.INSTANCES = false;
  43462. _this.NUM_BONE_INFLUENCERS = 0;
  43463. _this.BonesPerMesh = 0;
  43464. _this.NONUNIFORMSCALING = false;
  43465. _this.MORPHTARGETS = false;
  43466. _this.MORPHTARGETS_NORMAL = false;
  43467. _this.MORPHTARGETS_TANGENT = false;
  43468. _this.NUM_MORPH_INFLUENCERS = 0;
  43469. _this.IMAGEPROCESSING = false;
  43470. _this.VIGNETTE = false;
  43471. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43472. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43473. _this.TONEMAPPING = false;
  43474. _this.CONTRAST = false;
  43475. _this.COLORCURVES = false;
  43476. _this.COLORGRADING = false;
  43477. _this.COLORGRADING3D = false;
  43478. _this.SAMPLER3DGREENDEPTH = false;
  43479. _this.SAMPLER3DBGRMAP = false;
  43480. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43481. _this.EXPOSURE = false;
  43482. _this.USEPHYSICALLIGHTFALLOFF = false;
  43483. _this.TWOSIDEDLIGHTING = false;
  43484. _this.SHADOWFLOAT = false;
  43485. _this.CLIPPLANE = false;
  43486. _this.POINTSIZE = false;
  43487. _this.FOG = false;
  43488. _this.LOGARITHMICDEPTH = false;
  43489. _this.FORCENORMALFORWARD = false;
  43490. _this.SPECULARAA = false;
  43491. _this.UNLIT = false;
  43492. _this.rebuild();
  43493. return _this;
  43494. }
  43495. /**
  43496. * Resets the PBR Material defines.
  43497. */
  43498. PBRMaterialDefines.prototype.reset = function () {
  43499. _super.prototype.reset.call(this);
  43500. this.ALPHATESTVALUE = "0.5";
  43501. this.PBR = true;
  43502. };
  43503. return PBRMaterialDefines;
  43504. }(BABYLON.MaterialDefines));
  43505. /**
  43506. * The Physically based material base class of BJS.
  43507. *
  43508. * This offers the main features of a standard PBR material.
  43509. * For more information, please refer to the documentation :
  43510. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43511. */
  43512. var PBRBaseMaterial = /** @class */ (function (_super) {
  43513. __extends(PBRBaseMaterial, _super);
  43514. /**
  43515. * Instantiates a new PBRMaterial instance.
  43516. *
  43517. * @param name The material name
  43518. * @param scene The scene the material will be use in.
  43519. */
  43520. function PBRBaseMaterial(name, scene) {
  43521. var _this = _super.call(this, name, scene) || this;
  43522. /**
  43523. * Intensity of the direct lights e.g. the four lights available in your scene.
  43524. * This impacts both the direct diffuse and specular highlights.
  43525. */
  43526. _this._directIntensity = 1.0;
  43527. /**
  43528. * Intensity of the emissive part of the material.
  43529. * This helps controlling the emissive effect without modifying the emissive color.
  43530. */
  43531. _this._emissiveIntensity = 1.0;
  43532. /**
  43533. * Intensity of the environment e.g. how much the environment will light the object
  43534. * either through harmonics for rough material or through the refelction for shiny ones.
  43535. */
  43536. _this._environmentIntensity = 1.0;
  43537. /**
  43538. * This is a special control allowing the reduction of the specular highlights coming from the
  43539. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43540. */
  43541. _this._specularIntensity = 1.0;
  43542. /**
  43543. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43544. */
  43545. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43546. /**
  43547. * Debug Control allowing disabling the bump map on this material.
  43548. */
  43549. _this._disableBumpMap = false;
  43550. /**
  43551. * AKA Occlusion Texture Intensity in other nomenclature.
  43552. */
  43553. _this._ambientTextureStrength = 1.0;
  43554. /**
  43555. * The color of a material in ambient lighting.
  43556. */
  43557. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43558. /**
  43559. * AKA Diffuse Color in other nomenclature.
  43560. */
  43561. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43562. /**
  43563. * AKA Specular Color in other nomenclature.
  43564. */
  43565. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43566. /**
  43567. * The color applied when light is reflected from a material.
  43568. */
  43569. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43570. /**
  43571. * The color applied when light is emitted from a material.
  43572. */
  43573. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43574. /**
  43575. * AKA Glossiness in other nomenclature.
  43576. */
  43577. _this._microSurface = 0.9;
  43578. /**
  43579. * source material index of refraction (IOR)' / 'destination material IOR.
  43580. */
  43581. _this._indexOfRefraction = 0.66;
  43582. /**
  43583. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43584. */
  43585. _this._invertRefractionY = false;
  43586. /**
  43587. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43588. * Materials half opaque for instance using refraction could benefit from this control.
  43589. */
  43590. _this._linkRefractionWithTransparency = false;
  43591. /**
  43592. * Specifies that the material will use the light map as a show map.
  43593. */
  43594. _this._useLightmapAsShadowmap = false;
  43595. /**
  43596. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43597. * makes the reflect vector face the model (under horizon).
  43598. */
  43599. _this._useHorizonOcclusion = true;
  43600. /**
  43601. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43602. * too much the area relying on ambient texture to define their ambient occlusion.
  43603. */
  43604. _this._useRadianceOcclusion = true;
  43605. /**
  43606. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43607. */
  43608. _this._useAlphaFromAlbedoTexture = false;
  43609. /**
  43610. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43611. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43612. */
  43613. _this._useSpecularOverAlpha = true;
  43614. /**
  43615. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43616. */
  43617. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43618. /**
  43619. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43620. */
  43621. _this._useRoughnessFromMetallicTextureAlpha = true;
  43622. /**
  43623. * Specifies if the metallic texture contains the roughness information in its green channel.
  43624. */
  43625. _this._useRoughnessFromMetallicTextureGreen = false;
  43626. /**
  43627. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43628. */
  43629. _this._useMetallnessFromMetallicTextureBlue = false;
  43630. /**
  43631. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43632. */
  43633. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43634. /**
  43635. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43636. */
  43637. _this._useAmbientInGrayScale = false;
  43638. /**
  43639. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43640. * The material will try to infer what glossiness each pixel should be.
  43641. */
  43642. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43643. /**
  43644. * BJS is using an harcoded light falloff based on a manually sets up range.
  43645. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43646. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43647. */
  43648. _this._usePhysicalLightFalloff = true;
  43649. /**
  43650. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43651. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43652. */
  43653. _this._useRadianceOverAlpha = true;
  43654. /**
  43655. * Allows using an object space normal map (instead of tangent space).
  43656. */
  43657. _this._useObjectSpaceNormalMap = false;
  43658. /**
  43659. * Allows using the bump map in parallax mode.
  43660. */
  43661. _this._useParallax = false;
  43662. /**
  43663. * Allows using the bump map in parallax occlusion mode.
  43664. */
  43665. _this._useParallaxOcclusion = false;
  43666. /**
  43667. * Controls the scale bias of the parallax mode.
  43668. */
  43669. _this._parallaxScaleBias = 0.05;
  43670. /**
  43671. * If sets to true, disables all the lights affecting the material.
  43672. */
  43673. _this._disableLighting = false;
  43674. /**
  43675. * Number of Simultaneous lights allowed on the material.
  43676. */
  43677. _this._maxSimultaneousLights = 4;
  43678. /**
  43679. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43680. */
  43681. _this._invertNormalMapX = false;
  43682. /**
  43683. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43684. */
  43685. _this._invertNormalMapY = false;
  43686. /**
  43687. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43688. */
  43689. _this._twoSidedLighting = false;
  43690. /**
  43691. * Defines the alpha limits in alpha test mode.
  43692. */
  43693. _this._alphaCutOff = 0.4;
  43694. /**
  43695. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43696. */
  43697. _this._forceAlphaTest = false;
  43698. /**
  43699. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43700. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43701. */
  43702. _this._useAlphaFresnel = false;
  43703. /**
  43704. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43705. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43706. */
  43707. _this._useLinearAlphaFresnel = false;
  43708. /**
  43709. * The transparency mode of the material.
  43710. */
  43711. _this._transparencyMode = null;
  43712. /**
  43713. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43714. * from cos thetav and roughness:
  43715. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43716. */
  43717. _this._environmentBRDFTexture = null;
  43718. /**
  43719. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43720. */
  43721. _this._forceIrradianceInFragment = false;
  43722. /**
  43723. * Force normal to face away from face.
  43724. */
  43725. _this._forceNormalForward = false;
  43726. /**
  43727. * Enables specular anti aliasing in the PBR shader.
  43728. * It will both interacts on the Geometry for analytical and IBL lighting.
  43729. * It also prefilter the roughness map based on the bump values.
  43730. */
  43731. _this._enableSpecularAntiAliasing = false;
  43732. /**
  43733. * Stores the available render targets.
  43734. */
  43735. _this._renderTargets = new BABYLON.SmartArray(16);
  43736. /**
  43737. * Sets the global ambient color for the material used in lighting calculations.
  43738. */
  43739. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43740. /**
  43741. * If set to true, no lighting calculations will be applied.
  43742. */
  43743. _this._unlit = false;
  43744. // Setup the default processing configuration to the scene.
  43745. _this._attachImageProcessingConfiguration(null);
  43746. _this.getRenderTargetTextures = function () {
  43747. _this._renderTargets.reset();
  43748. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43749. _this._renderTargets.push(_this._reflectionTexture);
  43750. }
  43751. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43752. _this._renderTargets.push(_this._refractionTexture);
  43753. }
  43754. return _this._renderTargets;
  43755. };
  43756. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43757. return _this;
  43758. }
  43759. /**
  43760. * Attaches a new image processing configuration to the PBR Material.
  43761. * @param configuration
  43762. */
  43763. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43764. var _this = this;
  43765. if (configuration === this._imageProcessingConfiguration) {
  43766. return;
  43767. }
  43768. // Detaches observer.
  43769. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43770. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43771. }
  43772. // Pick the scene configuration if needed.
  43773. if (!configuration) {
  43774. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43775. }
  43776. else {
  43777. this._imageProcessingConfiguration = configuration;
  43778. }
  43779. // Attaches observer.
  43780. if (this._imageProcessingConfiguration) {
  43781. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43782. _this._markAllSubMeshesAsImageProcessingDirty();
  43783. });
  43784. }
  43785. };
  43786. /**
  43787. * Gets the name of the material class.
  43788. */
  43789. PBRBaseMaterial.prototype.getClassName = function () {
  43790. return "PBRBaseMaterial";
  43791. };
  43792. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43793. /**
  43794. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43795. */
  43796. get: function () {
  43797. return this._useLogarithmicDepth;
  43798. },
  43799. /**
  43800. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43801. */
  43802. set: function (value) {
  43803. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43804. },
  43805. enumerable: true,
  43806. configurable: true
  43807. });
  43808. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43809. /**
  43810. * Gets the current transparency mode.
  43811. */
  43812. get: function () {
  43813. return this._transparencyMode;
  43814. },
  43815. /**
  43816. * Sets the transparency mode of the material.
  43817. *
  43818. * | Value | Type | Description |
  43819. * | ----- | ----------------------------------- | ----------- |
  43820. * | 0 | OPAQUE | |
  43821. * | 1 | ALPHATEST | |
  43822. * | 2 | ALPHABLEND | |
  43823. * | 3 | ALPHATESTANDBLEND | |
  43824. *
  43825. */
  43826. set: function (value) {
  43827. if (this._transparencyMode === value) {
  43828. return;
  43829. }
  43830. this._transparencyMode = value;
  43831. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43832. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43833. },
  43834. enumerable: true,
  43835. configurable: true
  43836. });
  43837. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43838. /**
  43839. * Returns true if alpha blending should be disabled.
  43840. */
  43841. get: function () {
  43842. return (this._linkRefractionWithTransparency ||
  43843. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43844. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43845. },
  43846. enumerable: true,
  43847. configurable: true
  43848. });
  43849. /**
  43850. * Specifies whether or not this material should be rendered in alpha blend mode.
  43851. */
  43852. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43853. if (this._disableAlphaBlending) {
  43854. return false;
  43855. }
  43856. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43857. };
  43858. /**
  43859. * Specifies if the mesh will require alpha blending.
  43860. * @param mesh - BJS mesh.
  43861. */
  43862. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43863. if (this._disableAlphaBlending) {
  43864. return false;
  43865. }
  43866. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43867. };
  43868. /**
  43869. * Specifies whether or not this material should be rendered in alpha test mode.
  43870. */
  43871. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43872. if (this._forceAlphaTest) {
  43873. return true;
  43874. }
  43875. if (this._linkRefractionWithTransparency) {
  43876. return false;
  43877. }
  43878. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43879. };
  43880. /**
  43881. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  43882. */
  43883. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  43884. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  43885. };
  43886. /**
  43887. * Gets the texture used for the alpha test.
  43888. */
  43889. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  43890. return this._albedoTexture;
  43891. };
  43892. /**
  43893. * Specifies that the submesh is ready to be used.
  43894. * @param mesh - BJS mesh.
  43895. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  43896. * @param useInstances - Specifies that instances should be used.
  43897. * @returns - boolean indicating that the submesh is ready or not.
  43898. */
  43899. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43900. if (subMesh.effect && this.isFrozen) {
  43901. if (this._wasPreviouslyReady) {
  43902. return true;
  43903. }
  43904. }
  43905. if (!subMesh._materialDefines) {
  43906. subMesh._materialDefines = new PBRMaterialDefines();
  43907. }
  43908. var defines = subMesh._materialDefines;
  43909. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43910. if (defines._renderId === this.getScene().getRenderId()) {
  43911. return true;
  43912. }
  43913. }
  43914. var scene = this.getScene();
  43915. var engine = scene.getEngine();
  43916. if (defines._areTexturesDirty) {
  43917. if (scene.texturesEnabled) {
  43918. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  43919. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  43920. return false;
  43921. }
  43922. }
  43923. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  43924. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43925. return false;
  43926. }
  43927. }
  43928. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  43929. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43930. return false;
  43931. }
  43932. }
  43933. var reflectionTexture = this._getReflectionTexture();
  43934. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43935. if (!reflectionTexture.isReadyOrNotBlocking()) {
  43936. return false;
  43937. }
  43938. }
  43939. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  43940. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43941. return false;
  43942. }
  43943. }
  43944. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  43945. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43946. return false;
  43947. }
  43948. }
  43949. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  43950. if (this._metallicTexture) {
  43951. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  43952. return false;
  43953. }
  43954. }
  43955. else if (this._reflectivityTexture) {
  43956. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  43957. return false;
  43958. }
  43959. }
  43960. if (this._microSurfaceTexture) {
  43961. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  43962. return false;
  43963. }
  43964. }
  43965. }
  43966. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  43967. // Bump texture cannot be not blocking.
  43968. if (!this._bumpTexture.isReady()) {
  43969. return false;
  43970. }
  43971. }
  43972. var refractionTexture = this._getRefractionTexture();
  43973. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  43974. if (!refractionTexture.isReadyOrNotBlocking()) {
  43975. return false;
  43976. }
  43977. }
  43978. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  43979. // This is blocking.
  43980. if (!this._environmentBRDFTexture.isReady()) {
  43981. return false;
  43982. }
  43983. }
  43984. }
  43985. }
  43986. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43987. if (!this._imageProcessingConfiguration.isReady()) {
  43988. return false;
  43989. }
  43990. }
  43991. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  43992. mesh.createNormals(true);
  43993. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  43994. }
  43995. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  43996. if (effect) {
  43997. scene.resetCachedMaterial();
  43998. subMesh.setEffect(effect, defines);
  43999. this.buildUniformLayout();
  44000. }
  44001. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44002. return false;
  44003. }
  44004. defines._renderId = scene.getRenderId();
  44005. this._wasPreviouslyReady = true;
  44006. return true;
  44007. };
  44008. /**
  44009. * Specifies if the material uses metallic roughness workflow.
  44010. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44011. */
  44012. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44013. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44014. return true;
  44015. }
  44016. return false;
  44017. };
  44018. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44019. if (onCompiled === void 0) { onCompiled = null; }
  44020. if (onError === void 0) { onError = null; }
  44021. if (useInstances === void 0) { useInstances = null; }
  44022. if (useClipPlane === void 0) { useClipPlane = null; }
  44023. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44024. if (!defines.isDirty) {
  44025. return null;
  44026. }
  44027. defines.markAsProcessed();
  44028. var scene = this.getScene();
  44029. var engine = scene.getEngine();
  44030. // Fallbacks
  44031. var fallbacks = new BABYLON.EffectFallbacks();
  44032. var fallbackRank = 0;
  44033. if (defines.USESPHERICALINVERTEX) {
  44034. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44035. }
  44036. if (defines.FOG) {
  44037. fallbacks.addFallback(fallbackRank, "FOG");
  44038. }
  44039. if (defines.SPECULARAA) {
  44040. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44041. }
  44042. if (defines.POINTSIZE) {
  44043. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44044. }
  44045. if (defines.LOGARITHMICDEPTH) {
  44046. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44047. }
  44048. if (defines.PARALLAX) {
  44049. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44050. }
  44051. if (defines.PARALLAXOCCLUSION) {
  44052. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44053. }
  44054. if (defines.ENVIRONMENTBRDF) {
  44055. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44056. }
  44057. if (defines.TANGENT) {
  44058. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44059. }
  44060. if (defines.BUMP) {
  44061. fallbacks.addFallback(fallbackRank++, "BUMP");
  44062. }
  44063. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44064. if (defines.SPECULARTERM) {
  44065. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44066. }
  44067. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44068. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44069. }
  44070. if (defines.LIGHTMAP) {
  44071. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44072. }
  44073. if (defines.NORMAL) {
  44074. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44075. }
  44076. if (defines.AMBIENT) {
  44077. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44078. }
  44079. if (defines.EMISSIVE) {
  44080. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44081. }
  44082. if (defines.VERTEXCOLOR) {
  44083. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44084. }
  44085. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44086. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44087. }
  44088. if (defines.MORPHTARGETS) {
  44089. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44090. }
  44091. //Attributes
  44092. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44093. if (defines.NORMAL) {
  44094. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44095. }
  44096. if (defines.TANGENT) {
  44097. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44098. }
  44099. if (defines.UV1) {
  44100. attribs.push(BABYLON.VertexBuffer.UVKind);
  44101. }
  44102. if (defines.UV2) {
  44103. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44104. }
  44105. if (defines.VERTEXCOLOR) {
  44106. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44107. }
  44108. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44109. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44110. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44111. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44112. "vFogInfos", "vFogColor", "pointSize",
  44113. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44114. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44115. "mBones",
  44116. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44117. "vLightingIntensity",
  44118. "logarithmicDepthConstant",
  44119. "vSphericalX", "vSphericalY", "vSphericalZ",
  44120. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44121. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44122. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44123. "vTangentSpaceParams"
  44124. ];
  44125. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44126. "bumpSampler", "lightmapSampler", "opacitySampler",
  44127. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44128. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44129. "microSurfaceSampler", "environmentBrdfSampler"];
  44130. var uniformBuffers = ["Material", "Scene"];
  44131. if (BABYLON.ImageProcessingConfiguration) {
  44132. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44133. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44134. }
  44135. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44136. uniformsNames: uniforms,
  44137. uniformBuffersNames: uniformBuffers,
  44138. samplers: samplers,
  44139. defines: defines,
  44140. maxSimultaneousLights: this._maxSimultaneousLights
  44141. });
  44142. var join = defines.toString();
  44143. return engine.createEffect("pbr", {
  44144. attributes: attribs,
  44145. uniformsNames: uniforms,
  44146. uniformBuffersNames: uniformBuffers,
  44147. samplers: samplers,
  44148. defines: join,
  44149. fallbacks: fallbacks,
  44150. onCompiled: onCompiled,
  44151. onError: onError,
  44152. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44153. }, engine);
  44154. };
  44155. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44156. if (useInstances === void 0) { useInstances = null; }
  44157. if (useClipPlane === void 0) { useClipPlane = null; }
  44158. var scene = this.getScene();
  44159. var engine = scene.getEngine();
  44160. // Lights
  44161. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44162. defines._needNormals = true;
  44163. // Textures
  44164. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44165. if (defines._areTexturesDirty) {
  44166. defines._needUVs = false;
  44167. if (scene.texturesEnabled) {
  44168. if (scene.getEngine().getCaps().textureLOD) {
  44169. defines.LODBASEDMICROSFURACE = true;
  44170. }
  44171. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44172. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44173. }
  44174. else {
  44175. defines.ALBEDO = false;
  44176. }
  44177. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44178. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44179. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44180. }
  44181. else {
  44182. defines.AMBIENT = false;
  44183. }
  44184. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44185. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44186. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44187. }
  44188. else {
  44189. defines.OPACITY = false;
  44190. }
  44191. var reflectionTexture = this._getReflectionTexture();
  44192. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44193. defines.REFLECTION = true;
  44194. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44195. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44196. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44197. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44198. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44199. defines.INVERTCUBICMAP = true;
  44200. }
  44201. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44202. switch (reflectionTexture.coordinatesMode) {
  44203. case BABYLON.Texture.EXPLICIT_MODE:
  44204. defines.REFLECTIONMAP_EXPLICIT = true;
  44205. break;
  44206. case BABYLON.Texture.PLANAR_MODE:
  44207. defines.REFLECTIONMAP_PLANAR = true;
  44208. break;
  44209. case BABYLON.Texture.PROJECTION_MODE:
  44210. defines.REFLECTIONMAP_PROJECTION = true;
  44211. break;
  44212. case BABYLON.Texture.SKYBOX_MODE:
  44213. defines.REFLECTIONMAP_SKYBOX = true;
  44214. break;
  44215. case BABYLON.Texture.SPHERICAL_MODE:
  44216. defines.REFLECTIONMAP_SPHERICAL = true;
  44217. break;
  44218. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44219. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44220. break;
  44221. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44222. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44223. break;
  44224. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44225. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44226. break;
  44227. case BABYLON.Texture.CUBIC_MODE:
  44228. case BABYLON.Texture.INVCUBIC_MODE:
  44229. default:
  44230. defines.REFLECTIONMAP_CUBIC = true;
  44231. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44232. break;
  44233. }
  44234. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44235. if (reflectionTexture.sphericalPolynomial) {
  44236. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44237. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44238. defines.USESPHERICALINVERTEX = false;
  44239. }
  44240. else {
  44241. defines.USESPHERICALINVERTEX = true;
  44242. }
  44243. }
  44244. }
  44245. }
  44246. else {
  44247. defines.REFLECTION = false;
  44248. defines.REFLECTIONMAP_3D = false;
  44249. defines.REFLECTIONMAP_SPHERICAL = false;
  44250. defines.REFLECTIONMAP_PLANAR = false;
  44251. defines.REFLECTIONMAP_CUBIC = false;
  44252. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44253. defines.REFLECTIONMAP_PROJECTION = false;
  44254. defines.REFLECTIONMAP_SKYBOX = false;
  44255. defines.REFLECTIONMAP_EXPLICIT = false;
  44256. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44257. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44258. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44259. defines.INVERTCUBICMAP = false;
  44260. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44261. defines.USESPHERICALINVERTEX = false;
  44262. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44263. defines.LODINREFLECTIONALPHA = false;
  44264. defines.GAMMAREFLECTION = false;
  44265. defines.RGBDREFLECTION = false;
  44266. }
  44267. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44268. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44269. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44270. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44271. }
  44272. else {
  44273. defines.LIGHTMAP = false;
  44274. }
  44275. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44276. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44277. }
  44278. else {
  44279. defines.EMISSIVE = false;
  44280. }
  44281. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44282. if (this._metallicTexture) {
  44283. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44284. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44285. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44286. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44287. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44288. }
  44289. else if (this._reflectivityTexture) {
  44290. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44291. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44292. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44293. }
  44294. else {
  44295. defines.REFLECTIVITY = false;
  44296. }
  44297. if (this._microSurfaceTexture) {
  44298. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44299. }
  44300. else {
  44301. defines.MICROSURFACEMAP = false;
  44302. }
  44303. }
  44304. else {
  44305. defines.REFLECTIVITY = false;
  44306. defines.MICROSURFACEMAP = false;
  44307. }
  44308. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44309. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44310. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44311. defines.PARALLAX = true;
  44312. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44313. }
  44314. else {
  44315. defines.PARALLAX = false;
  44316. }
  44317. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44318. }
  44319. else {
  44320. defines.BUMP = false;
  44321. }
  44322. var refractionTexture = this._getRefractionTexture();
  44323. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44324. defines.REFRACTION = true;
  44325. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44326. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44327. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44328. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44329. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44330. if (this._linkRefractionWithTransparency) {
  44331. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44332. }
  44333. }
  44334. else {
  44335. defines.REFRACTION = false;
  44336. }
  44337. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44338. defines.ENVIRONMENTBRDF = true;
  44339. }
  44340. else {
  44341. defines.ENVIRONMENTBRDF = false;
  44342. }
  44343. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44344. defines.ALPHAFROMALBEDO = true;
  44345. }
  44346. else {
  44347. defines.ALPHAFROMALBEDO = false;
  44348. }
  44349. }
  44350. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44351. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44352. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44353. if (!this.backFaceCulling && this._twoSidedLighting) {
  44354. defines.TWOSIDEDLIGHTING = true;
  44355. }
  44356. else {
  44357. defines.TWOSIDEDLIGHTING = false;
  44358. }
  44359. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44360. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44361. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44362. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44363. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44364. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44365. }
  44366. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44367. this._imageProcessingConfiguration.prepareDefines(defines);
  44368. }
  44369. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44370. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44371. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44372. // Misc.
  44373. if (defines._areMiscDirty) {
  44374. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44375. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44376. }
  44377. // Values that need to be evaluated on every frame
  44378. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44379. // Attribs
  44380. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44381. };
  44382. /**
  44383. * Force shader compilation
  44384. */
  44385. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44386. var _this = this;
  44387. var localOptions = __assign({ clipPlane: false }, options);
  44388. var defines = new PBRMaterialDefines();
  44389. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44390. if (effect.isReady()) {
  44391. if (onCompiled) {
  44392. onCompiled(this);
  44393. }
  44394. }
  44395. else {
  44396. effect.onCompileObservable.add(function () {
  44397. if (onCompiled) {
  44398. onCompiled(_this);
  44399. }
  44400. });
  44401. }
  44402. };
  44403. /**
  44404. * Initializes the uniform buffer layout for the shader.
  44405. */
  44406. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44407. // Order is important !
  44408. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44409. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44410. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44411. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44412. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44413. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44414. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44415. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44416. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44417. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44418. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44419. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44420. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44421. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44422. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44423. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44424. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44425. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44426. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44427. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44428. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44429. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44430. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44431. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44432. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44433. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44434. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44435. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44436. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44437. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44438. this._uniformBuffer.addUniform("pointSize", 1);
  44439. this._uniformBuffer.create();
  44440. };
  44441. /**
  44442. * Unbinds the textures.
  44443. */
  44444. PBRBaseMaterial.prototype.unbind = function () {
  44445. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44446. this._uniformBuffer.setTexture("reflectionSampler", null);
  44447. }
  44448. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44449. this._uniformBuffer.setTexture("refractionSampler", null);
  44450. }
  44451. _super.prototype.unbind.call(this);
  44452. };
  44453. /**
  44454. * Binds the submesh data.
  44455. * @param world - The world matrix.
  44456. * @param mesh - The BJS mesh.
  44457. * @param subMesh - A submesh of the BJS mesh.
  44458. */
  44459. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44460. var scene = this.getScene();
  44461. var defines = subMesh._materialDefines;
  44462. if (!defines) {
  44463. return;
  44464. }
  44465. var effect = subMesh.effect;
  44466. if (!effect) {
  44467. return;
  44468. }
  44469. this._activeEffect = effect;
  44470. // Matrices
  44471. this.bindOnlyWorldMatrix(world);
  44472. // Normal Matrix
  44473. if (defines.OBJECTSPACE_NORMALMAP) {
  44474. world.toNormalMatrix(this._normalMatrix);
  44475. this.bindOnlyNormalMatrix(this._normalMatrix);
  44476. }
  44477. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44478. // Bones
  44479. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44480. var reflectionTexture = null;
  44481. if (mustRebind) {
  44482. this._uniformBuffer.bindToEffect(effect, "Material");
  44483. this.bindViewProjection(effect);
  44484. reflectionTexture = this._getReflectionTexture();
  44485. var refractionTexture = this._getRefractionTexture();
  44486. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44487. // Texture uniforms
  44488. if (scene.texturesEnabled) {
  44489. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44490. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44491. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44492. }
  44493. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44494. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44495. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44496. }
  44497. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44498. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44499. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44500. }
  44501. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44502. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44503. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44504. if (reflectionTexture.boundingBoxSize) {
  44505. var cubeTexture = reflectionTexture;
  44506. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44507. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44508. }
  44509. var polynomials = reflectionTexture.sphericalPolynomial;
  44510. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44511. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44512. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44513. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44514. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44515. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44516. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44517. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44518. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44519. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44520. }
  44521. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44522. }
  44523. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44524. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44525. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44526. }
  44527. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44528. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44529. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44530. }
  44531. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44532. if (this._metallicTexture) {
  44533. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44534. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44535. }
  44536. else if (this._reflectivityTexture) {
  44537. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44538. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44539. }
  44540. if (this._microSurfaceTexture) {
  44541. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44542. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44543. }
  44544. }
  44545. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44546. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44547. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44548. if (scene._mirroredCameraPosition) {
  44549. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44550. }
  44551. else {
  44552. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44553. }
  44554. }
  44555. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44556. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44557. var depth = 1.0;
  44558. if (!refractionTexture.isCube) {
  44559. if (refractionTexture.depth) {
  44560. depth = refractionTexture.depth;
  44561. }
  44562. }
  44563. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44564. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44565. }
  44566. }
  44567. // Point size
  44568. if (this.pointsCloud) {
  44569. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44570. }
  44571. // Colors
  44572. if (defines.METALLICWORKFLOW) {
  44573. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44574. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44575. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44576. }
  44577. else {
  44578. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44579. }
  44580. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44581. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44582. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44583. // Misc
  44584. this._lightingInfos.x = this._directIntensity;
  44585. this._lightingInfos.y = this._emissiveIntensity;
  44586. this._lightingInfos.z = this._environmentIntensity;
  44587. this._lightingInfos.w = this._specularIntensity;
  44588. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44589. }
  44590. // Textures
  44591. if (scene.texturesEnabled) {
  44592. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44593. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44594. }
  44595. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44596. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44597. }
  44598. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44599. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44600. }
  44601. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44602. if (defines.LODBASEDMICROSFURACE) {
  44603. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44604. }
  44605. else {
  44606. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44607. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44608. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44609. }
  44610. }
  44611. if (defines.ENVIRONMENTBRDF) {
  44612. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44613. }
  44614. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44615. if (defines.LODBASEDMICROSFURACE) {
  44616. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44617. }
  44618. else {
  44619. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44620. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44621. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44622. }
  44623. }
  44624. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44625. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44626. }
  44627. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44628. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44629. }
  44630. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44631. if (this._metallicTexture) {
  44632. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44633. }
  44634. else if (this._reflectivityTexture) {
  44635. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44636. }
  44637. if (this._microSurfaceTexture) {
  44638. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44639. }
  44640. }
  44641. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44642. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44643. }
  44644. }
  44645. // Clip plane
  44646. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44647. // Colors
  44648. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44649. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44650. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44651. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44652. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44653. }
  44654. if (mustRebind || !this.isFrozen) {
  44655. // Lights
  44656. if (scene.lightsEnabled && !this._disableLighting) {
  44657. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44658. }
  44659. // View
  44660. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44661. this.bindView(effect);
  44662. }
  44663. // Fog
  44664. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44665. // Morph targets
  44666. if (defines.NUM_MORPH_INFLUENCERS) {
  44667. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44668. }
  44669. // image processing
  44670. this._imageProcessingConfiguration.bind(this._activeEffect);
  44671. // Log. depth
  44672. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44673. }
  44674. this._uniformBuffer.update();
  44675. this._afterBind(mesh, this._activeEffect);
  44676. };
  44677. /**
  44678. * Returns the animatable textures.
  44679. * @returns - Array of animatable textures.
  44680. */
  44681. PBRBaseMaterial.prototype.getAnimatables = function () {
  44682. var results = [];
  44683. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44684. results.push(this._albedoTexture);
  44685. }
  44686. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44687. results.push(this._ambientTexture);
  44688. }
  44689. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44690. results.push(this._opacityTexture);
  44691. }
  44692. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44693. results.push(this._reflectionTexture);
  44694. }
  44695. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44696. results.push(this._emissiveTexture);
  44697. }
  44698. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44699. results.push(this._metallicTexture);
  44700. }
  44701. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44702. results.push(this._reflectivityTexture);
  44703. }
  44704. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44705. results.push(this._bumpTexture);
  44706. }
  44707. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44708. results.push(this._lightmapTexture);
  44709. }
  44710. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44711. results.push(this._refractionTexture);
  44712. }
  44713. return results;
  44714. };
  44715. /**
  44716. * Returns the texture used for reflections.
  44717. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44718. */
  44719. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44720. if (this._reflectionTexture) {
  44721. return this._reflectionTexture;
  44722. }
  44723. return this.getScene().environmentTexture;
  44724. };
  44725. /**
  44726. * Returns the texture used for refraction or null if none is used.
  44727. * @returns - Refection texture if present. If no refraction texture and refraction
  44728. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44729. */
  44730. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44731. if (this._refractionTexture) {
  44732. return this._refractionTexture;
  44733. }
  44734. if (this._linkRefractionWithTransparency) {
  44735. return this.getScene().environmentTexture;
  44736. }
  44737. return null;
  44738. };
  44739. /**
  44740. * Disposes the resources of the material.
  44741. * @param forceDisposeEffect - Forces the disposal of effects.
  44742. * @param forceDisposeTextures - Forces the disposal of all textures.
  44743. */
  44744. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44745. if (forceDisposeTextures) {
  44746. if (this._albedoTexture) {
  44747. this._albedoTexture.dispose();
  44748. }
  44749. if (this._ambientTexture) {
  44750. this._ambientTexture.dispose();
  44751. }
  44752. if (this._opacityTexture) {
  44753. this._opacityTexture.dispose();
  44754. }
  44755. if (this._reflectionTexture) {
  44756. this._reflectionTexture.dispose();
  44757. }
  44758. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44759. this._environmentBRDFTexture.dispose();
  44760. }
  44761. if (this._emissiveTexture) {
  44762. this._emissiveTexture.dispose();
  44763. }
  44764. if (this._metallicTexture) {
  44765. this._metallicTexture.dispose();
  44766. }
  44767. if (this._reflectivityTexture) {
  44768. this._reflectivityTexture.dispose();
  44769. }
  44770. if (this._bumpTexture) {
  44771. this._bumpTexture.dispose();
  44772. }
  44773. if (this._lightmapTexture) {
  44774. this._lightmapTexture.dispose();
  44775. }
  44776. if (this._refractionTexture) {
  44777. this._refractionTexture.dispose();
  44778. }
  44779. }
  44780. this._renderTargets.dispose();
  44781. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44782. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44783. }
  44784. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44785. };
  44786. /**
  44787. * Stores the reflectivity values based on metallic roughness workflow.
  44788. */
  44789. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44790. __decorate([
  44791. BABYLON.serializeAsImageProcessingConfiguration()
  44792. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44793. __decorate([
  44794. BABYLON.serialize()
  44795. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44796. __decorate([
  44797. BABYLON.serialize()
  44798. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44799. return PBRBaseMaterial;
  44800. }(BABYLON.PushMaterial));
  44801. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44802. })(BABYLON || (BABYLON = {}));
  44803. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44804. var BABYLON;
  44805. (function (BABYLON) {
  44806. /**
  44807. * The Physically based simple base material of BJS.
  44808. *
  44809. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44810. * It is used as the base class for both the specGloss and metalRough conventions.
  44811. */
  44812. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44813. __extends(PBRBaseSimpleMaterial, _super);
  44814. /**
  44815. * Instantiates a new PBRMaterial instance.
  44816. *
  44817. * @param name The material name
  44818. * @param scene The scene the material will be use in.
  44819. */
  44820. function PBRBaseSimpleMaterial(name, scene) {
  44821. var _this = _super.call(this, name, scene) || this;
  44822. /**
  44823. * Number of Simultaneous lights allowed on the material.
  44824. */
  44825. _this.maxSimultaneousLights = 4;
  44826. /**
  44827. * If sets to true, disables all the lights affecting the material.
  44828. */
  44829. _this.disableLighting = false;
  44830. /**
  44831. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44832. */
  44833. _this.invertNormalMapX = false;
  44834. /**
  44835. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44836. */
  44837. _this.invertNormalMapY = false;
  44838. /**
  44839. * Emissivie color used to self-illuminate the model.
  44840. */
  44841. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44842. /**
  44843. * Occlusion Channel Strenght.
  44844. */
  44845. _this.occlusionStrength = 1.0;
  44846. _this.useLightmapAsShadowmap = false;
  44847. _this._useAlphaFromAlbedoTexture = true;
  44848. _this._useAmbientInGrayScale = true;
  44849. return _this;
  44850. }
  44851. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44852. /**
  44853. * Gets the current double sided mode.
  44854. */
  44855. get: function () {
  44856. return this._twoSidedLighting;
  44857. },
  44858. /**
  44859. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44860. */
  44861. set: function (value) {
  44862. if (this._twoSidedLighting === value) {
  44863. return;
  44864. }
  44865. this._twoSidedLighting = value;
  44866. this.backFaceCulling = !value;
  44867. this._markAllSubMeshesAsTexturesDirty();
  44868. },
  44869. enumerable: true,
  44870. configurable: true
  44871. });
  44872. /**
  44873. * Return the active textures of the material.
  44874. */
  44875. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  44876. var activeTextures = _super.prototype.getActiveTextures.call(this);
  44877. if (this.environmentTexture) {
  44878. activeTextures.push(this.environmentTexture);
  44879. }
  44880. if (this.normalTexture) {
  44881. activeTextures.push(this.normalTexture);
  44882. }
  44883. if (this.emissiveTexture) {
  44884. activeTextures.push(this.emissiveTexture);
  44885. }
  44886. if (this.occlusionTexture) {
  44887. activeTextures.push(this.occlusionTexture);
  44888. }
  44889. if (this.lightmapTexture) {
  44890. activeTextures.push(this.lightmapTexture);
  44891. }
  44892. return activeTextures;
  44893. };
  44894. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  44895. if (_super.prototype.hasTexture.call(this, texture)) {
  44896. return true;
  44897. }
  44898. if (this.lightmapTexture === texture) {
  44899. return true;
  44900. }
  44901. return false;
  44902. };
  44903. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  44904. return "PBRBaseSimpleMaterial";
  44905. };
  44906. __decorate([
  44907. BABYLON.serialize(),
  44908. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44909. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  44910. __decorate([
  44911. BABYLON.serialize(),
  44912. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44913. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  44914. __decorate([
  44915. BABYLON.serializeAsTexture(),
  44916. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  44917. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  44918. __decorate([
  44919. BABYLON.serialize(),
  44920. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44921. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  44922. __decorate([
  44923. BABYLON.serialize(),
  44924. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44925. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  44926. __decorate([
  44927. BABYLON.serializeAsTexture(),
  44928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  44929. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  44930. __decorate([
  44931. BABYLON.serializeAsColor3("emissive"),
  44932. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44933. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  44934. __decorate([
  44935. BABYLON.serializeAsTexture(),
  44936. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44937. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  44938. __decorate([
  44939. BABYLON.serialize(),
  44940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  44941. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  44942. __decorate([
  44943. BABYLON.serializeAsTexture(),
  44944. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  44945. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  44946. __decorate([
  44947. BABYLON.serialize(),
  44948. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  44949. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  44950. __decorate([
  44951. BABYLON.serialize()
  44952. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  44953. __decorate([
  44954. BABYLON.serializeAsTexture(),
  44955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  44956. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  44957. __decorate([
  44958. BABYLON.serialize(),
  44959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44960. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44961. return PBRBaseSimpleMaterial;
  44962. }(BABYLON.PBRBaseMaterial));
  44963. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  44964. })(BABYLON || (BABYLON = {}));
  44965. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  44966. var BABYLON;
  44967. (function (BABYLON) {
  44968. /**
  44969. * The Physically based material of BJS.
  44970. *
  44971. * This offers the main features of a standard PBR material.
  44972. * For more information, please refer to the documentation :
  44973. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44974. */
  44975. var PBRMaterial = /** @class */ (function (_super) {
  44976. __extends(PBRMaterial, _super);
  44977. /**
  44978. * Instantiates a new PBRMaterial instance.
  44979. *
  44980. * @param name The material name
  44981. * @param scene The scene the material will be use in.
  44982. */
  44983. function PBRMaterial(name, scene) {
  44984. var _this = _super.call(this, name, scene) || this;
  44985. /**
  44986. * Intensity of the direct lights e.g. the four lights available in your scene.
  44987. * This impacts both the direct diffuse and specular highlights.
  44988. */
  44989. _this.directIntensity = 1.0;
  44990. /**
  44991. * Intensity of the emissive part of the material.
  44992. * This helps controlling the emissive effect without modifying the emissive color.
  44993. */
  44994. _this.emissiveIntensity = 1.0;
  44995. /**
  44996. * Intensity of the environment e.g. how much the environment will light the object
  44997. * either through harmonics for rough material or through the refelction for shiny ones.
  44998. */
  44999. _this.environmentIntensity = 1.0;
  45000. /**
  45001. * This is a special control allowing the reduction of the specular highlights coming from the
  45002. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45003. */
  45004. _this.specularIntensity = 1.0;
  45005. /**
  45006. * Debug Control allowing disabling the bump map on this material.
  45007. */
  45008. _this.disableBumpMap = false;
  45009. /**
  45010. * AKA Occlusion Texture Intensity in other nomenclature.
  45011. */
  45012. _this.ambientTextureStrength = 1.0;
  45013. /**
  45014. * The color of a material in ambient lighting.
  45015. */
  45016. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45017. /**
  45018. * AKA Diffuse Color in other nomenclature.
  45019. */
  45020. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45021. /**
  45022. * AKA Specular Color in other nomenclature.
  45023. */
  45024. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45025. /**
  45026. * The color reflected from the material.
  45027. */
  45028. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45029. /**
  45030. * The color emitted from the material.
  45031. */
  45032. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45033. /**
  45034. * AKA Glossiness in other nomenclature.
  45035. */
  45036. _this.microSurface = 1.0;
  45037. /**
  45038. * source material index of refraction (IOR)' / 'destination material IOR.
  45039. */
  45040. _this.indexOfRefraction = 0.66;
  45041. /**
  45042. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45043. */
  45044. _this.invertRefractionY = false;
  45045. /**
  45046. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45047. * Materials half opaque for instance using refraction could benefit from this control.
  45048. */
  45049. _this.linkRefractionWithTransparency = false;
  45050. _this.useLightmapAsShadowmap = false;
  45051. /**
  45052. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45053. */
  45054. _this.useAlphaFromAlbedoTexture = false;
  45055. /**
  45056. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45057. */
  45058. _this.forceAlphaTest = false;
  45059. /**
  45060. * Defines the alpha limits in alpha test mode.
  45061. */
  45062. _this.alphaCutOff = 0.4;
  45063. /**
  45064. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45065. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45066. */
  45067. _this.useSpecularOverAlpha = true;
  45068. /**
  45069. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45070. */
  45071. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45072. /**
  45073. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45074. */
  45075. _this.useRoughnessFromMetallicTextureAlpha = true;
  45076. /**
  45077. * Specifies if the metallic texture contains the roughness information in its green channel.
  45078. */
  45079. _this.useRoughnessFromMetallicTextureGreen = false;
  45080. /**
  45081. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45082. */
  45083. _this.useMetallnessFromMetallicTextureBlue = false;
  45084. /**
  45085. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45086. */
  45087. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45088. /**
  45089. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45090. */
  45091. _this.useAmbientInGrayScale = false;
  45092. /**
  45093. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45094. * The material will try to infer what glossiness each pixel should be.
  45095. */
  45096. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45097. /**
  45098. * BJS is using an harcoded light falloff based on a manually sets up range.
  45099. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45100. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45101. */
  45102. _this.usePhysicalLightFalloff = true;
  45103. /**
  45104. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45105. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45106. */
  45107. _this.useRadianceOverAlpha = true;
  45108. /**
  45109. * Allows using an object space normal map (instead of tangent space).
  45110. */
  45111. _this.useObjectSpaceNormalMap = false;
  45112. /**
  45113. * Allows using the bump map in parallax mode.
  45114. */
  45115. _this.useParallax = false;
  45116. /**
  45117. * Allows using the bump map in parallax occlusion mode.
  45118. */
  45119. _this.useParallaxOcclusion = false;
  45120. /**
  45121. * Controls the scale bias of the parallax mode.
  45122. */
  45123. _this.parallaxScaleBias = 0.05;
  45124. /**
  45125. * If sets to true, disables all the lights affecting the material.
  45126. */
  45127. _this.disableLighting = false;
  45128. /**
  45129. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45130. */
  45131. _this.forceIrradianceInFragment = false;
  45132. /**
  45133. * Number of Simultaneous lights allowed on the material.
  45134. */
  45135. _this.maxSimultaneousLights = 4;
  45136. /**
  45137. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45138. */
  45139. _this.invertNormalMapX = false;
  45140. /**
  45141. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45142. */
  45143. _this.invertNormalMapY = false;
  45144. /**
  45145. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45146. */
  45147. _this.twoSidedLighting = false;
  45148. /**
  45149. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45150. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45151. */
  45152. _this.useAlphaFresnel = false;
  45153. /**
  45154. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45155. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45156. */
  45157. _this.useLinearAlphaFresnel = false;
  45158. /**
  45159. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45160. * And/Or occlude the blended part.
  45161. */
  45162. _this.environmentBRDFTexture = null;
  45163. /**
  45164. * Force normal to face away from face.
  45165. */
  45166. _this.forceNormalForward = false;
  45167. /**
  45168. * Enables specular anti aliasing in the PBR shader.
  45169. * It will both interacts on the Geometry for analytical and IBL lighting.
  45170. * It also prefilter the roughness map based on the bump values.
  45171. */
  45172. _this.enableSpecularAntiAliasing = false;
  45173. /**
  45174. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45175. * makes the reflect vector face the model (under horizon).
  45176. */
  45177. _this.useHorizonOcclusion = true;
  45178. /**
  45179. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45180. * too much the area relying on ambient texture to define their ambient occlusion.
  45181. */
  45182. _this.useRadianceOcclusion = true;
  45183. /**
  45184. * If set to true, no lighting calculations will be applied.
  45185. */
  45186. _this.unlit = false;
  45187. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45188. return _this;
  45189. }
  45190. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45191. /**
  45192. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45193. */
  45194. get: function () {
  45195. return this._PBRMATERIAL_OPAQUE;
  45196. },
  45197. enumerable: true,
  45198. configurable: true
  45199. });
  45200. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45201. /**
  45202. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45203. */
  45204. get: function () {
  45205. return this._PBRMATERIAL_ALPHATEST;
  45206. },
  45207. enumerable: true,
  45208. configurable: true
  45209. });
  45210. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45211. /**
  45212. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45213. */
  45214. get: function () {
  45215. return this._PBRMATERIAL_ALPHABLEND;
  45216. },
  45217. enumerable: true,
  45218. configurable: true
  45219. });
  45220. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45221. /**
  45222. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45223. * They are also discarded below the alpha cutoff threshold to improve performances.
  45224. */
  45225. get: function () {
  45226. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45227. },
  45228. enumerable: true,
  45229. configurable: true
  45230. });
  45231. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45232. /**
  45233. * Gets the image processing configuration used either in this material.
  45234. */
  45235. get: function () {
  45236. return this._imageProcessingConfiguration;
  45237. },
  45238. /**
  45239. * Sets the Default image processing configuration used either in the this material.
  45240. *
  45241. * If sets to null, the scene one is in use.
  45242. */
  45243. set: function (value) {
  45244. this._attachImageProcessingConfiguration(value);
  45245. // Ensure the effect will be rebuilt.
  45246. this._markAllSubMeshesAsTexturesDirty();
  45247. },
  45248. enumerable: true,
  45249. configurable: true
  45250. });
  45251. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45252. /**
  45253. * Gets wether the color curves effect is enabled.
  45254. */
  45255. get: function () {
  45256. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45257. },
  45258. /**
  45259. * Sets wether the color curves effect is enabled.
  45260. */
  45261. set: function (value) {
  45262. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45263. },
  45264. enumerable: true,
  45265. configurable: true
  45266. });
  45267. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45268. /**
  45269. * Gets wether the color grading effect is enabled.
  45270. */
  45271. get: function () {
  45272. return this.imageProcessingConfiguration.colorGradingEnabled;
  45273. },
  45274. /**
  45275. * Gets wether the color grading effect is enabled.
  45276. */
  45277. set: function (value) {
  45278. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45279. },
  45280. enumerable: true,
  45281. configurable: true
  45282. });
  45283. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45284. /**
  45285. * Gets wether tonemapping is enabled or not.
  45286. */
  45287. get: function () {
  45288. return this._imageProcessingConfiguration.toneMappingEnabled;
  45289. },
  45290. /**
  45291. * Sets wether tonemapping is enabled or not
  45292. */
  45293. set: function (value) {
  45294. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45295. },
  45296. enumerable: true,
  45297. configurable: true
  45298. });
  45299. ;
  45300. ;
  45301. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45302. /**
  45303. * The camera exposure used on this material.
  45304. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45305. * This corresponds to a photographic exposure.
  45306. */
  45307. get: function () {
  45308. return this._imageProcessingConfiguration.exposure;
  45309. },
  45310. /**
  45311. * The camera exposure used on this material.
  45312. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45313. * This corresponds to a photographic exposure.
  45314. */
  45315. set: function (value) {
  45316. this._imageProcessingConfiguration.exposure = value;
  45317. },
  45318. enumerable: true,
  45319. configurable: true
  45320. });
  45321. ;
  45322. ;
  45323. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45324. /**
  45325. * Gets The camera contrast used on this material.
  45326. */
  45327. get: function () {
  45328. return this._imageProcessingConfiguration.contrast;
  45329. },
  45330. /**
  45331. * Sets The camera contrast used on this material.
  45332. */
  45333. set: function (value) {
  45334. this._imageProcessingConfiguration.contrast = value;
  45335. },
  45336. enumerable: true,
  45337. configurable: true
  45338. });
  45339. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45340. /**
  45341. * Gets the Color Grading 2D Lookup Texture.
  45342. */
  45343. get: function () {
  45344. return this._imageProcessingConfiguration.colorGradingTexture;
  45345. },
  45346. /**
  45347. * Sets the Color Grading 2D Lookup Texture.
  45348. */
  45349. set: function (value) {
  45350. this._imageProcessingConfiguration.colorGradingTexture = value;
  45351. },
  45352. enumerable: true,
  45353. configurable: true
  45354. });
  45355. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45356. /**
  45357. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45358. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45359. * 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;
  45360. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45361. */
  45362. get: function () {
  45363. return this._imageProcessingConfiguration.colorCurves;
  45364. },
  45365. /**
  45366. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45367. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45368. * 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;
  45369. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45370. */
  45371. set: function (value) {
  45372. this._imageProcessingConfiguration.colorCurves = value;
  45373. },
  45374. enumerable: true,
  45375. configurable: true
  45376. });
  45377. /**
  45378. * Returns the name of this material class.
  45379. */
  45380. PBRMaterial.prototype.getClassName = function () {
  45381. return "PBRMaterial";
  45382. };
  45383. /**
  45384. * Returns an array of the actively used textures.
  45385. * @returns - Array of BaseTextures
  45386. */
  45387. PBRMaterial.prototype.getActiveTextures = function () {
  45388. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45389. if (this._albedoTexture) {
  45390. activeTextures.push(this._albedoTexture);
  45391. }
  45392. if (this._ambientTexture) {
  45393. activeTextures.push(this._ambientTexture);
  45394. }
  45395. if (this._opacityTexture) {
  45396. activeTextures.push(this._opacityTexture);
  45397. }
  45398. if (this._reflectionTexture) {
  45399. activeTextures.push(this._reflectionTexture);
  45400. }
  45401. if (this._emissiveTexture) {
  45402. activeTextures.push(this._emissiveTexture);
  45403. }
  45404. if (this._reflectivityTexture) {
  45405. activeTextures.push(this._reflectivityTexture);
  45406. }
  45407. if (this._metallicTexture) {
  45408. activeTextures.push(this._metallicTexture);
  45409. }
  45410. if (this._microSurfaceTexture) {
  45411. activeTextures.push(this._microSurfaceTexture);
  45412. }
  45413. if (this._bumpTexture) {
  45414. activeTextures.push(this._bumpTexture);
  45415. }
  45416. if (this._lightmapTexture) {
  45417. activeTextures.push(this._lightmapTexture);
  45418. }
  45419. if (this._refractionTexture) {
  45420. activeTextures.push(this._refractionTexture);
  45421. }
  45422. return activeTextures;
  45423. };
  45424. /**
  45425. * Checks to see if a texture is used in the material.
  45426. * @param texture - Base texture to use.
  45427. * @returns - Boolean specifying if a texture is used in the material.
  45428. */
  45429. PBRMaterial.prototype.hasTexture = function (texture) {
  45430. if (_super.prototype.hasTexture.call(this, texture)) {
  45431. return true;
  45432. }
  45433. if (this._albedoTexture === texture) {
  45434. return true;
  45435. }
  45436. if (this._ambientTexture === texture) {
  45437. return true;
  45438. }
  45439. if (this._opacityTexture === texture) {
  45440. return true;
  45441. }
  45442. if (this._reflectionTexture === texture) {
  45443. return true;
  45444. }
  45445. if (this._reflectivityTexture === texture) {
  45446. return true;
  45447. }
  45448. if (this._metallicTexture === texture) {
  45449. return true;
  45450. }
  45451. if (this._microSurfaceTexture === texture) {
  45452. return true;
  45453. }
  45454. if (this._bumpTexture === texture) {
  45455. return true;
  45456. }
  45457. if (this._lightmapTexture === texture) {
  45458. return true;
  45459. }
  45460. if (this._refractionTexture === texture) {
  45461. return true;
  45462. }
  45463. return false;
  45464. };
  45465. /**
  45466. * Makes a duplicate of the current material.
  45467. * @param name - name to use for the new material.
  45468. */
  45469. PBRMaterial.prototype.clone = function (name) {
  45470. var _this = this;
  45471. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45472. clone.id = name;
  45473. clone.name = name;
  45474. return clone;
  45475. };
  45476. /**
  45477. * Serializes this PBR Material.
  45478. * @returns - An object with the serialized material.
  45479. */
  45480. PBRMaterial.prototype.serialize = function () {
  45481. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45482. serializationObject.customType = "BABYLON.PBRMaterial";
  45483. return serializationObject;
  45484. };
  45485. // Statics
  45486. /**
  45487. * Parses a PBR Material from a serialized object.
  45488. * @param source - Serialized object.
  45489. * @param scene - BJS scene instance.
  45490. * @param rootUrl - url for the scene object
  45491. * @returns - PBRMaterial
  45492. */
  45493. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45494. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45495. };
  45496. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45497. /**
  45498. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45499. */
  45500. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45501. /**
  45502. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45503. */
  45504. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45505. /**
  45506. * 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.
  45507. * They are also discarded below the alpha cutoff threshold to improve performances.
  45508. */
  45509. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45510. __decorate([
  45511. BABYLON.serialize(),
  45512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45513. ], PBRMaterial.prototype, "directIntensity", void 0);
  45514. __decorate([
  45515. BABYLON.serialize(),
  45516. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45517. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45518. __decorate([
  45519. BABYLON.serialize(),
  45520. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45521. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45522. __decorate([
  45523. BABYLON.serialize(),
  45524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45525. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45526. __decorate([
  45527. BABYLON.serialize(),
  45528. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45529. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45530. __decorate([
  45531. BABYLON.serializeAsTexture(),
  45532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45533. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45534. __decorate([
  45535. BABYLON.serializeAsTexture(),
  45536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45537. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45538. __decorate([
  45539. BABYLON.serialize(),
  45540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45541. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45542. __decorate([
  45543. BABYLON.serializeAsTexture(),
  45544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45545. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45546. __decorate([
  45547. BABYLON.serializeAsTexture(),
  45548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45549. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45550. __decorate([
  45551. BABYLON.serializeAsTexture(),
  45552. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45553. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45554. __decorate([
  45555. BABYLON.serializeAsTexture(),
  45556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45557. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45558. __decorate([
  45559. BABYLON.serializeAsTexture(),
  45560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45561. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45562. __decorate([
  45563. BABYLON.serialize(),
  45564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45565. ], PBRMaterial.prototype, "metallic", void 0);
  45566. __decorate([
  45567. BABYLON.serialize(),
  45568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45569. ], PBRMaterial.prototype, "roughness", void 0);
  45570. __decorate([
  45571. BABYLON.serializeAsTexture(),
  45572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45573. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45574. __decorate([
  45575. BABYLON.serializeAsTexture(),
  45576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45577. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45578. __decorate([
  45579. BABYLON.serializeAsTexture(),
  45580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45581. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45582. __decorate([
  45583. BABYLON.serializeAsTexture(),
  45584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45585. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45586. __decorate([
  45587. BABYLON.serializeAsColor3("ambient"),
  45588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45589. ], PBRMaterial.prototype, "ambientColor", void 0);
  45590. __decorate([
  45591. BABYLON.serializeAsColor3("albedo"),
  45592. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45593. ], PBRMaterial.prototype, "albedoColor", void 0);
  45594. __decorate([
  45595. BABYLON.serializeAsColor3("reflectivity"),
  45596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45597. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45598. __decorate([
  45599. BABYLON.serializeAsColor3("reflection"),
  45600. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45601. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45602. __decorate([
  45603. BABYLON.serializeAsColor3("emissive"),
  45604. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45605. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45606. __decorate([
  45607. BABYLON.serialize(),
  45608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45609. ], PBRMaterial.prototype, "microSurface", void 0);
  45610. __decorate([
  45611. BABYLON.serialize(),
  45612. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45613. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45614. __decorate([
  45615. BABYLON.serialize(),
  45616. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45617. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45618. __decorate([
  45619. BABYLON.serialize(),
  45620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45621. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45622. __decorate([
  45623. BABYLON.serialize(),
  45624. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45625. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45626. __decorate([
  45627. BABYLON.serialize(),
  45628. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45629. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45630. __decorate([
  45631. BABYLON.serialize(),
  45632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45633. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45637. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45641. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45642. __decorate([
  45643. BABYLON.serialize(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45645. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45654. __decorate([
  45655. BABYLON.serialize(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45658. __decorate([
  45659. BABYLON.serialize(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45665. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45666. __decorate([
  45667. BABYLON.serialize(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45669. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45670. __decorate([
  45671. BABYLON.serialize(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45674. __decorate([
  45675. BABYLON.serialize(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45678. __decorate([
  45679. BABYLON.serialize(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45682. __decorate([
  45683. BABYLON.serialize(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45685. ], PBRMaterial.prototype, "useParallax", void 0);
  45686. __decorate([
  45687. BABYLON.serialize(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45689. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45690. __decorate([
  45691. BABYLON.serialize(),
  45692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45693. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45694. __decorate([
  45695. BABYLON.serialize(),
  45696. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45697. ], PBRMaterial.prototype, "disableLighting", void 0);
  45698. __decorate([
  45699. BABYLON.serialize(),
  45700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45701. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45702. __decorate([
  45703. BABYLON.serialize(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45705. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45706. __decorate([
  45707. BABYLON.serialize(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45709. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45710. __decorate([
  45711. BABYLON.serialize(),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45714. __decorate([
  45715. BABYLON.serialize(),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45717. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45718. __decorate([
  45719. BABYLON.serialize(),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45721. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45722. __decorate([
  45723. BABYLON.serialize(),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45725. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45726. __decorate([
  45727. BABYLON.serializeAsTexture(),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45729. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45733. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45734. __decorate([
  45735. BABYLON.serialize(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45737. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45738. __decorate([
  45739. BABYLON.serialize(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45741. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45742. __decorate([
  45743. BABYLON.serialize(),
  45744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45745. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45746. __decorate([
  45747. BABYLON.serialize(),
  45748. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45749. ], PBRMaterial.prototype, "unlit", void 0);
  45750. return PBRMaterial;
  45751. }(BABYLON.PBRBaseMaterial));
  45752. BABYLON.PBRMaterial = PBRMaterial;
  45753. })(BABYLON || (BABYLON = {}));
  45754. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45755. var BABYLON;
  45756. (function (BABYLON) {
  45757. /**
  45758. * The PBR material of BJS following the metal roughness convention.
  45759. *
  45760. * This fits to the PBR convention in the GLTF definition:
  45761. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45762. */
  45763. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45764. __extends(PBRMetallicRoughnessMaterial, _super);
  45765. /**
  45766. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45767. *
  45768. * @param name The material name
  45769. * @param scene The scene the material will be use in.
  45770. */
  45771. function PBRMetallicRoughnessMaterial(name, scene) {
  45772. var _this = _super.call(this, name, scene) || this;
  45773. _this._useRoughnessFromMetallicTextureAlpha = false;
  45774. _this._useRoughnessFromMetallicTextureGreen = true;
  45775. _this._useMetallnessFromMetallicTextureBlue = true;
  45776. _this.metallic = 1.0;
  45777. _this.roughness = 1.0;
  45778. return _this;
  45779. }
  45780. /**
  45781. * Return the currrent class name of the material.
  45782. */
  45783. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45784. return "PBRMetallicRoughnessMaterial";
  45785. };
  45786. /**
  45787. * Return the active textures of the material.
  45788. */
  45789. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45790. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45791. if (this.baseTexture) {
  45792. activeTextures.push(this.baseTexture);
  45793. }
  45794. if (this.metallicRoughnessTexture) {
  45795. activeTextures.push(this.metallicRoughnessTexture);
  45796. }
  45797. return activeTextures;
  45798. };
  45799. /**
  45800. * Checks to see if a texture is used in the material.
  45801. * @param texture - Base texture to use.
  45802. * @returns - Boolean specifying if a texture is used in the material.
  45803. */
  45804. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45805. if (_super.prototype.hasTexture.call(this, texture)) {
  45806. return true;
  45807. }
  45808. if (this.baseTexture === texture) {
  45809. return true;
  45810. }
  45811. if (this.metallicRoughnessTexture === texture) {
  45812. return true;
  45813. }
  45814. return false;
  45815. };
  45816. /**
  45817. * Makes a duplicate of the current material.
  45818. * @param name - name to use for the new material.
  45819. */
  45820. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45821. var _this = this;
  45822. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45823. clone.id = name;
  45824. clone.name = name;
  45825. return clone;
  45826. };
  45827. /**
  45828. * Serialize the material to a parsable JSON object.
  45829. */
  45830. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45831. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45832. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45833. return serializationObject;
  45834. };
  45835. /**
  45836. * Parses a JSON object correponding to the serialize function.
  45837. */
  45838. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45839. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45840. };
  45841. __decorate([
  45842. BABYLON.serializeAsColor3(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45844. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45845. __decorate([
  45846. BABYLON.serializeAsTexture(),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45848. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45849. __decorate([
  45850. BABYLON.serialize(),
  45851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45852. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45853. __decorate([
  45854. BABYLON.serialize(),
  45855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45856. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45857. __decorate([
  45858. BABYLON.serializeAsTexture(),
  45859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45860. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45861. return PBRMetallicRoughnessMaterial;
  45862. }(BABYLON.PBRBaseSimpleMaterial));
  45863. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45864. })(BABYLON || (BABYLON = {}));
  45865. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45866. var BABYLON;
  45867. (function (BABYLON) {
  45868. /**
  45869. * The PBR material of BJS following the specular glossiness convention.
  45870. *
  45871. * This fits to the PBR convention in the GLTF definition:
  45872. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45873. */
  45874. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45875. __extends(PBRSpecularGlossinessMaterial, _super);
  45876. /**
  45877. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  45878. *
  45879. * @param name The material name
  45880. * @param scene The scene the material will be use in.
  45881. */
  45882. function PBRSpecularGlossinessMaterial(name, scene) {
  45883. var _this = _super.call(this, name, scene) || this;
  45884. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  45885. return _this;
  45886. }
  45887. /**
  45888. * Return the currrent class name of the material.
  45889. */
  45890. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  45891. return "PBRSpecularGlossinessMaterial";
  45892. };
  45893. /**
  45894. * Return the active textures of the material.
  45895. */
  45896. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  45897. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45898. if (this.diffuseTexture) {
  45899. activeTextures.push(this.diffuseTexture);
  45900. }
  45901. if (this.specularGlossinessTexture) {
  45902. activeTextures.push(this.specularGlossinessTexture);
  45903. }
  45904. return activeTextures;
  45905. };
  45906. /**
  45907. * Checks to see if a texture is used in the material.
  45908. * @param texture - Base texture to use.
  45909. * @returns - Boolean specifying if a texture is used in the material.
  45910. */
  45911. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  45912. if (_super.prototype.hasTexture.call(this, texture)) {
  45913. return true;
  45914. }
  45915. if (this.diffuseTexture === texture) {
  45916. return true;
  45917. }
  45918. if (this.specularGlossinessTexture === texture) {
  45919. return true;
  45920. }
  45921. return false;
  45922. };
  45923. /**
  45924. * Makes a duplicate of the current material.
  45925. * @param name - name to use for the new material.
  45926. */
  45927. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  45928. var _this = this;
  45929. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  45930. clone.id = name;
  45931. clone.name = name;
  45932. return clone;
  45933. };
  45934. /**
  45935. * Serialize the material to a parsable JSON object.
  45936. */
  45937. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  45938. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45939. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  45940. return serializationObject;
  45941. };
  45942. /**
  45943. * Parses a JSON object correponding to the serialize function.
  45944. */
  45945. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  45946. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  45947. };
  45948. __decorate([
  45949. BABYLON.serializeAsColor3("diffuse"),
  45950. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45951. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  45952. __decorate([
  45953. BABYLON.serializeAsTexture(),
  45954. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45955. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  45956. __decorate([
  45957. BABYLON.serializeAsColor3("specular"),
  45958. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  45959. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  45960. __decorate([
  45961. BABYLON.serialize(),
  45962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  45963. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  45964. __decorate([
  45965. BABYLON.serializeAsTexture(),
  45966. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  45967. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  45968. return PBRSpecularGlossinessMaterial;
  45969. }(BABYLON.PBRBaseSimpleMaterial));
  45970. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  45971. })(BABYLON || (BABYLON = {}));
  45972. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  45973. var BABYLON;
  45974. (function (BABYLON) {
  45975. BABYLON.CameraInputTypes = {};
  45976. var CameraInputsManager = /** @class */ (function () {
  45977. function CameraInputsManager(camera) {
  45978. this.attached = {};
  45979. this.camera = camera;
  45980. this.checkInputs = function () { };
  45981. }
  45982. /**
  45983. * Add an input method to a camera.
  45984. * builtin inputs example: camera.inputs.addGamepad();
  45985. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  45986. * @param input camera input method
  45987. */
  45988. CameraInputsManager.prototype.add = function (input) {
  45989. var type = input.getSimpleName();
  45990. if (this.attached[type]) {
  45991. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  45992. return;
  45993. }
  45994. this.attached[type] = input;
  45995. input.camera = this.camera;
  45996. //for checkInputs, we are dynamically creating a function
  45997. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  45998. if (input.checkInputs) {
  45999. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46000. }
  46001. if (this.attachedElement) {
  46002. input.attachControl(this.attachedElement);
  46003. }
  46004. };
  46005. /**
  46006. * Remove a specific input method from a camera
  46007. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46008. * @param inputToRemove camera input method
  46009. */
  46010. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46011. for (var cam in this.attached) {
  46012. var input = this.attached[cam];
  46013. if (input === inputToRemove) {
  46014. input.detachControl(this.attachedElement);
  46015. input.camera = null;
  46016. delete this.attached[cam];
  46017. this.rebuildInputCheck();
  46018. }
  46019. }
  46020. };
  46021. CameraInputsManager.prototype.removeByType = function (inputType) {
  46022. for (var cam in this.attached) {
  46023. var input = this.attached[cam];
  46024. if (input.getClassName() === inputType) {
  46025. input.detachControl(this.attachedElement);
  46026. input.camera = null;
  46027. delete this.attached[cam];
  46028. this.rebuildInputCheck();
  46029. }
  46030. }
  46031. };
  46032. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46033. var current = this.checkInputs;
  46034. return function () {
  46035. current();
  46036. fn();
  46037. };
  46038. };
  46039. CameraInputsManager.prototype.attachInput = function (input) {
  46040. if (this.attachedElement) {
  46041. input.attachControl(this.attachedElement, this.noPreventDefault);
  46042. }
  46043. };
  46044. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46045. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46046. if (this.attachedElement) {
  46047. return;
  46048. }
  46049. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46050. this.attachedElement = element;
  46051. this.noPreventDefault = noPreventDefault;
  46052. for (var cam in this.attached) {
  46053. this.attached[cam].attachControl(element, noPreventDefault);
  46054. }
  46055. };
  46056. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46057. if (disconnect === void 0) { disconnect = false; }
  46058. if (this.attachedElement !== element) {
  46059. return;
  46060. }
  46061. for (var cam in this.attached) {
  46062. this.attached[cam].detachControl(element);
  46063. if (disconnect) {
  46064. this.attached[cam].camera = null;
  46065. }
  46066. }
  46067. this.attachedElement = null;
  46068. };
  46069. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46070. this.checkInputs = function () { };
  46071. for (var cam in this.attached) {
  46072. var input = this.attached[cam];
  46073. if (input.checkInputs) {
  46074. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46075. }
  46076. }
  46077. };
  46078. /**
  46079. * Remove all attached input methods from a camera
  46080. */
  46081. CameraInputsManager.prototype.clear = function () {
  46082. if (this.attachedElement) {
  46083. this.detachElement(this.attachedElement, true);
  46084. }
  46085. this.attached = {};
  46086. this.attachedElement = null;
  46087. this.checkInputs = function () { };
  46088. };
  46089. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46090. var inputs = {};
  46091. for (var cam in this.attached) {
  46092. var input = this.attached[cam];
  46093. var res = BABYLON.SerializationHelper.Serialize(input);
  46094. inputs[input.getClassName()] = res;
  46095. }
  46096. serializedCamera.inputsmgr = inputs;
  46097. };
  46098. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46099. var parsedInputs = parsedCamera.inputsmgr;
  46100. if (parsedInputs) {
  46101. this.clear();
  46102. for (var n in parsedInputs) {
  46103. var construct = BABYLON.CameraInputTypes[n];
  46104. if (construct) {
  46105. var parsedinput = parsedInputs[n];
  46106. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46107. this.add(input);
  46108. }
  46109. }
  46110. }
  46111. else {
  46112. //2016-03-08 this part is for managing backward compatibility
  46113. for (var n in this.attached) {
  46114. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46115. if (construct) {
  46116. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46117. this.remove(this.attached[n]);
  46118. this.add(input);
  46119. }
  46120. }
  46121. }
  46122. };
  46123. return CameraInputsManager;
  46124. }());
  46125. BABYLON.CameraInputsManager = CameraInputsManager;
  46126. })(BABYLON || (BABYLON = {}));
  46127. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46128. var BABYLON;
  46129. (function (BABYLON) {
  46130. var TargetCamera = /** @class */ (function (_super) {
  46131. __extends(TargetCamera, _super);
  46132. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46133. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46134. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46135. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46136. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46137. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46138. _this.speed = 2.0;
  46139. _this.noRotationConstraint = false;
  46140. _this.lockedTarget = null;
  46141. _this._currentTarget = BABYLON.Vector3.Zero();
  46142. _this._viewMatrix = BABYLON.Matrix.Zero();
  46143. _this._camMatrix = BABYLON.Matrix.Zero();
  46144. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46145. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46146. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46147. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46148. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46149. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46150. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46151. return _this;
  46152. }
  46153. TargetCamera.prototype.getFrontPosition = function (distance) {
  46154. this.getWorldMatrix();
  46155. var direction = this.getTarget().subtract(this.position);
  46156. direction.normalize();
  46157. direction.scaleInPlace(distance);
  46158. return this.globalPosition.add(direction);
  46159. };
  46160. TargetCamera.prototype._getLockedTargetPosition = function () {
  46161. if (!this.lockedTarget) {
  46162. return null;
  46163. }
  46164. if (this.lockedTarget.absolutePosition) {
  46165. this.lockedTarget.computeWorldMatrix();
  46166. }
  46167. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46168. };
  46169. TargetCamera.prototype.storeState = function () {
  46170. this._storedPosition = this.position.clone();
  46171. this._storedRotation = this.rotation.clone();
  46172. if (this.rotationQuaternion) {
  46173. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46174. }
  46175. return _super.prototype.storeState.call(this);
  46176. };
  46177. /**
  46178. * Restored camera state. You must call storeState() first
  46179. */
  46180. TargetCamera.prototype._restoreStateValues = function () {
  46181. if (!_super.prototype._restoreStateValues.call(this)) {
  46182. return false;
  46183. }
  46184. this.position = this._storedPosition.clone();
  46185. this.rotation = this._storedRotation.clone();
  46186. if (this.rotationQuaternion) {
  46187. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46188. }
  46189. this.cameraDirection.copyFromFloats(0, 0, 0);
  46190. this.cameraRotation.copyFromFloats(0, 0);
  46191. return true;
  46192. };
  46193. // Cache
  46194. TargetCamera.prototype._initCache = function () {
  46195. _super.prototype._initCache.call(this);
  46196. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46197. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46198. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46199. };
  46200. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46201. if (!ignoreParentClass) {
  46202. _super.prototype._updateCache.call(this);
  46203. }
  46204. var lockedTargetPosition = this._getLockedTargetPosition();
  46205. if (!lockedTargetPosition) {
  46206. this._cache.lockedTarget = null;
  46207. }
  46208. else {
  46209. if (!this._cache.lockedTarget) {
  46210. this._cache.lockedTarget = lockedTargetPosition.clone();
  46211. }
  46212. else {
  46213. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46214. }
  46215. }
  46216. this._cache.rotation.copyFrom(this.rotation);
  46217. if (this.rotationQuaternion)
  46218. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46219. };
  46220. // Synchronized
  46221. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46222. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46223. return false;
  46224. }
  46225. var lockedTargetPosition = this._getLockedTargetPosition();
  46226. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46227. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46228. };
  46229. // Methods
  46230. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46231. var engine = this.getEngine();
  46232. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46233. };
  46234. // Target
  46235. TargetCamera.prototype.setTarget = function (target) {
  46236. this.upVector.normalize();
  46237. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46238. this._camMatrix.invert();
  46239. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46240. var vDir = target.subtract(this.position);
  46241. if (vDir.x >= 0.0) {
  46242. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46243. }
  46244. else {
  46245. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46246. }
  46247. this.rotation.z = 0;
  46248. if (isNaN(this.rotation.x)) {
  46249. this.rotation.x = 0;
  46250. }
  46251. if (isNaN(this.rotation.y)) {
  46252. this.rotation.y = 0;
  46253. }
  46254. if (isNaN(this.rotation.z)) {
  46255. this.rotation.z = 0;
  46256. }
  46257. if (this.rotationQuaternion) {
  46258. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46259. }
  46260. };
  46261. /**
  46262. * Return the current target position of the camera. This value is expressed in local space.
  46263. */
  46264. TargetCamera.prototype.getTarget = function () {
  46265. return this._currentTarget;
  46266. };
  46267. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46268. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46269. };
  46270. TargetCamera.prototype._updatePosition = function () {
  46271. if (this.parent) {
  46272. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46273. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46274. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46275. return;
  46276. }
  46277. this.position.addInPlace(this.cameraDirection);
  46278. };
  46279. TargetCamera.prototype._checkInputs = function () {
  46280. var needToMove = this._decideIfNeedsToMove();
  46281. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46282. // Move
  46283. if (needToMove) {
  46284. this._updatePosition();
  46285. }
  46286. // Rotate
  46287. if (needToRotate) {
  46288. this.rotation.x += this.cameraRotation.x;
  46289. this.rotation.y += this.cameraRotation.y;
  46290. //rotate, if quaternion is set and rotation was used
  46291. if (this.rotationQuaternion) {
  46292. var len = this.rotation.lengthSquared();
  46293. if (len) {
  46294. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46295. }
  46296. }
  46297. if (!this.noRotationConstraint) {
  46298. var limit = (Math.PI / 2) * 0.95;
  46299. if (this.rotation.x > limit)
  46300. this.rotation.x = limit;
  46301. if (this.rotation.x < -limit)
  46302. this.rotation.x = -limit;
  46303. }
  46304. }
  46305. // Inertia
  46306. if (needToMove) {
  46307. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46308. this.cameraDirection.x = 0;
  46309. }
  46310. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46311. this.cameraDirection.y = 0;
  46312. }
  46313. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46314. this.cameraDirection.z = 0;
  46315. }
  46316. this.cameraDirection.scaleInPlace(this.inertia);
  46317. }
  46318. if (needToRotate) {
  46319. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46320. this.cameraRotation.x = 0;
  46321. }
  46322. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46323. this.cameraRotation.y = 0;
  46324. }
  46325. this.cameraRotation.scaleInPlace(this.inertia);
  46326. }
  46327. _super.prototype._checkInputs.call(this);
  46328. };
  46329. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46330. if (this.rotationQuaternion) {
  46331. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46332. }
  46333. else {
  46334. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46335. }
  46336. //update the up vector!
  46337. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46338. };
  46339. TargetCamera.prototype._getViewMatrix = function () {
  46340. if (this.lockedTarget) {
  46341. this.setTarget(this._getLockedTargetPosition());
  46342. }
  46343. // Compute
  46344. this._updateCameraRotationMatrix();
  46345. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46346. // Computing target and final matrix
  46347. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46348. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46349. return this._viewMatrix;
  46350. };
  46351. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46352. if (this.parent) {
  46353. var parentWorldMatrix = this.parent.getWorldMatrix();
  46354. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46355. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46356. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46357. this._markSyncedWithParent();
  46358. }
  46359. else {
  46360. this._globalPosition.copyFrom(this.position);
  46361. this._globalCurrentTarget.copyFrom(target);
  46362. this._globalCurrentUpVector.copyFrom(up);
  46363. }
  46364. if (this.getScene().useRightHandedSystem) {
  46365. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46366. }
  46367. else {
  46368. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46369. }
  46370. };
  46371. /**
  46372. * @override
  46373. * Override Camera.createRigCamera
  46374. */
  46375. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46376. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46377. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46378. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46379. if (!this.rotationQuaternion) {
  46380. this.rotationQuaternion = new BABYLON.Quaternion();
  46381. }
  46382. rigCamera._cameraRigParams = {};
  46383. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46384. }
  46385. return rigCamera;
  46386. }
  46387. return null;
  46388. };
  46389. /**
  46390. * @override
  46391. * Override Camera._updateRigCameras
  46392. */
  46393. TargetCamera.prototype._updateRigCameras = function () {
  46394. var camLeft = this._rigCameras[0];
  46395. var camRight = this._rigCameras[1];
  46396. switch (this.cameraRigMode) {
  46397. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46398. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46399. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46400. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46401. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46402. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46403. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46404. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46405. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46406. camLeft.setTarget(this.getTarget());
  46407. camRight.setTarget(this.getTarget());
  46408. break;
  46409. case BABYLON.Camera.RIG_MODE_VR:
  46410. if (camLeft.rotationQuaternion) {
  46411. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46412. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46413. }
  46414. else {
  46415. camLeft.rotation.copyFrom(this.rotation);
  46416. camRight.rotation.copyFrom(this.rotation);
  46417. }
  46418. camLeft.position.copyFrom(this.position);
  46419. camRight.position.copyFrom(this.position);
  46420. break;
  46421. }
  46422. _super.prototype._updateRigCameras.call(this);
  46423. };
  46424. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46425. if (!this._rigCamTransformMatrix) {
  46426. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46427. }
  46428. var target = this.getTarget();
  46429. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46430. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46431. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46432. };
  46433. TargetCamera.prototype.getClassName = function () {
  46434. return "TargetCamera";
  46435. };
  46436. __decorate([
  46437. BABYLON.serializeAsVector3()
  46438. ], TargetCamera.prototype, "rotation", void 0);
  46439. __decorate([
  46440. BABYLON.serialize()
  46441. ], TargetCamera.prototype, "speed", void 0);
  46442. __decorate([
  46443. BABYLON.serializeAsMeshReference("lockedTargetId")
  46444. ], TargetCamera.prototype, "lockedTarget", void 0);
  46445. return TargetCamera;
  46446. }(BABYLON.Camera));
  46447. BABYLON.TargetCamera = TargetCamera;
  46448. })(BABYLON || (BABYLON = {}));
  46449. //# sourceMappingURL=babylon.targetCamera.js.map
  46450. var BABYLON;
  46451. (function (BABYLON) {
  46452. var FreeCameraMouseInput = /** @class */ (function () {
  46453. function FreeCameraMouseInput(touchEnabled) {
  46454. if (touchEnabled === void 0) { touchEnabled = true; }
  46455. this.touchEnabled = touchEnabled;
  46456. this.buttons = [0, 1, 2];
  46457. this.angularSensibility = 2000.0;
  46458. this.previousPosition = null;
  46459. }
  46460. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46461. var _this = this;
  46462. var engine = this.camera.getEngine();
  46463. if (!this._pointerInput) {
  46464. this._pointerInput = function (p, s) {
  46465. var evt = p.event;
  46466. if (engine.isInVRExclusivePointerMode) {
  46467. return;
  46468. }
  46469. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46470. return;
  46471. }
  46472. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46473. return;
  46474. }
  46475. var srcElement = (evt.srcElement || evt.target);
  46476. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46477. try {
  46478. srcElement.setPointerCapture(evt.pointerId);
  46479. }
  46480. catch (e) {
  46481. //Nothing to do with the error. Execution will continue.
  46482. }
  46483. _this.previousPosition = {
  46484. x: evt.clientX,
  46485. y: evt.clientY
  46486. };
  46487. if (!noPreventDefault) {
  46488. evt.preventDefault();
  46489. element.focus();
  46490. }
  46491. }
  46492. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46493. try {
  46494. srcElement.releasePointerCapture(evt.pointerId);
  46495. }
  46496. catch (e) {
  46497. //Nothing to do with the error.
  46498. }
  46499. _this.previousPosition = null;
  46500. if (!noPreventDefault) {
  46501. evt.preventDefault();
  46502. }
  46503. }
  46504. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46505. if (!_this.previousPosition || engine.isPointerLock) {
  46506. return;
  46507. }
  46508. var offsetX = evt.clientX - _this.previousPosition.x;
  46509. if (_this.camera.getScene().useRightHandedSystem)
  46510. offsetX *= -1;
  46511. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46512. offsetX *= -1;
  46513. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46514. var offsetY = evt.clientY - _this.previousPosition.y;
  46515. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46516. _this.previousPosition = {
  46517. x: evt.clientX,
  46518. y: evt.clientY
  46519. };
  46520. if (!noPreventDefault) {
  46521. evt.preventDefault();
  46522. }
  46523. }
  46524. };
  46525. }
  46526. this._onMouseMove = function (evt) {
  46527. if (!engine.isPointerLock) {
  46528. return;
  46529. }
  46530. if (engine.isInVRExclusivePointerMode) {
  46531. return;
  46532. }
  46533. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46534. if (_this.camera.getScene().useRightHandedSystem)
  46535. offsetX *= -1;
  46536. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46537. offsetX *= -1;
  46538. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46539. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46540. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46541. _this.previousPosition = null;
  46542. if (!noPreventDefault) {
  46543. evt.preventDefault();
  46544. }
  46545. };
  46546. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46547. element.addEventListener("mousemove", this._onMouseMove, false);
  46548. };
  46549. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46550. if (this._observer && element) {
  46551. this.camera.getScene().onPointerObservable.remove(this._observer);
  46552. if (this._onMouseMove) {
  46553. element.removeEventListener("mousemove", this._onMouseMove);
  46554. }
  46555. this._observer = null;
  46556. this._onMouseMove = null;
  46557. this.previousPosition = null;
  46558. }
  46559. };
  46560. FreeCameraMouseInput.prototype.getClassName = function () {
  46561. return "FreeCameraMouseInput";
  46562. };
  46563. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46564. return "mouse";
  46565. };
  46566. __decorate([
  46567. BABYLON.serialize()
  46568. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46569. __decorate([
  46570. BABYLON.serialize()
  46571. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46572. return FreeCameraMouseInput;
  46573. }());
  46574. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46575. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46576. })(BABYLON || (BABYLON = {}));
  46577. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46578. var BABYLON;
  46579. (function (BABYLON) {
  46580. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46581. function FreeCameraKeyboardMoveInput() {
  46582. this._keys = new Array();
  46583. this.keysUp = [38];
  46584. this.keysDown = [40];
  46585. this.keysLeft = [37];
  46586. this.keysRight = [39];
  46587. }
  46588. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46589. var _this = this;
  46590. if (this._onCanvasBlurObserver) {
  46591. return;
  46592. }
  46593. this._scene = this.camera.getScene();
  46594. this._engine = this._scene.getEngine();
  46595. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46596. _this._keys = [];
  46597. });
  46598. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46599. var evt = info.event;
  46600. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46601. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46602. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46603. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46604. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46605. var index = _this._keys.indexOf(evt.keyCode);
  46606. if (index === -1) {
  46607. _this._keys.push(evt.keyCode);
  46608. }
  46609. if (!noPreventDefault) {
  46610. evt.preventDefault();
  46611. }
  46612. }
  46613. }
  46614. else {
  46615. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46616. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46617. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46618. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46619. var index = _this._keys.indexOf(evt.keyCode);
  46620. if (index >= 0) {
  46621. _this._keys.splice(index, 1);
  46622. }
  46623. if (!noPreventDefault) {
  46624. evt.preventDefault();
  46625. }
  46626. }
  46627. }
  46628. });
  46629. };
  46630. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46631. if (this._scene) {
  46632. if (this._onKeyboardObserver) {
  46633. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46634. }
  46635. if (this._onCanvasBlurObserver) {
  46636. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46637. }
  46638. this._onKeyboardObserver = null;
  46639. this._onCanvasBlurObserver = null;
  46640. }
  46641. this._keys = [];
  46642. };
  46643. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46644. if (this._onKeyboardObserver) {
  46645. var camera = this.camera;
  46646. // Keyboard
  46647. for (var index = 0; index < this._keys.length; index++) {
  46648. var keyCode = this._keys[index];
  46649. var speed = camera._computeLocalCameraSpeed();
  46650. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46651. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46652. }
  46653. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46654. camera._localDirection.copyFromFloats(0, 0, speed);
  46655. }
  46656. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46657. camera._localDirection.copyFromFloats(speed, 0, 0);
  46658. }
  46659. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46660. camera._localDirection.copyFromFloats(0, 0, -speed);
  46661. }
  46662. if (camera.getScene().useRightHandedSystem) {
  46663. camera._localDirection.z *= -1;
  46664. }
  46665. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46666. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46667. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46668. }
  46669. }
  46670. };
  46671. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46672. return "FreeCameraKeyboardMoveInput";
  46673. };
  46674. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46675. this._keys = [];
  46676. };
  46677. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46678. return "keyboard";
  46679. };
  46680. __decorate([
  46681. BABYLON.serialize()
  46682. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46683. __decorate([
  46684. BABYLON.serialize()
  46685. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46686. __decorate([
  46687. BABYLON.serialize()
  46688. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46689. __decorate([
  46690. BABYLON.serialize()
  46691. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46692. return FreeCameraKeyboardMoveInput;
  46693. }());
  46694. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46695. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46696. })(BABYLON || (BABYLON = {}));
  46697. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46698. var BABYLON;
  46699. (function (BABYLON) {
  46700. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46701. __extends(FreeCameraInputsManager, _super);
  46702. function FreeCameraInputsManager(camera) {
  46703. return _super.call(this, camera) || this;
  46704. }
  46705. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46706. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46707. return this;
  46708. };
  46709. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46710. if (touchEnabled === void 0) { touchEnabled = true; }
  46711. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46712. return this;
  46713. };
  46714. FreeCameraInputsManager.prototype.addGamepad = function () {
  46715. this.add(new BABYLON.FreeCameraGamepadInput());
  46716. return this;
  46717. };
  46718. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46719. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46720. return this;
  46721. };
  46722. FreeCameraInputsManager.prototype.addTouch = function () {
  46723. this.add(new BABYLON.FreeCameraTouchInput());
  46724. return this;
  46725. };
  46726. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46727. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46728. return this;
  46729. };
  46730. return FreeCameraInputsManager;
  46731. }(BABYLON.CameraInputsManager));
  46732. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46733. })(BABYLON || (BABYLON = {}));
  46734. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46735. var BABYLON;
  46736. (function (BABYLON) {
  46737. var FreeCamera = /** @class */ (function (_super) {
  46738. __extends(FreeCamera, _super);
  46739. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46740. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46741. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46742. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46743. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46744. _this.checkCollisions = false;
  46745. _this.applyGravity = false;
  46746. _this._needMoveForGravity = false;
  46747. _this._oldPosition = BABYLON.Vector3.Zero();
  46748. _this._diffPosition = BABYLON.Vector3.Zero();
  46749. _this._newPosition = BABYLON.Vector3.Zero();
  46750. // Collisions
  46751. _this._collisionMask = -1;
  46752. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46753. if (collidedMesh === void 0) { collidedMesh = null; }
  46754. //TODO move this to the collision coordinator!
  46755. if (_this.getScene().workerCollisions)
  46756. newPosition.multiplyInPlace(_this._collider._radius);
  46757. var updatePosition = function (newPos) {
  46758. _this._newPosition.copyFrom(newPos);
  46759. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46760. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46761. _this.position.addInPlace(_this._diffPosition);
  46762. if (_this.onCollide && collidedMesh) {
  46763. _this.onCollide(collidedMesh);
  46764. }
  46765. }
  46766. };
  46767. updatePosition(newPosition);
  46768. };
  46769. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46770. _this.inputs.addKeyboard().addMouse();
  46771. return _this;
  46772. }
  46773. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46774. //-- begin properties for backward compatibility for inputs
  46775. /**
  46776. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46777. * Higher values reduce sensitivity.
  46778. */
  46779. get: function () {
  46780. var mouse = this.inputs.attached["mouse"];
  46781. if (mouse)
  46782. return mouse.angularSensibility;
  46783. return 0;
  46784. },
  46785. /**
  46786. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46787. * Higher values reduce sensitivity.
  46788. */
  46789. set: function (value) {
  46790. var mouse = this.inputs.attached["mouse"];
  46791. if (mouse)
  46792. mouse.angularSensibility = value;
  46793. },
  46794. enumerable: true,
  46795. configurable: true
  46796. });
  46797. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46798. get: function () {
  46799. var keyboard = this.inputs.attached["keyboard"];
  46800. if (keyboard)
  46801. return keyboard.keysUp;
  46802. return [];
  46803. },
  46804. set: function (value) {
  46805. var keyboard = this.inputs.attached["keyboard"];
  46806. if (keyboard)
  46807. keyboard.keysUp = value;
  46808. },
  46809. enumerable: true,
  46810. configurable: true
  46811. });
  46812. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46813. get: function () {
  46814. var keyboard = this.inputs.attached["keyboard"];
  46815. if (keyboard)
  46816. return keyboard.keysDown;
  46817. return [];
  46818. },
  46819. set: function (value) {
  46820. var keyboard = this.inputs.attached["keyboard"];
  46821. if (keyboard)
  46822. keyboard.keysDown = value;
  46823. },
  46824. enumerable: true,
  46825. configurable: true
  46826. });
  46827. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46828. get: function () {
  46829. var keyboard = this.inputs.attached["keyboard"];
  46830. if (keyboard)
  46831. return keyboard.keysLeft;
  46832. return [];
  46833. },
  46834. set: function (value) {
  46835. var keyboard = this.inputs.attached["keyboard"];
  46836. if (keyboard)
  46837. keyboard.keysLeft = value;
  46838. },
  46839. enumerable: true,
  46840. configurable: true
  46841. });
  46842. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46843. get: function () {
  46844. var keyboard = this.inputs.attached["keyboard"];
  46845. if (keyboard)
  46846. return keyboard.keysRight;
  46847. return [];
  46848. },
  46849. set: function (value) {
  46850. var keyboard = this.inputs.attached["keyboard"];
  46851. if (keyboard)
  46852. keyboard.keysRight = value;
  46853. },
  46854. enumerable: true,
  46855. configurable: true
  46856. });
  46857. // Controls
  46858. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46859. this.inputs.attachElement(element, noPreventDefault);
  46860. };
  46861. FreeCamera.prototype.detachControl = function (element) {
  46862. this.inputs.detachElement(element);
  46863. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46864. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46865. };
  46866. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46867. get: function () {
  46868. return this._collisionMask;
  46869. },
  46870. set: function (mask) {
  46871. this._collisionMask = !isNaN(mask) ? mask : -1;
  46872. },
  46873. enumerable: true,
  46874. configurable: true
  46875. });
  46876. FreeCamera.prototype._collideWithWorld = function (displacement) {
  46877. var globalPosition;
  46878. if (this.parent) {
  46879. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  46880. }
  46881. else {
  46882. globalPosition = this.position;
  46883. }
  46884. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  46885. this._oldPosition.addInPlace(this.ellipsoidOffset);
  46886. if (!this._collider) {
  46887. this._collider = new BABYLON.Collider();
  46888. }
  46889. this._collider._radius = this.ellipsoid;
  46890. this._collider.collisionMask = this._collisionMask;
  46891. //no need for clone, as long as gravity is not on.
  46892. var actualDisplacement = displacement;
  46893. //add gravity to the direction to prevent the dual-collision checking
  46894. if (this.applyGravity) {
  46895. //this prevents mending with cameraDirection, a global variable of the free camera class.
  46896. actualDisplacement = displacement.add(this.getScene().gravity);
  46897. }
  46898. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  46899. };
  46900. FreeCamera.prototype._checkInputs = function () {
  46901. if (!this._localDirection) {
  46902. this._localDirection = BABYLON.Vector3.Zero();
  46903. this._transformedDirection = BABYLON.Vector3.Zero();
  46904. }
  46905. this.inputs.checkInputs();
  46906. _super.prototype._checkInputs.call(this);
  46907. };
  46908. FreeCamera.prototype._decideIfNeedsToMove = function () {
  46909. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46910. };
  46911. FreeCamera.prototype._updatePosition = function () {
  46912. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  46913. this._collideWithWorld(this.cameraDirection);
  46914. }
  46915. else {
  46916. _super.prototype._updatePosition.call(this);
  46917. }
  46918. };
  46919. FreeCamera.prototype.dispose = function () {
  46920. this.inputs.clear();
  46921. _super.prototype.dispose.call(this);
  46922. };
  46923. FreeCamera.prototype.getClassName = function () {
  46924. return "FreeCamera";
  46925. };
  46926. __decorate([
  46927. BABYLON.serializeAsVector3()
  46928. ], FreeCamera.prototype, "ellipsoid", void 0);
  46929. __decorate([
  46930. BABYLON.serializeAsVector3()
  46931. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  46932. __decorate([
  46933. BABYLON.serialize()
  46934. ], FreeCamera.prototype, "checkCollisions", void 0);
  46935. __decorate([
  46936. BABYLON.serialize()
  46937. ], FreeCamera.prototype, "applyGravity", void 0);
  46938. return FreeCamera;
  46939. }(BABYLON.TargetCamera));
  46940. BABYLON.FreeCamera = FreeCamera;
  46941. })(BABYLON || (BABYLON = {}));
  46942. //# sourceMappingURL=babylon.freeCamera.js.map
  46943. var BABYLON;
  46944. (function (BABYLON) {
  46945. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  46946. function ArcRotateCameraKeyboardMoveInput() {
  46947. this._keys = new Array();
  46948. this.keysUp = [38];
  46949. this.keysDown = [40];
  46950. this.keysLeft = [37];
  46951. this.keysRight = [39];
  46952. this.keysReset = [220];
  46953. this.panningSensibility = 50.0;
  46954. this.zoomingSensibility = 25.0;
  46955. this.useAltToZoom = true;
  46956. }
  46957. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46958. var _this = this;
  46959. if (this._onCanvasBlurObserver) {
  46960. return;
  46961. }
  46962. this._scene = this.camera.getScene();
  46963. this._engine = this._scene.getEngine();
  46964. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46965. _this._keys = [];
  46966. });
  46967. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46968. var evt = info.event;
  46969. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46970. _this._ctrlPressed = evt.ctrlKey;
  46971. _this._altPressed = evt.altKey;
  46972. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46973. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46974. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46975. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46976. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46977. var index = _this._keys.indexOf(evt.keyCode);
  46978. if (index === -1) {
  46979. _this._keys.push(evt.keyCode);
  46980. }
  46981. if (evt.preventDefault) {
  46982. if (!noPreventDefault) {
  46983. evt.preventDefault();
  46984. }
  46985. }
  46986. }
  46987. }
  46988. else {
  46989. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46990. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46991. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46992. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  46993. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  46994. var index = _this._keys.indexOf(evt.keyCode);
  46995. if (index >= 0) {
  46996. _this._keys.splice(index, 1);
  46997. }
  46998. if (evt.preventDefault) {
  46999. if (!noPreventDefault) {
  47000. evt.preventDefault();
  47001. }
  47002. }
  47003. }
  47004. }
  47005. });
  47006. };
  47007. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47008. if (this._scene) {
  47009. if (this._onKeyboardObserver) {
  47010. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47011. }
  47012. if (this._onCanvasBlurObserver) {
  47013. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47014. }
  47015. this._onKeyboardObserver = null;
  47016. this._onCanvasBlurObserver = null;
  47017. }
  47018. this._keys = [];
  47019. };
  47020. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47021. if (this._onKeyboardObserver) {
  47022. var camera = this.camera;
  47023. for (var index = 0; index < this._keys.length; index++) {
  47024. var keyCode = this._keys[index];
  47025. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47026. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47027. camera.inertialPanningX -= 1 / this.panningSensibility;
  47028. }
  47029. else {
  47030. camera.inertialAlphaOffset -= 0.01;
  47031. }
  47032. }
  47033. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47034. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47035. camera.inertialPanningY += 1 / this.panningSensibility;
  47036. }
  47037. else if (this._altPressed && this.useAltToZoom) {
  47038. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47039. }
  47040. else {
  47041. camera.inertialBetaOffset -= 0.01;
  47042. }
  47043. }
  47044. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47045. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47046. camera.inertialPanningX += 1 / this.panningSensibility;
  47047. }
  47048. else {
  47049. camera.inertialAlphaOffset += 0.01;
  47050. }
  47051. }
  47052. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47053. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47054. camera.inertialPanningY -= 1 / this.panningSensibility;
  47055. }
  47056. else if (this._altPressed && this.useAltToZoom) {
  47057. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47058. }
  47059. else {
  47060. camera.inertialBetaOffset += 0.01;
  47061. }
  47062. }
  47063. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47064. camera.restoreState();
  47065. }
  47066. }
  47067. }
  47068. };
  47069. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47070. return "ArcRotateCameraKeyboardMoveInput";
  47071. };
  47072. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47073. return "keyboard";
  47074. };
  47075. __decorate([
  47076. BABYLON.serialize()
  47077. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47078. __decorate([
  47079. BABYLON.serialize()
  47080. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47081. __decorate([
  47082. BABYLON.serialize()
  47083. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47084. __decorate([
  47085. BABYLON.serialize()
  47086. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47087. __decorate([
  47088. BABYLON.serialize()
  47089. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47090. __decorate([
  47091. BABYLON.serialize()
  47092. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47093. __decorate([
  47094. BABYLON.serialize()
  47095. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47096. __decorate([
  47097. BABYLON.serialize()
  47098. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47099. return ArcRotateCameraKeyboardMoveInput;
  47100. }());
  47101. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47102. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47103. })(BABYLON || (BABYLON = {}));
  47104. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47105. var BABYLON;
  47106. (function (BABYLON) {
  47107. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47108. function ArcRotateCameraMouseWheelInput() {
  47109. this.wheelPrecision = 3.0;
  47110. /**
  47111. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47112. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47113. */
  47114. this.wheelDeltaPercentage = 0;
  47115. }
  47116. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47117. var _this = this;
  47118. this._wheel = function (p, s) {
  47119. //sanity check - this should be a PointerWheel event.
  47120. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47121. return;
  47122. var event = p.event;
  47123. var delta = 0;
  47124. if (event.wheelDelta) {
  47125. if (_this.wheelDeltaPercentage) {
  47126. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47127. if (event.wheelDelta > 0) {
  47128. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47129. }
  47130. else {
  47131. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47132. }
  47133. }
  47134. else {
  47135. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47136. }
  47137. }
  47138. else if (event.detail) {
  47139. delta = -event.detail / _this.wheelPrecision;
  47140. }
  47141. if (delta)
  47142. _this.camera.inertialRadiusOffset += delta;
  47143. if (event.preventDefault) {
  47144. if (!noPreventDefault) {
  47145. event.preventDefault();
  47146. }
  47147. }
  47148. };
  47149. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47150. };
  47151. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47152. if (this._observer && element) {
  47153. this.camera.getScene().onPointerObservable.remove(this._observer);
  47154. this._observer = null;
  47155. this._wheel = null;
  47156. }
  47157. };
  47158. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47159. return "ArcRotateCameraMouseWheelInput";
  47160. };
  47161. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47162. return "mousewheel";
  47163. };
  47164. __decorate([
  47165. BABYLON.serialize()
  47166. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47167. __decorate([
  47168. BABYLON.serialize()
  47169. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47170. return ArcRotateCameraMouseWheelInput;
  47171. }());
  47172. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47173. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47174. })(BABYLON || (BABYLON = {}));
  47175. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47176. var BABYLON;
  47177. (function (BABYLON) {
  47178. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47179. function ArcRotateCameraPointersInput() {
  47180. this.buttons = [0, 1, 2];
  47181. this.angularSensibilityX = 1000.0;
  47182. this.angularSensibilityY = 1000.0;
  47183. this.pinchPrecision = 12.0;
  47184. /**
  47185. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47186. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47187. */
  47188. this.pinchDeltaPercentage = 0;
  47189. this.panningSensibility = 1000.0;
  47190. this.multiTouchPanning = true;
  47191. this.multiTouchPanAndZoom = true;
  47192. this._isPanClick = false;
  47193. this.pinchInwards = true;
  47194. }
  47195. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47196. var _this = this;
  47197. var engine = this.camera.getEngine();
  47198. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47199. var pointA = null;
  47200. var pointB = null;
  47201. var previousPinchSquaredDistance = 0;
  47202. var initialDistance = 0;
  47203. var twoFingerActivityCount = 0;
  47204. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47205. this._pointerInput = function (p, s) {
  47206. var evt = p.event;
  47207. var isTouch = p.event.pointerType === "touch";
  47208. if (engine.isInVRExclusivePointerMode) {
  47209. return;
  47210. }
  47211. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47212. return;
  47213. }
  47214. var srcElement = (evt.srcElement || evt.target);
  47215. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47216. try {
  47217. srcElement.setPointerCapture(evt.pointerId);
  47218. }
  47219. catch (e) {
  47220. //Nothing to do with the error. Execution will continue.
  47221. }
  47222. // Manage panning with pan button click
  47223. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47224. // manage pointers
  47225. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47226. if (pointA === null) {
  47227. pointA = cacheSoloPointer;
  47228. }
  47229. else if (pointB === null) {
  47230. pointB = cacheSoloPointer;
  47231. }
  47232. if (!noPreventDefault) {
  47233. evt.preventDefault();
  47234. element.focus();
  47235. }
  47236. }
  47237. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47238. _this.camera.restoreState();
  47239. }
  47240. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47241. try {
  47242. srcElement.releasePointerCapture(evt.pointerId);
  47243. }
  47244. catch (e) {
  47245. //Nothing to do with the error.
  47246. }
  47247. cacheSoloPointer = null;
  47248. previousPinchSquaredDistance = 0;
  47249. previousMultiTouchPanPosition.isPaning = false;
  47250. previousMultiTouchPanPosition.isPinching = false;
  47251. twoFingerActivityCount = 0;
  47252. initialDistance = 0;
  47253. if (!isTouch) {
  47254. pointB = null; // Mouse and pen are mono pointer
  47255. }
  47256. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47257. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47258. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47259. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47260. if (engine._badOS) {
  47261. pointA = pointB = null;
  47262. }
  47263. else {
  47264. //only remove the impacted pointer in case of multitouch allowing on most
  47265. //platforms switching from rotate to zoom and pan seamlessly.
  47266. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47267. pointA = pointB;
  47268. pointB = null;
  47269. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47270. }
  47271. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47272. pointB = null;
  47273. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47274. }
  47275. else {
  47276. pointA = pointB = null;
  47277. }
  47278. }
  47279. if (!noPreventDefault) {
  47280. evt.preventDefault();
  47281. }
  47282. }
  47283. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47284. if (!noPreventDefault) {
  47285. evt.preventDefault();
  47286. }
  47287. // One button down
  47288. if (pointA && pointB === null && cacheSoloPointer) {
  47289. if (_this.panningSensibility !== 0 &&
  47290. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47291. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47292. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47293. }
  47294. else {
  47295. var offsetX = evt.clientX - cacheSoloPointer.x;
  47296. var offsetY = evt.clientY - cacheSoloPointer.y;
  47297. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47298. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47299. }
  47300. cacheSoloPointer.x = evt.clientX;
  47301. cacheSoloPointer.y = evt.clientY;
  47302. }
  47303. // Two buttons down: pinch/pan
  47304. else if (pointA && pointB) {
  47305. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47306. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47307. ed.x = evt.clientX;
  47308. ed.y = evt.clientY;
  47309. var direction = _this.pinchInwards ? 1 : -1;
  47310. var distX = pointA.x - pointB.x;
  47311. var distY = pointA.y - pointB.y;
  47312. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47313. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47314. if (previousPinchSquaredDistance === 0) {
  47315. initialDistance = pinchDistance;
  47316. previousPinchSquaredDistance = pinchSquaredDistance;
  47317. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47318. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47319. return;
  47320. }
  47321. if (_this.multiTouchPanAndZoom) {
  47322. if (_this.pinchDeltaPercentage) {
  47323. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47324. }
  47325. else {
  47326. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47327. (_this.pinchPrecision *
  47328. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47329. direction);
  47330. }
  47331. if (_this.panningSensibility !== 0) {
  47332. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47333. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47334. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47335. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47336. previousMultiTouchPanPosition.x = pointersCenterX;
  47337. previousMultiTouchPanPosition.y = pointersCenterY;
  47338. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47339. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47340. }
  47341. }
  47342. else {
  47343. twoFingerActivityCount++;
  47344. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47345. if (_this.pinchDeltaPercentage) {
  47346. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47347. }
  47348. else {
  47349. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47350. (_this.pinchPrecision *
  47351. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47352. direction);
  47353. }
  47354. previousMultiTouchPanPosition.isPaning = false;
  47355. previousMultiTouchPanPosition.isPinching = true;
  47356. }
  47357. else {
  47358. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47359. if (!previousMultiTouchPanPosition.isPaning) {
  47360. previousMultiTouchPanPosition.isPaning = true;
  47361. previousMultiTouchPanPosition.isPinching = false;
  47362. previousMultiTouchPanPosition.x = ed.x;
  47363. previousMultiTouchPanPosition.y = ed.y;
  47364. return;
  47365. }
  47366. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47367. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47368. }
  47369. }
  47370. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47371. previousMultiTouchPanPosition.x = ed.x;
  47372. previousMultiTouchPanPosition.y = ed.y;
  47373. }
  47374. }
  47375. previousPinchSquaredDistance = pinchSquaredDistance;
  47376. }
  47377. }
  47378. };
  47379. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47380. this._onContextMenu = function (evt) {
  47381. evt.preventDefault();
  47382. };
  47383. if (!this.camera._useCtrlForPanning) {
  47384. element.addEventListener("contextmenu", this._onContextMenu, false);
  47385. }
  47386. this._onLostFocus = function () {
  47387. //this._keys = [];
  47388. pointA = pointB = null;
  47389. previousPinchSquaredDistance = 0;
  47390. previousMultiTouchPanPosition.isPaning = false;
  47391. previousMultiTouchPanPosition.isPinching = false;
  47392. twoFingerActivityCount = 0;
  47393. cacheSoloPointer = null;
  47394. initialDistance = 0;
  47395. };
  47396. this._onMouseMove = function (evt) {
  47397. if (!engine.isPointerLock) {
  47398. return;
  47399. }
  47400. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47401. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47402. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47403. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47404. if (!noPreventDefault) {
  47405. evt.preventDefault();
  47406. }
  47407. };
  47408. this._onGestureStart = function (e) {
  47409. if (window.MSGesture === undefined) {
  47410. return;
  47411. }
  47412. if (!_this._MSGestureHandler) {
  47413. _this._MSGestureHandler = new MSGesture();
  47414. _this._MSGestureHandler.target = element;
  47415. }
  47416. _this._MSGestureHandler.addPointer(e.pointerId);
  47417. };
  47418. this._onGesture = function (e) {
  47419. _this.camera.radius *= e.scale;
  47420. if (e.preventDefault) {
  47421. if (!noPreventDefault) {
  47422. e.stopPropagation();
  47423. e.preventDefault();
  47424. }
  47425. }
  47426. };
  47427. element.addEventListener("mousemove", this._onMouseMove, false);
  47428. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47429. element.addEventListener("MSGestureChange", this._onGesture, false);
  47430. BABYLON.Tools.RegisterTopRootEvents([
  47431. { name: "blur", handler: this._onLostFocus }
  47432. ]);
  47433. };
  47434. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47435. if (this._onLostFocus) {
  47436. BABYLON.Tools.UnregisterTopRootEvents([
  47437. { name: "blur", handler: this._onLostFocus }
  47438. ]);
  47439. }
  47440. if (element && this._observer) {
  47441. this.camera.getScene().onPointerObservable.remove(this._observer);
  47442. this._observer = null;
  47443. if (this._onContextMenu) {
  47444. element.removeEventListener("contextmenu", this._onContextMenu);
  47445. }
  47446. if (this._onMouseMove) {
  47447. element.removeEventListener("mousemove", this._onMouseMove);
  47448. }
  47449. if (this._onGestureStart) {
  47450. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47451. }
  47452. if (this._onGesture) {
  47453. element.removeEventListener("MSGestureChange", this._onGesture);
  47454. }
  47455. this._isPanClick = false;
  47456. this.pinchInwards = true;
  47457. this._onMouseMove = null;
  47458. this._onGestureStart = null;
  47459. this._onGesture = null;
  47460. this._MSGestureHandler = null;
  47461. this._onLostFocus = null;
  47462. this._onContextMenu = null;
  47463. }
  47464. };
  47465. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47466. return "ArcRotateCameraPointersInput";
  47467. };
  47468. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47469. return "pointers";
  47470. };
  47471. __decorate([
  47472. BABYLON.serialize()
  47473. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47474. __decorate([
  47475. BABYLON.serialize()
  47476. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47477. __decorate([
  47478. BABYLON.serialize()
  47479. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47480. __decorate([
  47481. BABYLON.serialize()
  47482. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47483. __decorate([
  47484. BABYLON.serialize()
  47485. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47486. __decorate([
  47487. BABYLON.serialize()
  47488. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47489. __decorate([
  47490. BABYLON.serialize()
  47491. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47492. __decorate([
  47493. BABYLON.serialize()
  47494. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47495. return ArcRotateCameraPointersInput;
  47496. }());
  47497. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47498. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47499. })(BABYLON || (BABYLON = {}));
  47500. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47501. var BABYLON;
  47502. (function (BABYLON) {
  47503. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47504. __extends(ArcRotateCameraInputsManager, _super);
  47505. function ArcRotateCameraInputsManager(camera) {
  47506. return _super.call(this, camera) || this;
  47507. }
  47508. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47509. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47510. return this;
  47511. };
  47512. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47513. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47514. return this;
  47515. };
  47516. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47517. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47518. return this;
  47519. };
  47520. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47521. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47522. return this;
  47523. };
  47524. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47525. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47526. return this;
  47527. };
  47528. return ArcRotateCameraInputsManager;
  47529. }(BABYLON.CameraInputsManager));
  47530. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47531. })(BABYLON || (BABYLON = {}));
  47532. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47533. var BABYLON;
  47534. (function (BABYLON) {
  47535. var ArcRotateCamera = /** @class */ (function (_super) {
  47536. __extends(ArcRotateCamera, _super);
  47537. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47538. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47539. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47540. _this.inertialAlphaOffset = 0;
  47541. _this.inertialBetaOffset = 0;
  47542. _this.inertialRadiusOffset = 0;
  47543. _this.lowerAlphaLimit = null;
  47544. _this.upperAlphaLimit = null;
  47545. _this.lowerBetaLimit = 0.01;
  47546. _this.upperBetaLimit = Math.PI;
  47547. _this.lowerRadiusLimit = null;
  47548. _this.upperRadiusLimit = null;
  47549. _this.inertialPanningX = 0;
  47550. _this.inertialPanningY = 0;
  47551. _this.pinchToPanMaxDistance = 20;
  47552. _this.panningDistanceLimit = null;
  47553. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47554. _this.panningInertia = 0.9;
  47555. //-- end properties for backward compatibility for inputs
  47556. _this.zoomOnFactor = 1;
  47557. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47558. _this.allowUpsideDown = true;
  47559. _this._viewMatrix = new BABYLON.Matrix();
  47560. // Panning
  47561. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47562. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47563. _this.checkCollisions = false;
  47564. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47565. _this._previousPosition = BABYLON.Vector3.Zero();
  47566. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47567. _this._newPosition = BABYLON.Vector3.Zero();
  47568. _this._computationVector = BABYLON.Vector3.Zero();
  47569. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47570. if (collidedMesh === void 0) { collidedMesh = null; }
  47571. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47572. newPosition.multiplyInPlace(_this._collider._radius);
  47573. }
  47574. if (!collidedMesh) {
  47575. _this._previousPosition.copyFrom(_this.position);
  47576. }
  47577. else {
  47578. _this.setPosition(newPosition);
  47579. if (_this.onCollide) {
  47580. _this.onCollide(collidedMesh);
  47581. }
  47582. }
  47583. // Recompute because of constraints
  47584. var cosa = Math.cos(_this.alpha);
  47585. var sina = Math.sin(_this.alpha);
  47586. var cosb = Math.cos(_this.beta);
  47587. var sinb = Math.sin(_this.beta);
  47588. if (sinb === 0) {
  47589. sinb = 0.0001;
  47590. }
  47591. var target = _this._getTargetPosition();
  47592. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47593. target.addToRef(_this._computationVector, _this._newPosition);
  47594. _this.position.copyFrom(_this._newPosition);
  47595. var up = _this.upVector;
  47596. if (_this.allowUpsideDown && _this.beta < 0) {
  47597. up = up.clone();
  47598. up = up.negate();
  47599. }
  47600. _this._computeViewMatrix(_this.position, target, up);
  47601. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47602. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47603. _this._collisionTriggered = false;
  47604. };
  47605. _this._target = BABYLON.Vector3.Zero();
  47606. if (target) {
  47607. _this.setTarget(target);
  47608. }
  47609. _this.alpha = alpha;
  47610. _this.beta = beta;
  47611. _this.radius = radius;
  47612. _this.getViewMatrix();
  47613. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47614. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47615. return _this;
  47616. }
  47617. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47618. get: function () {
  47619. return this._target;
  47620. },
  47621. set: function (value) {
  47622. this.setTarget(value);
  47623. },
  47624. enumerable: true,
  47625. configurable: true
  47626. });
  47627. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47628. //-- begin properties for backward compatibility for inputs
  47629. get: function () {
  47630. var pointers = this.inputs.attached["pointers"];
  47631. if (pointers)
  47632. return pointers.angularSensibilityX;
  47633. return 0;
  47634. },
  47635. set: function (value) {
  47636. var pointers = this.inputs.attached["pointers"];
  47637. if (pointers) {
  47638. pointers.angularSensibilityX = value;
  47639. }
  47640. },
  47641. enumerable: true,
  47642. configurable: true
  47643. });
  47644. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47645. get: function () {
  47646. var pointers = this.inputs.attached["pointers"];
  47647. if (pointers)
  47648. return pointers.angularSensibilityY;
  47649. return 0;
  47650. },
  47651. set: function (value) {
  47652. var pointers = this.inputs.attached["pointers"];
  47653. if (pointers) {
  47654. pointers.angularSensibilityY = value;
  47655. }
  47656. },
  47657. enumerable: true,
  47658. configurable: true
  47659. });
  47660. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47661. get: function () {
  47662. var pointers = this.inputs.attached["pointers"];
  47663. if (pointers)
  47664. return pointers.pinchPrecision;
  47665. return 0;
  47666. },
  47667. set: function (value) {
  47668. var pointers = this.inputs.attached["pointers"];
  47669. if (pointers) {
  47670. pointers.pinchPrecision = value;
  47671. }
  47672. },
  47673. enumerable: true,
  47674. configurable: true
  47675. });
  47676. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47677. get: function () {
  47678. var pointers = this.inputs.attached["pointers"];
  47679. if (pointers)
  47680. return pointers.pinchDeltaPercentage;
  47681. return 0;
  47682. },
  47683. set: function (value) {
  47684. var pointers = this.inputs.attached["pointers"];
  47685. if (pointers) {
  47686. pointers.pinchDeltaPercentage = value;
  47687. }
  47688. },
  47689. enumerable: true,
  47690. configurable: true
  47691. });
  47692. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47693. get: function () {
  47694. var pointers = this.inputs.attached["pointers"];
  47695. if (pointers)
  47696. return pointers.panningSensibility;
  47697. return 0;
  47698. },
  47699. set: function (value) {
  47700. var pointers = this.inputs.attached["pointers"];
  47701. if (pointers) {
  47702. pointers.panningSensibility = value;
  47703. }
  47704. },
  47705. enumerable: true,
  47706. configurable: true
  47707. });
  47708. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47709. get: function () {
  47710. var keyboard = this.inputs.attached["keyboard"];
  47711. if (keyboard)
  47712. return keyboard.keysUp;
  47713. return [];
  47714. },
  47715. set: function (value) {
  47716. var keyboard = this.inputs.attached["keyboard"];
  47717. if (keyboard)
  47718. keyboard.keysUp = value;
  47719. },
  47720. enumerable: true,
  47721. configurable: true
  47722. });
  47723. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47724. get: function () {
  47725. var keyboard = this.inputs.attached["keyboard"];
  47726. if (keyboard)
  47727. return keyboard.keysDown;
  47728. return [];
  47729. },
  47730. set: function (value) {
  47731. var keyboard = this.inputs.attached["keyboard"];
  47732. if (keyboard)
  47733. keyboard.keysDown = value;
  47734. },
  47735. enumerable: true,
  47736. configurable: true
  47737. });
  47738. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47739. get: function () {
  47740. var keyboard = this.inputs.attached["keyboard"];
  47741. if (keyboard)
  47742. return keyboard.keysLeft;
  47743. return [];
  47744. },
  47745. set: function (value) {
  47746. var keyboard = this.inputs.attached["keyboard"];
  47747. if (keyboard)
  47748. keyboard.keysLeft = value;
  47749. },
  47750. enumerable: true,
  47751. configurable: true
  47752. });
  47753. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47754. get: function () {
  47755. var keyboard = this.inputs.attached["keyboard"];
  47756. if (keyboard)
  47757. return keyboard.keysRight;
  47758. return [];
  47759. },
  47760. set: function (value) {
  47761. var keyboard = this.inputs.attached["keyboard"];
  47762. if (keyboard)
  47763. keyboard.keysRight = value;
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47769. get: function () {
  47770. var mousewheel = this.inputs.attached["mousewheel"];
  47771. if (mousewheel)
  47772. return mousewheel.wheelPrecision;
  47773. return 0;
  47774. },
  47775. set: function (value) {
  47776. var mousewheel = this.inputs.attached["mousewheel"];
  47777. if (mousewheel)
  47778. mousewheel.wheelPrecision = value;
  47779. },
  47780. enumerable: true,
  47781. configurable: true
  47782. });
  47783. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47784. get: function () {
  47785. var mousewheel = this.inputs.attached["mousewheel"];
  47786. if (mousewheel)
  47787. return mousewheel.wheelDeltaPercentage;
  47788. return 0;
  47789. },
  47790. set: function (value) {
  47791. var mousewheel = this.inputs.attached["mousewheel"];
  47792. if (mousewheel)
  47793. mousewheel.wheelDeltaPercentage = value;
  47794. },
  47795. enumerable: true,
  47796. configurable: true
  47797. });
  47798. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47799. get: function () {
  47800. return this._bouncingBehavior;
  47801. },
  47802. enumerable: true,
  47803. configurable: true
  47804. });
  47805. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47806. get: function () {
  47807. return this._bouncingBehavior != null;
  47808. },
  47809. set: function (value) {
  47810. if (value === this.useBouncingBehavior) {
  47811. return;
  47812. }
  47813. if (value) {
  47814. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47815. this.addBehavior(this._bouncingBehavior);
  47816. }
  47817. else if (this._bouncingBehavior) {
  47818. this.removeBehavior(this._bouncingBehavior);
  47819. this._bouncingBehavior = null;
  47820. }
  47821. },
  47822. enumerable: true,
  47823. configurable: true
  47824. });
  47825. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47826. get: function () {
  47827. return this._framingBehavior;
  47828. },
  47829. enumerable: true,
  47830. configurable: true
  47831. });
  47832. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47833. get: function () {
  47834. return this._framingBehavior != null;
  47835. },
  47836. set: function (value) {
  47837. if (value === this.useFramingBehavior) {
  47838. return;
  47839. }
  47840. if (value) {
  47841. this._framingBehavior = new BABYLON.FramingBehavior();
  47842. this.addBehavior(this._framingBehavior);
  47843. }
  47844. else if (this._framingBehavior) {
  47845. this.removeBehavior(this._framingBehavior);
  47846. this._framingBehavior = null;
  47847. }
  47848. },
  47849. enumerable: true,
  47850. configurable: true
  47851. });
  47852. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47853. get: function () {
  47854. return this._autoRotationBehavior;
  47855. },
  47856. enumerable: true,
  47857. configurable: true
  47858. });
  47859. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47860. get: function () {
  47861. return this._autoRotationBehavior != null;
  47862. },
  47863. set: function (value) {
  47864. if (value === this.useAutoRotationBehavior) {
  47865. return;
  47866. }
  47867. if (value) {
  47868. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47869. this.addBehavior(this._autoRotationBehavior);
  47870. }
  47871. else if (this._autoRotationBehavior) {
  47872. this.removeBehavior(this._autoRotationBehavior);
  47873. this._autoRotationBehavior = null;
  47874. }
  47875. },
  47876. enumerable: true,
  47877. configurable: true
  47878. });
  47879. // Cache
  47880. ArcRotateCamera.prototype._initCache = function () {
  47881. _super.prototype._initCache.call(this);
  47882. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47883. this._cache.alpha = undefined;
  47884. this._cache.beta = undefined;
  47885. this._cache.radius = undefined;
  47886. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  47887. };
  47888. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  47889. if (!ignoreParentClass) {
  47890. _super.prototype._updateCache.call(this);
  47891. }
  47892. this._cache._target.copyFrom(this._getTargetPosition());
  47893. this._cache.alpha = this.alpha;
  47894. this._cache.beta = this.beta;
  47895. this._cache.radius = this.radius;
  47896. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  47897. };
  47898. ArcRotateCamera.prototype._getTargetPosition = function () {
  47899. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  47900. var pos = this._targetHost.getAbsolutePosition();
  47901. if (this._targetBoundingCenter) {
  47902. pos.addToRef(this._targetBoundingCenter, this._target);
  47903. }
  47904. else {
  47905. this._target.copyFrom(pos);
  47906. }
  47907. }
  47908. var lockedTargetPosition = this._getLockedTargetPosition();
  47909. if (lockedTargetPosition) {
  47910. return lockedTargetPosition;
  47911. }
  47912. return this._target;
  47913. };
  47914. ArcRotateCamera.prototype.storeState = function () {
  47915. this._storedAlpha = this.alpha;
  47916. this._storedBeta = this.beta;
  47917. this._storedRadius = this.radius;
  47918. this._storedTarget = this._getTargetPosition().clone();
  47919. return _super.prototype.storeState.call(this);
  47920. };
  47921. /**
  47922. * Restored camera state. You must call storeState() first
  47923. */
  47924. ArcRotateCamera.prototype._restoreStateValues = function () {
  47925. if (!_super.prototype._restoreStateValues.call(this)) {
  47926. return false;
  47927. }
  47928. this.alpha = this._storedAlpha;
  47929. this.beta = this._storedBeta;
  47930. this.radius = this._storedRadius;
  47931. this.setTarget(this._storedTarget.clone());
  47932. this.inertialAlphaOffset = 0;
  47933. this.inertialBetaOffset = 0;
  47934. this.inertialRadiusOffset = 0;
  47935. this.inertialPanningX = 0;
  47936. this.inertialPanningY = 0;
  47937. return true;
  47938. };
  47939. // Synchronized
  47940. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  47941. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  47942. return false;
  47943. return this._cache._target.equals(this._getTargetPosition())
  47944. && this._cache.alpha === this.alpha
  47945. && this._cache.beta === this.beta
  47946. && this._cache.radius === this.radius
  47947. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  47948. };
  47949. // Methods
  47950. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  47951. var _this = this;
  47952. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  47953. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  47954. this._useCtrlForPanning = useCtrlForPanning;
  47955. this._panningMouseButton = panningMouseButton;
  47956. this.inputs.attachElement(element, noPreventDefault);
  47957. this._reset = function () {
  47958. _this.inertialAlphaOffset = 0;
  47959. _this.inertialBetaOffset = 0;
  47960. _this.inertialRadiusOffset = 0;
  47961. _this.inertialPanningX = 0;
  47962. _this.inertialPanningY = 0;
  47963. };
  47964. };
  47965. ArcRotateCamera.prototype.detachControl = function (element) {
  47966. this.inputs.detachElement(element);
  47967. if (this._reset) {
  47968. this._reset();
  47969. }
  47970. };
  47971. ArcRotateCamera.prototype._checkInputs = function () {
  47972. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  47973. if (this._collisionTriggered) {
  47974. return;
  47975. }
  47976. this.inputs.checkInputs();
  47977. // Inertia
  47978. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  47979. var inertialAlphaOffset = this.inertialAlphaOffset;
  47980. if (this.beta <= 0)
  47981. inertialAlphaOffset *= -1;
  47982. if (this.getScene().useRightHandedSystem)
  47983. inertialAlphaOffset *= -1;
  47984. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  47985. inertialAlphaOffset *= -1;
  47986. this.alpha += inertialAlphaOffset;
  47987. this.beta += this.inertialBetaOffset;
  47988. this.radius -= this.inertialRadiusOffset;
  47989. this.inertialAlphaOffset *= this.inertia;
  47990. this.inertialBetaOffset *= this.inertia;
  47991. this.inertialRadiusOffset *= this.inertia;
  47992. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  47993. this.inertialAlphaOffset = 0;
  47994. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  47995. this.inertialBetaOffset = 0;
  47996. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  47997. this.inertialRadiusOffset = 0;
  47998. }
  47999. // Panning inertia
  48000. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48001. if (!this._localDirection) {
  48002. this._localDirection = BABYLON.Vector3.Zero();
  48003. this._transformedDirection = BABYLON.Vector3.Zero();
  48004. }
  48005. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48006. this._localDirection.multiplyInPlace(this.panningAxis);
  48007. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48008. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48009. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48010. if (!this.panningAxis.y) {
  48011. this._transformedDirection.y = 0;
  48012. }
  48013. if (!this._targetHost) {
  48014. if (this.panningDistanceLimit) {
  48015. this._transformedDirection.addInPlace(this._target);
  48016. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48017. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48018. this._target.copyFrom(this._transformedDirection);
  48019. }
  48020. }
  48021. else {
  48022. this._target.addInPlace(this._transformedDirection);
  48023. }
  48024. }
  48025. this.inertialPanningX *= this.panningInertia;
  48026. this.inertialPanningY *= this.panningInertia;
  48027. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48028. this.inertialPanningX = 0;
  48029. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48030. this.inertialPanningY = 0;
  48031. }
  48032. // Limits
  48033. this._checkLimits();
  48034. _super.prototype._checkInputs.call(this);
  48035. };
  48036. ArcRotateCamera.prototype._checkLimits = function () {
  48037. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48038. if (this.allowUpsideDown && this.beta > Math.PI) {
  48039. this.beta = this.beta - (2 * Math.PI);
  48040. }
  48041. }
  48042. else {
  48043. if (this.beta < this.lowerBetaLimit) {
  48044. this.beta = this.lowerBetaLimit;
  48045. }
  48046. }
  48047. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48048. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48049. this.beta = this.beta + (2 * Math.PI);
  48050. }
  48051. }
  48052. else {
  48053. if (this.beta > this.upperBetaLimit) {
  48054. this.beta = this.upperBetaLimit;
  48055. }
  48056. }
  48057. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48058. this.alpha = this.lowerAlphaLimit;
  48059. }
  48060. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48061. this.alpha = this.upperAlphaLimit;
  48062. }
  48063. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48064. this.radius = this.lowerRadiusLimit;
  48065. }
  48066. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48067. this.radius = this.upperRadiusLimit;
  48068. }
  48069. };
  48070. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48071. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48072. this.radius = this._computationVector.length();
  48073. if (this.radius === 0) {
  48074. this.radius = 0.0001; // Just to avoid division by zero
  48075. }
  48076. // Alpha
  48077. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48078. if (this._computationVector.z < 0) {
  48079. this.alpha = 2 * Math.PI - this.alpha;
  48080. }
  48081. // Beta
  48082. this.beta = Math.acos(this._computationVector.y / this.radius);
  48083. this._checkLimits();
  48084. };
  48085. ArcRotateCamera.prototype.setPosition = function (position) {
  48086. if (this.position.equals(position)) {
  48087. return;
  48088. }
  48089. this.position.copyFrom(position);
  48090. this.rebuildAnglesAndRadius();
  48091. };
  48092. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48093. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48094. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48095. if (target.getBoundingInfo) {
  48096. if (toBoundingCenter) {
  48097. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48098. }
  48099. else {
  48100. this._targetBoundingCenter = null;
  48101. }
  48102. this._targetHost = target;
  48103. this._target = this._getTargetPosition();
  48104. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48105. }
  48106. else {
  48107. var newTarget = target;
  48108. var currentTarget = this._getTargetPosition();
  48109. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48110. return;
  48111. }
  48112. this._targetHost = null;
  48113. this._target = newTarget;
  48114. this._targetBoundingCenter = null;
  48115. this.onMeshTargetChangedObservable.notifyObservers(null);
  48116. }
  48117. this.rebuildAnglesAndRadius();
  48118. };
  48119. ArcRotateCamera.prototype._getViewMatrix = function () {
  48120. // Compute
  48121. var cosa = Math.cos(this.alpha);
  48122. var sina = Math.sin(this.alpha);
  48123. var cosb = Math.cos(this.beta);
  48124. var sinb = Math.sin(this.beta);
  48125. if (sinb === 0) {
  48126. sinb = 0.0001;
  48127. }
  48128. var target = this._getTargetPosition();
  48129. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48130. target.addToRef(this._computationVector, this._newPosition);
  48131. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48132. if (!this._collider) {
  48133. this._collider = new BABYLON.Collider();
  48134. }
  48135. this._collider._radius = this.collisionRadius;
  48136. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48137. this._collisionTriggered = true;
  48138. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48139. }
  48140. else {
  48141. this.position.copyFrom(this._newPosition);
  48142. var up = this.upVector;
  48143. if (this.allowUpsideDown && sinb < 0) {
  48144. up = up.clone();
  48145. up = up.negate();
  48146. }
  48147. this._computeViewMatrix(this.position, target, up);
  48148. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48149. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48150. }
  48151. this._currentTarget = target;
  48152. return this._viewMatrix;
  48153. };
  48154. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48155. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48156. meshes = meshes || this.getScene().meshes;
  48157. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48158. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48159. this.radius = distance * this.zoomOnFactor;
  48160. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48161. };
  48162. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48163. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48164. var meshesOrMinMaxVector;
  48165. var distance;
  48166. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48167. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48168. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48169. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48170. }
  48171. else { //minMaxVector and distance
  48172. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48173. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48174. distance = minMaxVectorAndDistance.distance;
  48175. }
  48176. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48177. if (!doNotUpdateMaxZ) {
  48178. this.maxZ = distance * 2;
  48179. }
  48180. };
  48181. /**
  48182. * @override
  48183. * Override Camera.createRigCamera
  48184. */
  48185. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48186. var alphaShift = 0;
  48187. switch (this.cameraRigMode) {
  48188. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48189. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48190. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48191. case BABYLON.Camera.RIG_MODE_VR:
  48192. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48193. break;
  48194. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48195. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48196. break;
  48197. }
  48198. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48199. rigCam._cameraRigParams = {};
  48200. return rigCam;
  48201. };
  48202. /**
  48203. * @override
  48204. * Override Camera._updateRigCameras
  48205. */
  48206. ArcRotateCamera.prototype._updateRigCameras = function () {
  48207. var camLeft = this._rigCameras[0];
  48208. var camRight = this._rigCameras[1];
  48209. camLeft.beta = camRight.beta = this.beta;
  48210. camLeft.radius = camRight.radius = this.radius;
  48211. switch (this.cameraRigMode) {
  48212. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48213. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48214. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48215. case BABYLON.Camera.RIG_MODE_VR:
  48216. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48217. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48218. break;
  48219. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48220. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48221. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48222. break;
  48223. }
  48224. _super.prototype._updateRigCameras.call(this);
  48225. };
  48226. ArcRotateCamera.prototype.dispose = function () {
  48227. this.inputs.clear();
  48228. _super.prototype.dispose.call(this);
  48229. };
  48230. ArcRotateCamera.prototype.getClassName = function () {
  48231. return "ArcRotateCamera";
  48232. };
  48233. __decorate([
  48234. BABYLON.serialize()
  48235. ], ArcRotateCamera.prototype, "alpha", void 0);
  48236. __decorate([
  48237. BABYLON.serialize()
  48238. ], ArcRotateCamera.prototype, "beta", void 0);
  48239. __decorate([
  48240. BABYLON.serialize()
  48241. ], ArcRotateCamera.prototype, "radius", void 0);
  48242. __decorate([
  48243. BABYLON.serializeAsVector3("target")
  48244. ], ArcRotateCamera.prototype, "_target", void 0);
  48245. __decorate([
  48246. BABYLON.serialize()
  48247. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48248. __decorate([
  48249. BABYLON.serialize()
  48250. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48251. __decorate([
  48252. BABYLON.serialize()
  48253. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48254. __decorate([
  48255. BABYLON.serialize()
  48256. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48257. __decorate([
  48258. BABYLON.serialize()
  48259. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48260. __decorate([
  48261. BABYLON.serialize()
  48262. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48263. __decorate([
  48264. BABYLON.serialize()
  48265. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48266. __decorate([
  48267. BABYLON.serialize()
  48268. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48269. __decorate([
  48270. BABYLON.serialize()
  48271. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48272. __decorate([
  48273. BABYLON.serialize()
  48274. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48275. __decorate([
  48276. BABYLON.serialize()
  48277. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48278. __decorate([
  48279. BABYLON.serialize()
  48280. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48281. __decorate([
  48282. BABYLON.serialize()
  48283. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48284. __decorate([
  48285. BABYLON.serializeAsVector3()
  48286. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48287. __decorate([
  48288. BABYLON.serialize()
  48289. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48290. __decorate([
  48291. BABYLON.serialize()
  48292. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48293. __decorate([
  48294. BABYLON.serialize()
  48295. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48296. return ArcRotateCamera;
  48297. }(BABYLON.TargetCamera));
  48298. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48299. })(BABYLON || (BABYLON = {}));
  48300. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48301. var BABYLON;
  48302. (function (BABYLON) {
  48303. /**
  48304. * The HemisphericLight simulates the ambient environment light,
  48305. * so the passed direction is the light reflection direction, not the incoming direction.
  48306. */
  48307. var HemisphericLight = /** @class */ (function (_super) {
  48308. __extends(HemisphericLight, _super);
  48309. /**
  48310. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48311. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48312. * The HemisphericLight can't cast shadows.
  48313. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48314. * @param name The friendly name of the light
  48315. * @param direction The direction of the light reflection
  48316. * @param scene The scene the light belongs to
  48317. */
  48318. function HemisphericLight(name, direction, scene) {
  48319. var _this = _super.call(this, name, scene) || this;
  48320. /**
  48321. * The groundColor is the light in the opposite direction to the one specified during creation.
  48322. * 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.
  48323. */
  48324. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48325. _this.direction = direction || BABYLON.Vector3.Up();
  48326. return _this;
  48327. }
  48328. HemisphericLight.prototype._buildUniformLayout = function () {
  48329. this._uniformBuffer.addUniform("vLightData", 4);
  48330. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48331. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48332. this._uniformBuffer.addUniform("vLightGround", 3);
  48333. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48334. this._uniformBuffer.addUniform("depthValues", 2);
  48335. this._uniformBuffer.create();
  48336. };
  48337. /**
  48338. * Returns the string "HemisphericLight".
  48339. * @return The class name
  48340. */
  48341. HemisphericLight.prototype.getClassName = function () {
  48342. return "HemisphericLight";
  48343. };
  48344. /**
  48345. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48346. * Returns the updated direction.
  48347. * @param target The target the direction should point to
  48348. * @return The computed direction
  48349. */
  48350. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48351. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48352. return this.direction;
  48353. };
  48354. /**
  48355. * Returns the shadow generator associated to the light.
  48356. * @returns Always null for hemispheric lights because it does not support shadows.
  48357. */
  48358. HemisphericLight.prototype.getShadowGenerator = function () {
  48359. return null;
  48360. };
  48361. /**
  48362. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48363. * @param effect The effect to update
  48364. * @param lightIndex The index of the light in the effect to update
  48365. * @returns The hemispheric light
  48366. */
  48367. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48368. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48369. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48370. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48371. return this;
  48372. };
  48373. /**
  48374. * @hidden internal use only.
  48375. */
  48376. HemisphericLight.prototype._getWorldMatrix = function () {
  48377. if (!this._worldMatrix) {
  48378. this._worldMatrix = BABYLON.Matrix.Identity();
  48379. }
  48380. return this._worldMatrix;
  48381. };
  48382. /**
  48383. * Returns the integer 3.
  48384. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48385. */
  48386. HemisphericLight.prototype.getTypeID = function () {
  48387. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48388. };
  48389. __decorate([
  48390. BABYLON.serializeAsColor3()
  48391. ], HemisphericLight.prototype, "groundColor", void 0);
  48392. __decorate([
  48393. BABYLON.serializeAsVector3()
  48394. ], HemisphericLight.prototype, "direction", void 0);
  48395. return HemisphericLight;
  48396. }(BABYLON.Light));
  48397. BABYLON.HemisphericLight = HemisphericLight;
  48398. })(BABYLON || (BABYLON = {}));
  48399. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48400. var BABYLON;
  48401. (function (BABYLON) {
  48402. /**
  48403. * Base implementation IShadowLight
  48404. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48405. */
  48406. var ShadowLight = /** @class */ (function (_super) {
  48407. __extends(ShadowLight, _super);
  48408. function ShadowLight() {
  48409. var _this = _super !== null && _super.apply(this, arguments) || this;
  48410. _this._needProjectionMatrixCompute = true;
  48411. return _this;
  48412. }
  48413. ShadowLight.prototype._setPosition = function (value) {
  48414. this._position = value;
  48415. };
  48416. Object.defineProperty(ShadowLight.prototype, "position", {
  48417. /**
  48418. * Sets the position the shadow will be casted from. Also use as the light position for both
  48419. * point and spot lights.
  48420. */
  48421. get: function () {
  48422. return this._position;
  48423. },
  48424. /**
  48425. * Sets the position the shadow will be casted from. Also use as the light position for both
  48426. * point and spot lights.
  48427. */
  48428. set: function (value) {
  48429. this._setPosition(value);
  48430. },
  48431. enumerable: true,
  48432. configurable: true
  48433. });
  48434. ShadowLight.prototype._setDirection = function (value) {
  48435. this._direction = value;
  48436. };
  48437. Object.defineProperty(ShadowLight.prototype, "direction", {
  48438. /**
  48439. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48440. * Also use as the light direction on spot and directional lights.
  48441. */
  48442. get: function () {
  48443. return this._direction;
  48444. },
  48445. /**
  48446. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48447. * Also use as the light direction on spot and directional lights.
  48448. */
  48449. set: function (value) {
  48450. this._setDirection(value);
  48451. },
  48452. enumerable: true,
  48453. configurable: true
  48454. });
  48455. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48456. /**
  48457. * Gets the shadow projection clipping minimum z value.
  48458. */
  48459. get: function () {
  48460. return this._shadowMinZ;
  48461. },
  48462. /**
  48463. * Sets the shadow projection clipping minimum z value.
  48464. */
  48465. set: function (value) {
  48466. this._shadowMinZ = value;
  48467. this.forceProjectionMatrixCompute();
  48468. },
  48469. enumerable: true,
  48470. configurable: true
  48471. });
  48472. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48473. /**
  48474. * Sets the shadow projection clipping maximum z value.
  48475. */
  48476. get: function () {
  48477. return this._shadowMaxZ;
  48478. },
  48479. /**
  48480. * Gets the shadow projection clipping maximum z value.
  48481. */
  48482. set: function (value) {
  48483. this._shadowMaxZ = value;
  48484. this.forceProjectionMatrixCompute();
  48485. },
  48486. enumerable: true,
  48487. configurable: true
  48488. });
  48489. /**
  48490. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48491. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48492. */
  48493. ShadowLight.prototype.computeTransformedInformation = function () {
  48494. if (this.parent && this.parent.getWorldMatrix) {
  48495. if (!this.transformedPosition) {
  48496. this.transformedPosition = BABYLON.Vector3.Zero();
  48497. }
  48498. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48499. // In case the direction is present.
  48500. if (this.direction) {
  48501. if (!this.transformedDirection) {
  48502. this.transformedDirection = BABYLON.Vector3.Zero();
  48503. }
  48504. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48505. }
  48506. return true;
  48507. }
  48508. return false;
  48509. };
  48510. /**
  48511. * Return the depth scale used for the shadow map.
  48512. * @returns the depth scale.
  48513. */
  48514. ShadowLight.prototype.getDepthScale = function () {
  48515. return 50.0;
  48516. };
  48517. /**
  48518. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48519. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48520. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48521. */
  48522. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48523. return this.transformedDirection ? this.transformedDirection : this.direction;
  48524. };
  48525. /**
  48526. * Returns the ShadowLight absolute position in the World.
  48527. * @returns the position vector in world space
  48528. */
  48529. ShadowLight.prototype.getAbsolutePosition = function () {
  48530. return this.transformedPosition ? this.transformedPosition : this.position;
  48531. };
  48532. /**
  48533. * Sets the ShadowLight direction toward the passed target.
  48534. * @param target The point tot target in local space
  48535. * @returns the updated ShadowLight direction
  48536. */
  48537. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48538. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48539. return this.direction;
  48540. };
  48541. /**
  48542. * Returns the light rotation in euler definition.
  48543. * @returns the x y z rotation in local space.
  48544. */
  48545. ShadowLight.prototype.getRotation = function () {
  48546. this.direction.normalize();
  48547. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48548. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48549. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48550. };
  48551. /**
  48552. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48553. * @returns true if a cube texture needs to be use
  48554. */
  48555. ShadowLight.prototype.needCube = function () {
  48556. return false;
  48557. };
  48558. /**
  48559. * Detects if the projection matrix requires to be recomputed this frame.
  48560. * @returns true if it requires to be recomputed otherwise, false.
  48561. */
  48562. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48563. return this._needProjectionMatrixCompute;
  48564. };
  48565. /**
  48566. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48567. */
  48568. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48569. this._needProjectionMatrixCompute = true;
  48570. };
  48571. /**
  48572. * Get the world matrix of the sahdow lights.
  48573. * @hidden Internal Use Only
  48574. */
  48575. ShadowLight.prototype._getWorldMatrix = function () {
  48576. if (!this._worldMatrix) {
  48577. this._worldMatrix = BABYLON.Matrix.Identity();
  48578. }
  48579. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48580. return this._worldMatrix;
  48581. };
  48582. /**
  48583. * Gets the minZ used for shadow according to both the scene and the light.
  48584. * @param activeCamera The camera we are returning the min for
  48585. * @returns the depth min z
  48586. */
  48587. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48588. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48589. };
  48590. /**
  48591. * Gets the maxZ used for shadow according to both the scene and the light.
  48592. * @param activeCamera The camera we are returning the max for
  48593. * @returns the depth max z
  48594. */
  48595. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48596. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48597. };
  48598. /**
  48599. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48600. * @param matrix The materix to updated with the projection information
  48601. * @param viewMatrix The transform matrix of the light
  48602. * @param renderList The list of mesh to render in the map
  48603. * @returns The current light
  48604. */
  48605. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48606. if (this.customProjectionMatrixBuilder) {
  48607. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48608. }
  48609. else {
  48610. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48611. }
  48612. return this;
  48613. };
  48614. __decorate([
  48615. BABYLON.serializeAsVector3()
  48616. ], ShadowLight.prototype, "position", null);
  48617. __decorate([
  48618. BABYLON.serializeAsVector3()
  48619. ], ShadowLight.prototype, "direction", null);
  48620. __decorate([
  48621. BABYLON.serialize()
  48622. ], ShadowLight.prototype, "shadowMinZ", null);
  48623. __decorate([
  48624. BABYLON.serialize()
  48625. ], ShadowLight.prototype, "shadowMaxZ", null);
  48626. return ShadowLight;
  48627. }(BABYLON.Light));
  48628. BABYLON.ShadowLight = ShadowLight;
  48629. })(BABYLON || (BABYLON = {}));
  48630. //# sourceMappingURL=babylon.shadowLight.js.map
  48631. var BABYLON;
  48632. (function (BABYLON) {
  48633. /**
  48634. * A point light is a light defined by an unique point in world space.
  48635. * The light is emitted in every direction from this point.
  48636. * A good example of a point light is a standard light bulb.
  48637. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48638. */
  48639. var PointLight = /** @class */ (function (_super) {
  48640. __extends(PointLight, _super);
  48641. /**
  48642. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48643. * A PointLight emits the light in every direction.
  48644. * It can cast shadows.
  48645. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48646. * ```javascript
  48647. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48648. * ```
  48649. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48650. * @param name The light friendly name
  48651. * @param position The position of the point light in the scene
  48652. * @param scene The scene the lights belongs to
  48653. */
  48654. function PointLight(name, position, scene) {
  48655. var _this = _super.call(this, name, scene) || this;
  48656. _this._shadowAngle = Math.PI / 2;
  48657. _this.position = position;
  48658. return _this;
  48659. }
  48660. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48661. /**
  48662. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48663. * This specifies what angle the shadow will use to be created.
  48664. *
  48665. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48666. */
  48667. get: function () {
  48668. return this._shadowAngle;
  48669. },
  48670. /**
  48671. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48672. * This specifies what angle the shadow will use to be created.
  48673. *
  48674. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48675. */
  48676. set: function (value) {
  48677. this._shadowAngle = value;
  48678. this.forceProjectionMatrixCompute();
  48679. },
  48680. enumerable: true,
  48681. configurable: true
  48682. });
  48683. Object.defineProperty(PointLight.prototype, "direction", {
  48684. /**
  48685. * Gets the direction if it has been set.
  48686. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48687. */
  48688. get: function () {
  48689. return this._direction;
  48690. },
  48691. /**
  48692. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48693. */
  48694. set: function (value) {
  48695. var previousNeedCube = this.needCube();
  48696. this._direction = value;
  48697. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48698. this._shadowGenerator.recreateShadowMap();
  48699. }
  48700. },
  48701. enumerable: true,
  48702. configurable: true
  48703. });
  48704. /**
  48705. * Returns the string "PointLight"
  48706. * @returns the class name
  48707. */
  48708. PointLight.prototype.getClassName = function () {
  48709. return "PointLight";
  48710. };
  48711. /**
  48712. * Returns the integer 0.
  48713. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48714. */
  48715. PointLight.prototype.getTypeID = function () {
  48716. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48717. };
  48718. /**
  48719. * Specifies wether or not the shadowmap should be a cube texture.
  48720. * @returns true if the shadowmap needs to be a cube texture.
  48721. */
  48722. PointLight.prototype.needCube = function () {
  48723. return !this.direction;
  48724. };
  48725. /**
  48726. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48727. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48728. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48729. */
  48730. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48731. if (this.direction) {
  48732. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48733. }
  48734. else {
  48735. switch (faceIndex) {
  48736. case 0:
  48737. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48738. case 1:
  48739. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48740. case 2:
  48741. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48742. case 3:
  48743. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48744. case 4:
  48745. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48746. case 5:
  48747. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48748. }
  48749. }
  48750. return BABYLON.Vector3.Zero();
  48751. };
  48752. /**
  48753. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48754. * - fov = PI / 2
  48755. * - aspect ratio : 1.0
  48756. * - z-near and far equal to the active camera minZ and maxZ.
  48757. * Returns the PointLight.
  48758. */
  48759. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48760. var activeCamera = this.getScene().activeCamera;
  48761. if (!activeCamera) {
  48762. return;
  48763. }
  48764. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48765. };
  48766. PointLight.prototype._buildUniformLayout = function () {
  48767. this._uniformBuffer.addUniform("vLightData", 4);
  48768. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48769. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48770. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48771. this._uniformBuffer.addUniform("depthValues", 2);
  48772. this._uniformBuffer.create();
  48773. };
  48774. /**
  48775. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48776. * @param effect The effect to update
  48777. * @param lightIndex The index of the light in the effect to update
  48778. * @returns The point light
  48779. */
  48780. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48781. if (this.computeTransformedInformation()) {
  48782. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48783. return this;
  48784. }
  48785. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48786. return this;
  48787. };
  48788. __decorate([
  48789. BABYLON.serialize()
  48790. ], PointLight.prototype, "shadowAngle", null);
  48791. return PointLight;
  48792. }(BABYLON.ShadowLight));
  48793. BABYLON.PointLight = PointLight;
  48794. })(BABYLON || (BABYLON = {}));
  48795. //# sourceMappingURL=babylon.pointLight.js.map
  48796. var BABYLON;
  48797. (function (BABYLON) {
  48798. /**
  48799. * A directional light is defined by a direction (what a surprise!).
  48800. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48801. * 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.
  48802. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48803. */
  48804. var DirectionalLight = /** @class */ (function (_super) {
  48805. __extends(DirectionalLight, _super);
  48806. /**
  48807. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48808. * The directional light is emitted from everywhere in the given direction.
  48809. * It can cast shawdows.
  48810. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48811. * @param name The friendly name of the light
  48812. * @param direction The direction of the light
  48813. * @param scene The scene the light belongs to
  48814. */
  48815. function DirectionalLight(name, direction, scene) {
  48816. var _this = _super.call(this, name, scene) || this;
  48817. _this._shadowFrustumSize = 0;
  48818. _this._shadowOrthoScale = 0.1;
  48819. /**
  48820. * Automatically compute the projection matrix to best fit (including all the casters)
  48821. * on each frame.
  48822. */
  48823. _this.autoUpdateExtends = true;
  48824. // Cache
  48825. _this._orthoLeft = Number.MAX_VALUE;
  48826. _this._orthoRight = Number.MIN_VALUE;
  48827. _this._orthoTop = Number.MIN_VALUE;
  48828. _this._orthoBottom = Number.MAX_VALUE;
  48829. _this.position = direction.scale(-1.0);
  48830. _this.direction = direction;
  48831. return _this;
  48832. }
  48833. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48834. /**
  48835. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48836. */
  48837. get: function () {
  48838. return this._shadowFrustumSize;
  48839. },
  48840. /**
  48841. * Specifies a fix frustum size for the shadow generation.
  48842. */
  48843. set: function (value) {
  48844. this._shadowFrustumSize = value;
  48845. this.forceProjectionMatrixCompute();
  48846. },
  48847. enumerable: true,
  48848. configurable: true
  48849. });
  48850. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48851. /**
  48852. * Gets the shadow projection scale against the optimal computed one.
  48853. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48854. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48855. */
  48856. get: function () {
  48857. return this._shadowOrthoScale;
  48858. },
  48859. /**
  48860. * Sets the shadow projection scale against the optimal computed one.
  48861. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48862. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48863. */
  48864. set: function (value) {
  48865. this._shadowOrthoScale = value;
  48866. this.forceProjectionMatrixCompute();
  48867. },
  48868. enumerable: true,
  48869. configurable: true
  48870. });
  48871. /**
  48872. * Returns the string "DirectionalLight".
  48873. * @return The class name
  48874. */
  48875. DirectionalLight.prototype.getClassName = function () {
  48876. return "DirectionalLight";
  48877. };
  48878. /**
  48879. * Returns the integer 1.
  48880. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48881. */
  48882. DirectionalLight.prototype.getTypeID = function () {
  48883. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  48884. };
  48885. /**
  48886. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  48887. * Returns the DirectionalLight Shadow projection matrix.
  48888. */
  48889. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48890. if (this.shadowFrustumSize > 0) {
  48891. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  48892. }
  48893. else {
  48894. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48895. }
  48896. };
  48897. /**
  48898. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  48899. * Returns the DirectionalLight Shadow projection matrix.
  48900. */
  48901. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  48902. var activeCamera = this.getScene().activeCamera;
  48903. if (!activeCamera) {
  48904. return;
  48905. }
  48906. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  48907. };
  48908. /**
  48909. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  48910. * Returns the DirectionalLight Shadow projection matrix.
  48911. */
  48912. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48913. var activeCamera = this.getScene().activeCamera;
  48914. if (!activeCamera) {
  48915. return;
  48916. }
  48917. // Check extends
  48918. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  48919. var tempVector3 = BABYLON.Vector3.Zero();
  48920. this._orthoLeft = Number.MAX_VALUE;
  48921. this._orthoRight = Number.MIN_VALUE;
  48922. this._orthoTop = Number.MIN_VALUE;
  48923. this._orthoBottom = Number.MAX_VALUE;
  48924. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  48925. var mesh = renderList[meshIndex];
  48926. if (!mesh) {
  48927. continue;
  48928. }
  48929. var boundingInfo = mesh.getBoundingInfo();
  48930. var boundingBox = boundingInfo.boundingBox;
  48931. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  48932. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  48933. if (tempVector3.x < this._orthoLeft)
  48934. this._orthoLeft = tempVector3.x;
  48935. if (tempVector3.y < this._orthoBottom)
  48936. this._orthoBottom = tempVector3.y;
  48937. if (tempVector3.x > this._orthoRight)
  48938. this._orthoRight = tempVector3.x;
  48939. if (tempVector3.y > this._orthoTop)
  48940. this._orthoTop = tempVector3.y;
  48941. }
  48942. }
  48943. }
  48944. var xOffset = this._orthoRight - this._orthoLeft;
  48945. var yOffset = this._orthoTop - this._orthoBottom;
  48946. 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);
  48947. };
  48948. DirectionalLight.prototype._buildUniformLayout = function () {
  48949. this._uniformBuffer.addUniform("vLightData", 4);
  48950. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48951. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48952. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48953. this._uniformBuffer.addUniform("depthValues", 2);
  48954. this._uniformBuffer.create();
  48955. };
  48956. /**
  48957. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  48958. * @param effect The effect to update
  48959. * @param lightIndex The index of the light in the effect to update
  48960. * @returns The directional light
  48961. */
  48962. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  48963. if (this.computeTransformedInformation()) {
  48964. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  48965. return this;
  48966. }
  48967. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  48968. return this;
  48969. };
  48970. /**
  48971. * Gets the minZ used for shadow according to both the scene and the light.
  48972. *
  48973. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48974. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48975. * @param activeCamera The camera we are returning the min for
  48976. * @returns the depth min z
  48977. */
  48978. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  48979. return 1;
  48980. };
  48981. /**
  48982. * Gets the maxZ used for shadow according to both the scene and the light.
  48983. *
  48984. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  48985. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  48986. * @param activeCamera The camera we are returning the max for
  48987. * @returns the depth max z
  48988. */
  48989. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  48990. return 1;
  48991. };
  48992. __decorate([
  48993. BABYLON.serialize()
  48994. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  48995. __decorate([
  48996. BABYLON.serialize()
  48997. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  48998. __decorate([
  48999. BABYLON.serialize()
  49000. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49001. return DirectionalLight;
  49002. }(BABYLON.ShadowLight));
  49003. BABYLON.DirectionalLight = DirectionalLight;
  49004. })(BABYLON || (BABYLON = {}));
  49005. //# sourceMappingURL=babylon.directionalLight.js.map
  49006. var BABYLON;
  49007. (function (BABYLON) {
  49008. /**
  49009. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49010. * These values define a cone of light starting from the position, emitting toward the direction.
  49011. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49012. * and the exponent defines the speed of the decay of the light with distance (reach).
  49013. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49014. */
  49015. var SpotLight = /** @class */ (function (_super) {
  49016. __extends(SpotLight, _super);
  49017. /**
  49018. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49019. * It can cast shadows.
  49020. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49021. * @param name The light friendly name
  49022. * @param position The position of the spot light in the scene
  49023. * @param direction The direction of the light in the scene
  49024. * @param angle The cone angle of the light in Radians
  49025. * @param exponent The light decay speed with the distance from the emission spot
  49026. * @param scene The scene the lights belongs to
  49027. */
  49028. function SpotLight(name, position, direction, angle, exponent, scene) {
  49029. var _this = _super.call(this, name, scene) || this;
  49030. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49031. _this._projectionTextureLightNear = 1e-6;
  49032. _this._projectionTextureLightFar = 1000.0;
  49033. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49034. _this._projectionTextureViewLightDirty = true;
  49035. _this._projectionTextureProjectionLightDirty = true;
  49036. _this._projectionTextureDirty = true;
  49037. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49038. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49039. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49040. _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);
  49041. _this.position = position;
  49042. _this.direction = direction;
  49043. _this.angle = angle;
  49044. _this.exponent = exponent;
  49045. return _this;
  49046. }
  49047. Object.defineProperty(SpotLight.prototype, "angle", {
  49048. /**
  49049. * Gets the cone angle of the spot light in Radians.
  49050. */
  49051. get: function () {
  49052. return this._angle;
  49053. },
  49054. /**
  49055. * Sets the cone angle of the spot light in Radians.
  49056. */
  49057. set: function (value) {
  49058. this._angle = value;
  49059. this._projectionTextureProjectionLightDirty = true;
  49060. this.forceProjectionMatrixCompute();
  49061. },
  49062. enumerable: true,
  49063. configurable: true
  49064. });
  49065. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49066. /**
  49067. * Allows scaling the angle of the light for shadow generation only.
  49068. */
  49069. get: function () {
  49070. return this._shadowAngleScale;
  49071. },
  49072. /**
  49073. * Allows scaling the angle of the light for shadow generation only.
  49074. */
  49075. set: function (value) {
  49076. this._shadowAngleScale = value;
  49077. this.forceProjectionMatrixCompute();
  49078. },
  49079. enumerable: true,
  49080. configurable: true
  49081. });
  49082. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49083. /**
  49084. * Allows reading the projecton texture
  49085. */
  49086. get: function () {
  49087. return this._projectionTextureMatrix;
  49088. },
  49089. enumerable: true,
  49090. configurable: true
  49091. });
  49092. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49093. /**
  49094. * Gets the near clip of the Spotlight for texture projection.
  49095. */
  49096. get: function () {
  49097. return this._projectionTextureLightNear;
  49098. },
  49099. /**
  49100. * Sets the near clip of the Spotlight for texture projection.
  49101. */
  49102. set: function (value) {
  49103. this._projectionTextureLightNear = value;
  49104. this._projectionTextureProjectionLightDirty = true;
  49105. },
  49106. enumerable: true,
  49107. configurable: true
  49108. });
  49109. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49110. /**
  49111. * Gets the far clip of the Spotlight for texture projection.
  49112. */
  49113. get: function () {
  49114. return this._projectionTextureLightFar;
  49115. },
  49116. /**
  49117. * Sets the far clip of the Spotlight for texture projection.
  49118. */
  49119. set: function (value) {
  49120. this._projectionTextureLightFar = value;
  49121. this._projectionTextureProjectionLightDirty = true;
  49122. },
  49123. enumerable: true,
  49124. configurable: true
  49125. });
  49126. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49127. /**
  49128. * Gets the Up vector of the Spotlight for texture projection.
  49129. */
  49130. get: function () {
  49131. return this._projectionTextureUpDirection;
  49132. },
  49133. /**
  49134. * Sets the Up vector of the Spotlight for texture projection.
  49135. */
  49136. set: function (value) {
  49137. this._projectionTextureUpDirection = value;
  49138. this._projectionTextureProjectionLightDirty = true;
  49139. },
  49140. enumerable: true,
  49141. configurable: true
  49142. });
  49143. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49144. /**
  49145. * Gets the projection texture of the light.
  49146. */
  49147. get: function () {
  49148. return this._projectionTexture;
  49149. },
  49150. /**
  49151. * Sets the projection texture of the light.
  49152. */
  49153. set: function (value) {
  49154. this._projectionTexture = value;
  49155. this._projectionTextureDirty = true;
  49156. },
  49157. enumerable: true,
  49158. configurable: true
  49159. });
  49160. /**
  49161. * Returns the string "SpotLight".
  49162. * @returns the class name
  49163. */
  49164. SpotLight.prototype.getClassName = function () {
  49165. return "SpotLight";
  49166. };
  49167. /**
  49168. * Returns the integer 2.
  49169. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49170. */
  49171. SpotLight.prototype.getTypeID = function () {
  49172. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49173. };
  49174. /**
  49175. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49176. */
  49177. SpotLight.prototype._setDirection = function (value) {
  49178. _super.prototype._setDirection.call(this, value);
  49179. this._projectionTextureViewLightDirty = true;
  49180. };
  49181. /**
  49182. * Overrides the position setter to recompute the projection texture view light Matrix.
  49183. */
  49184. SpotLight.prototype._setPosition = function (value) {
  49185. _super.prototype._setPosition.call(this, value);
  49186. this._projectionTextureViewLightDirty = true;
  49187. };
  49188. /**
  49189. * 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.
  49190. * Returns the SpotLight.
  49191. */
  49192. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49193. var activeCamera = this.getScene().activeCamera;
  49194. if (!activeCamera) {
  49195. return;
  49196. }
  49197. this._shadowAngleScale = this._shadowAngleScale || 1;
  49198. var angle = this._shadowAngleScale * this._angle;
  49199. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49200. };
  49201. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49202. this._projectionTextureViewLightDirty = false;
  49203. this._projectionTextureDirty = true;
  49204. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49205. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49206. };
  49207. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49208. this._projectionTextureProjectionLightDirty = false;
  49209. this._projectionTextureDirty = true;
  49210. var light_far = this.projectionTextureLightFar;
  49211. var light_near = this.projectionTextureLightNear;
  49212. var P = light_far / (light_far - light_near);
  49213. var Q = -P * light_near;
  49214. var S = 1.0 / Math.tan(this._angle / 2.0);
  49215. var A = 1.0;
  49216. 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);
  49217. };
  49218. /**
  49219. * Main function for light texture projection matrix computing.
  49220. */
  49221. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49222. this._projectionTextureDirty = false;
  49223. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49224. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49225. };
  49226. SpotLight.prototype._buildUniformLayout = function () {
  49227. this._uniformBuffer.addUniform("vLightData", 4);
  49228. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49229. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49230. this._uniformBuffer.addUniform("vLightDirection", 3);
  49231. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49232. this._uniformBuffer.addUniform("depthValues", 2);
  49233. this._uniformBuffer.create();
  49234. };
  49235. /**
  49236. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49237. * @param effect The effect to update
  49238. * @param lightIndex The index of the light in the effect to update
  49239. * @returns The spot light
  49240. */
  49241. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49242. var normalizeDirection;
  49243. if (this.computeTransformedInformation()) {
  49244. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49245. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49246. }
  49247. else {
  49248. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49249. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49250. }
  49251. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49252. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49253. if (this._projectionTextureViewLightDirty) {
  49254. this._computeProjectionTextureViewLightMatrix();
  49255. }
  49256. if (this._projectionTextureProjectionLightDirty) {
  49257. this._computeProjectionTextureProjectionLightMatrix();
  49258. }
  49259. if (this._projectionTextureDirty) {
  49260. this._computeProjectionTextureMatrix();
  49261. }
  49262. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49263. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49264. }
  49265. return this;
  49266. };
  49267. /**
  49268. * Disposes the light and the associated resources.
  49269. */
  49270. SpotLight.prototype.dispose = function () {
  49271. _super.prototype.dispose.call(this);
  49272. if (this._projectionTexture) {
  49273. this._projectionTexture.dispose();
  49274. }
  49275. };
  49276. __decorate([
  49277. BABYLON.serialize()
  49278. ], SpotLight.prototype, "angle", null);
  49279. __decorate([
  49280. BABYLON.serialize()
  49281. ], SpotLight.prototype, "shadowAngleScale", null);
  49282. __decorate([
  49283. BABYLON.serialize()
  49284. ], SpotLight.prototype, "exponent", void 0);
  49285. __decorate([
  49286. BABYLON.serialize()
  49287. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49288. __decorate([
  49289. BABYLON.serialize()
  49290. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49291. __decorate([
  49292. BABYLON.serialize()
  49293. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49294. __decorate([
  49295. BABYLON.serializeAsTexture("projectedLightTexture")
  49296. ], SpotLight.prototype, "_projectionTexture", void 0);
  49297. return SpotLight;
  49298. }(BABYLON.ShadowLight));
  49299. BABYLON.SpotLight = SpotLight;
  49300. })(BABYLON || (BABYLON = {}));
  49301. //# sourceMappingURL=babylon.spotLight.js.map
  49302. var BABYLON;
  49303. (function (BABYLON) {
  49304. /**
  49305. * Class used to override all child animations of a given target
  49306. */
  49307. var AnimationPropertiesOverride = /** @class */ (function () {
  49308. function AnimationPropertiesOverride() {
  49309. /**
  49310. * Gets or sets a value indicating if animation blending must be used
  49311. */
  49312. this.enableBlending = false;
  49313. /**
  49314. * Gets or sets the blending speed to use when enableBlending is true
  49315. */
  49316. this.blendingSpeed = 0.01;
  49317. /**
  49318. * Gets or sets the default loop mode to use
  49319. */
  49320. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49321. }
  49322. return AnimationPropertiesOverride;
  49323. }());
  49324. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49325. })(BABYLON || (BABYLON = {}));
  49326. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49327. var BABYLON;
  49328. (function (BABYLON) {
  49329. /**
  49330. * Represents the range of an animation
  49331. */
  49332. var AnimationRange = /** @class */ (function () {
  49333. /**
  49334. * Initializes the range of an animation
  49335. * @param name The name of the animation range
  49336. * @param from The starting frame of the animation
  49337. * @param to The ending frame of the animation
  49338. */
  49339. function AnimationRange(
  49340. /**The name of the animation range**/
  49341. name,
  49342. /**The starting frame of the animation */
  49343. from,
  49344. /**The ending frame of the animation*/
  49345. to) {
  49346. this.name = name;
  49347. this.from = from;
  49348. this.to = to;
  49349. }
  49350. /**
  49351. * Makes a copy of the animation range
  49352. * @returns A copy of the animation range
  49353. */
  49354. AnimationRange.prototype.clone = function () {
  49355. return new AnimationRange(this.name, this.from, this.to);
  49356. };
  49357. return AnimationRange;
  49358. }());
  49359. BABYLON.AnimationRange = AnimationRange;
  49360. /**
  49361. * Composed of a frame, and an action function
  49362. */
  49363. var AnimationEvent = /** @class */ (function () {
  49364. /**
  49365. * Initializes the animation event
  49366. * @param frame The frame for which the event is triggered
  49367. * @param action The event to perform when triggered
  49368. * @param onlyOnce Specifies if the event should be triggered only once
  49369. */
  49370. function AnimationEvent(
  49371. /** The frame for which the event is triggered **/
  49372. frame,
  49373. /** The event to perform when triggered **/
  49374. action,
  49375. /** Specifies if the event should be triggered only once**/
  49376. onlyOnce) {
  49377. this.frame = frame;
  49378. this.action = action;
  49379. this.onlyOnce = onlyOnce;
  49380. /**
  49381. * Specifies if the animation event is done
  49382. */
  49383. this.isDone = false;
  49384. }
  49385. /** @hidden */
  49386. AnimationEvent.prototype._clone = function () {
  49387. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49388. };
  49389. return AnimationEvent;
  49390. }());
  49391. BABYLON.AnimationEvent = AnimationEvent;
  49392. /**
  49393. * A cursor which tracks a point on a path
  49394. */
  49395. var PathCursor = /** @class */ (function () {
  49396. /**
  49397. * Initializes the path cursor
  49398. * @param path The path to track
  49399. */
  49400. function PathCursor(path) {
  49401. this.path = path;
  49402. /**
  49403. * Stores path cursor callbacks for when an onchange event is triggered
  49404. */
  49405. this._onchange = new Array();
  49406. /**
  49407. * The value of the path cursor
  49408. */
  49409. this.value = 0;
  49410. /**
  49411. * The animation array of the path cursor
  49412. */
  49413. this.animations = new Array();
  49414. }
  49415. /**
  49416. * Gets the cursor point on the path
  49417. * @returns A point on the path cursor at the cursor location
  49418. */
  49419. PathCursor.prototype.getPoint = function () {
  49420. var point = this.path.getPointAtLengthPosition(this.value);
  49421. return new BABYLON.Vector3(point.x, 0, point.y);
  49422. };
  49423. /**
  49424. * Moves the cursor ahead by the step amount
  49425. * @param step The amount to move the cursor forward
  49426. * @returns This path cursor
  49427. */
  49428. PathCursor.prototype.moveAhead = function (step) {
  49429. if (step === void 0) { step = 0.002; }
  49430. this.move(step);
  49431. return this;
  49432. };
  49433. /**
  49434. * Moves the cursor behind by the step amount
  49435. * @param step The amount to move the cursor back
  49436. * @returns This path cursor
  49437. */
  49438. PathCursor.prototype.moveBack = function (step) {
  49439. if (step === void 0) { step = 0.002; }
  49440. this.move(-step);
  49441. return this;
  49442. };
  49443. /**
  49444. * Moves the cursor by the step amount
  49445. * If the step amount is greater than one, an exception is thrown
  49446. * @param step The amount to move the cursor
  49447. * @returns This path cursor
  49448. */
  49449. PathCursor.prototype.move = function (step) {
  49450. if (Math.abs(step) > 1) {
  49451. throw "step size should be less than 1.";
  49452. }
  49453. this.value += step;
  49454. this.ensureLimits();
  49455. this.raiseOnChange();
  49456. return this;
  49457. };
  49458. /**
  49459. * Ensures that the value is limited between zero and one
  49460. * @returns This path cursor
  49461. */
  49462. PathCursor.prototype.ensureLimits = function () {
  49463. while (this.value > 1) {
  49464. this.value -= 1;
  49465. }
  49466. while (this.value < 0) {
  49467. this.value += 1;
  49468. }
  49469. return this;
  49470. };
  49471. /**
  49472. * Runs onchange callbacks on change (used by the animation engine)
  49473. * @returns This path cursor
  49474. */
  49475. PathCursor.prototype.raiseOnChange = function () {
  49476. var _this = this;
  49477. this._onchange.forEach(function (f) { return f(_this); });
  49478. return this;
  49479. };
  49480. /**
  49481. * Executes a function on change
  49482. * @param f A path cursor onchange callback
  49483. * @returns This path cursor
  49484. */
  49485. PathCursor.prototype.onchange = function (f) {
  49486. this._onchange.push(f);
  49487. return this;
  49488. };
  49489. return PathCursor;
  49490. }());
  49491. BABYLON.PathCursor = PathCursor;
  49492. /**
  49493. * Enum for the animation key frame interpolation type
  49494. */
  49495. var AnimationKeyInterpolation;
  49496. (function (AnimationKeyInterpolation) {
  49497. /**
  49498. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49499. */
  49500. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49501. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49502. /**
  49503. * Class used to store any kind of animation
  49504. */
  49505. var Animation = /** @class */ (function () {
  49506. /**
  49507. * Initializes the animation
  49508. * @param name Name of the animation
  49509. * @param targetProperty Property to animate
  49510. * @param framePerSecond The frames per second of the animation
  49511. * @param dataType The data type of the animation
  49512. * @param loopMode The loop mode of the animation
  49513. * @param enableBlendings Specifies if blending should be enabled
  49514. */
  49515. function Animation(
  49516. /**Name of the animation */
  49517. name,
  49518. /**Property to animate */
  49519. targetProperty,
  49520. /**The frames per second of the animation */
  49521. framePerSecond,
  49522. /**The data type of the animation */
  49523. dataType,
  49524. /**The loop mode of the animation */
  49525. loopMode,
  49526. /**Specifies if blending should be enabled */
  49527. enableBlending) {
  49528. this.name = name;
  49529. this.targetProperty = targetProperty;
  49530. this.framePerSecond = framePerSecond;
  49531. this.dataType = dataType;
  49532. this.loopMode = loopMode;
  49533. this.enableBlending = enableBlending;
  49534. /**
  49535. * @hidden Internal use only
  49536. */
  49537. this._runtimeAnimations = new Array();
  49538. /**
  49539. * The set of event that will be linked to this animation
  49540. */
  49541. this._events = new Array();
  49542. /**
  49543. * Stores the blending speed of the animation
  49544. */
  49545. this.blendingSpeed = 0.01;
  49546. /**
  49547. * Stores the animation ranges for the animation
  49548. */
  49549. this._ranges = {};
  49550. this.targetPropertyPath = targetProperty.split(".");
  49551. this.dataType = dataType;
  49552. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49553. }
  49554. /**
  49555. * @hidden Internal use
  49556. */
  49557. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49558. var dataType = undefined;
  49559. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49560. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49561. }
  49562. else if (from instanceof BABYLON.Quaternion) {
  49563. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49564. }
  49565. else if (from instanceof BABYLON.Vector3) {
  49566. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49567. }
  49568. else if (from instanceof BABYLON.Vector2) {
  49569. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49570. }
  49571. else if (from instanceof BABYLON.Color3) {
  49572. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49573. }
  49574. else if (from instanceof BABYLON.Size) {
  49575. dataType = Animation.ANIMATIONTYPE_SIZE;
  49576. }
  49577. if (dataType == undefined) {
  49578. return null;
  49579. }
  49580. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49581. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49582. animation.setKeys(keys);
  49583. if (easingFunction !== undefined) {
  49584. animation.setEasingFunction(easingFunction);
  49585. }
  49586. return animation;
  49587. };
  49588. /**
  49589. * Sets up an animation
  49590. * @param property The property to animate
  49591. * @param animationType The animation type to apply
  49592. * @param framePerSecond The frames per second of the animation
  49593. * @param easingFunction The easing function used in the animation
  49594. * @returns The created animation
  49595. */
  49596. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49597. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49598. animation.setEasingFunction(easingFunction);
  49599. return animation;
  49600. };
  49601. /**
  49602. * Create and start an animation on a node
  49603. * @param name defines the name of the global animation that will be run on all nodes
  49604. * @param node defines the root node where the animation will take place
  49605. * @param targetProperty defines property to animate
  49606. * @param framePerSecond defines the number of frame per second yo use
  49607. * @param totalFrame defines the number of frames in total
  49608. * @param from defines the initial value
  49609. * @param to defines the final value
  49610. * @param loopMode defines which loop mode you want to use (off by default)
  49611. * @param easingFunction defines the easing function to use (linear by default)
  49612. * @param onAnimationEnd defines the callback to call when animation end
  49613. * @returns the animatable created for this animation
  49614. */
  49615. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49616. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49617. if (!animation) {
  49618. return null;
  49619. }
  49620. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49621. };
  49622. /**
  49623. * Create and start an animation on a node and its descendants
  49624. * @param name defines the name of the global animation that will be run on all nodes
  49625. * @param node defines the root node where the animation will take place
  49626. * @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
  49627. * @param targetProperty defines property to animate
  49628. * @param framePerSecond defines the number of frame per second to use
  49629. * @param totalFrame defines the number of frames in total
  49630. * @param from defines the initial value
  49631. * @param to defines the final value
  49632. * @param loopMode defines which loop mode you want to use (off by default)
  49633. * @param easingFunction defines the easing function to use (linear by default)
  49634. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49635. * @returns the list of animatables created for all nodes
  49636. * @example https://www.babylonjs-playground.com/#MH0VLI
  49637. */
  49638. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49639. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49640. if (!animation) {
  49641. return null;
  49642. }
  49643. var scene = node.getScene();
  49644. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49645. };
  49646. /**
  49647. * Creates a new animation, merges it with the existing animations and starts it
  49648. * @param name Name of the animation
  49649. * @param node Node which contains the scene that begins the animations
  49650. * @param targetProperty Specifies which property to animate
  49651. * @param framePerSecond The frames per second of the animation
  49652. * @param totalFrame The total number of frames
  49653. * @param from The frame at the beginning of the animation
  49654. * @param to The frame at the end of the animation
  49655. * @param loopMode Specifies the loop mode of the animation
  49656. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49657. * @param onAnimationEnd Callback to run once the animation is complete
  49658. * @returns Nullable animation
  49659. */
  49660. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49661. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49662. if (!animation) {
  49663. return null;
  49664. }
  49665. node.animations.push(animation);
  49666. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49667. };
  49668. /**
  49669. * Transition property of an host to the target Value
  49670. * @param property The property to transition
  49671. * @param targetValue The target Value of the property
  49672. * @param host The object where the property to animate belongs
  49673. * @param scene Scene used to run the animation
  49674. * @param frameRate Framerate (in frame/s) to use
  49675. * @param transition The transition type we want to use
  49676. * @param duration The duration of the animation, in milliseconds
  49677. * @param onAnimationEnd Callback trigger at the end of the animation
  49678. * @returns Nullable animation
  49679. */
  49680. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49681. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49682. if (duration <= 0) {
  49683. host[property] = targetValue;
  49684. if (onAnimationEnd) {
  49685. onAnimationEnd();
  49686. }
  49687. return null;
  49688. }
  49689. var endFrame = frameRate * (duration / 1000);
  49690. transition.setKeys([{
  49691. frame: 0,
  49692. value: host[property].clone ? host[property].clone() : host[property]
  49693. },
  49694. {
  49695. frame: endFrame,
  49696. value: targetValue
  49697. }]);
  49698. if (!host.animations) {
  49699. host.animations = [];
  49700. }
  49701. host.animations.push(transition);
  49702. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49703. animation.onAnimationEnd = onAnimationEnd;
  49704. return animation;
  49705. };
  49706. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49707. /**
  49708. * Return the array of runtime animations currently using this animation
  49709. */
  49710. get: function () {
  49711. return this._runtimeAnimations;
  49712. },
  49713. enumerable: true,
  49714. configurable: true
  49715. });
  49716. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49717. /**
  49718. * Specifies if any of the runtime animations are currently running
  49719. */
  49720. get: function () {
  49721. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49722. var runtimeAnimation = _a[_i];
  49723. if (!runtimeAnimation.isStopped) {
  49724. return true;
  49725. }
  49726. }
  49727. return false;
  49728. },
  49729. enumerable: true,
  49730. configurable: true
  49731. });
  49732. // Methods
  49733. /**
  49734. * Converts the animation to a string
  49735. * @param fullDetails support for multiple levels of logging within scene loading
  49736. * @returns String form of the animation
  49737. */
  49738. Animation.prototype.toString = function (fullDetails) {
  49739. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49740. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49741. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49742. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49743. if (fullDetails) {
  49744. ret += ", Ranges: {";
  49745. var first = true;
  49746. for (var name in this._ranges) {
  49747. if (first) {
  49748. ret += ", ";
  49749. first = false;
  49750. }
  49751. ret += name;
  49752. }
  49753. ret += "}";
  49754. }
  49755. return ret;
  49756. };
  49757. /**
  49758. * Add an event to this animation
  49759. * @param event Event to add
  49760. */
  49761. Animation.prototype.addEvent = function (event) {
  49762. this._events.push(event);
  49763. };
  49764. /**
  49765. * Remove all events found at the given frame
  49766. * @param frame The frame to remove events from
  49767. */
  49768. Animation.prototype.removeEvents = function (frame) {
  49769. for (var index = 0; index < this._events.length; index++) {
  49770. if (this._events[index].frame === frame) {
  49771. this._events.splice(index, 1);
  49772. index--;
  49773. }
  49774. }
  49775. };
  49776. /**
  49777. * Retrieves all the events from the animation
  49778. * @returns Events from the animation
  49779. */
  49780. Animation.prototype.getEvents = function () {
  49781. return this._events;
  49782. };
  49783. /**
  49784. * Creates an animation range
  49785. * @param name Name of the animation range
  49786. * @param from Starting frame of the animation range
  49787. * @param to Ending frame of the animation
  49788. */
  49789. Animation.prototype.createRange = function (name, from, to) {
  49790. // check name not already in use; could happen for bones after serialized
  49791. if (!this._ranges[name]) {
  49792. this._ranges[name] = new AnimationRange(name, from, to);
  49793. }
  49794. };
  49795. /**
  49796. * Deletes an animation range by name
  49797. * @param name Name of the animation range to delete
  49798. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49799. */
  49800. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49801. if (deleteFrames === void 0) { deleteFrames = true; }
  49802. var range = this._ranges[name];
  49803. if (!range) {
  49804. return;
  49805. }
  49806. if (deleteFrames) {
  49807. var from = range.from;
  49808. var to = range.to;
  49809. // this loop MUST go high to low for multiple splices to work
  49810. for (var key = this._keys.length - 1; key >= 0; key--) {
  49811. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49812. this._keys.splice(key, 1);
  49813. }
  49814. }
  49815. }
  49816. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49817. };
  49818. /**
  49819. * Gets the animation range by name, or null if not defined
  49820. * @param name Name of the animation range
  49821. * @returns Nullable animation range
  49822. */
  49823. Animation.prototype.getRange = function (name) {
  49824. return this._ranges[name];
  49825. };
  49826. /**
  49827. * Gets the key frames from the animation
  49828. * @returns The key frames of the animation
  49829. */
  49830. Animation.prototype.getKeys = function () {
  49831. return this._keys;
  49832. };
  49833. /**
  49834. * Gets the highest frame rate of the animation
  49835. * @returns Highest frame rate of the animation
  49836. */
  49837. Animation.prototype.getHighestFrame = function () {
  49838. var ret = 0;
  49839. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49840. if (ret < this._keys[key].frame) {
  49841. ret = this._keys[key].frame;
  49842. }
  49843. }
  49844. return ret;
  49845. };
  49846. /**
  49847. * Gets the easing function of the animation
  49848. * @returns Easing function of the animation
  49849. */
  49850. Animation.prototype.getEasingFunction = function () {
  49851. return this._easingFunction;
  49852. };
  49853. /**
  49854. * Sets the easing function of the animation
  49855. * @param easingFunction A custom mathematical formula for animation
  49856. */
  49857. Animation.prototype.setEasingFunction = function (easingFunction) {
  49858. this._easingFunction = easingFunction;
  49859. };
  49860. /**
  49861. * Interpolates a scalar linearly
  49862. * @param startValue Start value of the animation curve
  49863. * @param endValue End value of the animation curve
  49864. * @param gradient Scalar amount to interpolate
  49865. * @returns Interpolated scalar value
  49866. */
  49867. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49868. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49869. };
  49870. /**
  49871. * Interpolates a scalar cubically
  49872. * @param startValue Start value of the animation curve
  49873. * @param outTangent End tangent of the animation
  49874. * @param endValue End value of the animation curve
  49875. * @param inTangent Start tangent of the animation curve
  49876. * @param gradient Scalar amount to interpolate
  49877. * @returns Interpolated scalar value
  49878. */
  49879. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49880. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49881. };
  49882. /**
  49883. * Interpolates a quaternion using a spherical linear interpolation
  49884. * @param startValue Start value of the animation curve
  49885. * @param endValue End value of the animation curve
  49886. * @param gradient Scalar amount to interpolate
  49887. * @returns Interpolated quaternion value
  49888. */
  49889. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  49890. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  49891. };
  49892. /**
  49893. * Interpolates a quaternion cubically
  49894. * @param startValue Start value of the animation curve
  49895. * @param outTangent End tangent of the animation curve
  49896. * @param endValue End value of the animation curve
  49897. * @param inTangent Start tangent of the animation curve
  49898. * @param gradient Scalar amount to interpolate
  49899. * @returns Interpolated quaternion value
  49900. */
  49901. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49902. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  49903. };
  49904. /**
  49905. * Interpolates a Vector3 linearl
  49906. * @param startValue Start value of the animation curve
  49907. * @param endValue End value of the animation curve
  49908. * @param gradient Scalar amount to interpolate
  49909. * @returns Interpolated scalar value
  49910. */
  49911. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  49912. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  49913. };
  49914. /**
  49915. * Interpolates a Vector3 cubically
  49916. * @param startValue Start value of the animation curve
  49917. * @param outTangent End tangent of the animation
  49918. * @param endValue End value of the animation curve
  49919. * @param inTangent Start tangent of the animation curve
  49920. * @param gradient Scalar amount to interpolate
  49921. * @returns InterpolatedVector3 value
  49922. */
  49923. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49924. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49925. };
  49926. /**
  49927. * Interpolates a Vector2 linearly
  49928. * @param startValue Start value of the animation curve
  49929. * @param endValue End value of the animation curve
  49930. * @param gradient Scalar amount to interpolate
  49931. * @returns Interpolated Vector2 value
  49932. */
  49933. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  49934. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  49935. };
  49936. /**
  49937. * Interpolates a Vector2 cubically
  49938. * @param startValue Start value of the animation curve
  49939. * @param outTangent End tangent of the animation
  49940. * @param endValue End value of the animation curve
  49941. * @param inTangent Start tangent of the animation curve
  49942. * @param gradient Scalar amount to interpolate
  49943. * @returns Interpolated Vector2 value
  49944. */
  49945. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  49946. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  49947. };
  49948. /**
  49949. * Interpolates a size linearly
  49950. * @param startValue Start value of the animation curve
  49951. * @param endValue End value of the animation curve
  49952. * @param gradient Scalar amount to interpolate
  49953. * @returns Interpolated Size value
  49954. */
  49955. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  49956. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  49957. };
  49958. /**
  49959. * Interpolates a Color3 linearly
  49960. * @param startValue Start value of the animation curve
  49961. * @param endValue End value of the animation curve
  49962. * @param gradient Scalar amount to interpolate
  49963. * @returns Interpolated Color3 value
  49964. */
  49965. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  49966. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  49967. };
  49968. /**
  49969. * @hidden Internal use only
  49970. */
  49971. Animation.prototype._getKeyValue = function (value) {
  49972. if (typeof value === "function") {
  49973. return value();
  49974. }
  49975. return value;
  49976. };
  49977. /**
  49978. * @hidden Internal use only
  49979. */
  49980. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  49981. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  49982. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  49983. }
  49984. var keys = this.getKeys();
  49985. // Try to get a hash to find the right key
  49986. 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));
  49987. if (keys[startKeyIndex].frame >= currentFrame) {
  49988. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  49989. startKeyIndex--;
  49990. }
  49991. }
  49992. for (var key = startKeyIndex; key < keys.length; key++) {
  49993. var endKey = keys[key + 1];
  49994. if (endKey.frame >= currentFrame) {
  49995. var startKey = keys[key];
  49996. var startValue = this._getKeyValue(startKey.value);
  49997. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  49998. return startValue;
  49999. }
  50000. var endValue = this._getKeyValue(endKey.value);
  50001. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50002. var frameDelta = endKey.frame - startKey.frame;
  50003. // gradient : percent of currentFrame between the frame inf and the frame sup
  50004. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50005. // check for easingFunction and correction of gradient
  50006. var easingFunction = this.getEasingFunction();
  50007. if (easingFunction != null) {
  50008. gradient = easingFunction.ease(gradient);
  50009. }
  50010. switch (this.dataType) {
  50011. // Float
  50012. case Animation.ANIMATIONTYPE_FLOAT:
  50013. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50014. switch (loopMode) {
  50015. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50016. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50017. return floatValue;
  50018. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50019. return offsetValue * repeatCount + floatValue;
  50020. }
  50021. break;
  50022. // Quaternion
  50023. case Animation.ANIMATIONTYPE_QUATERNION:
  50024. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50025. switch (loopMode) {
  50026. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50027. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50028. return quatValue;
  50029. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50030. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50031. }
  50032. return quatValue;
  50033. // Vector3
  50034. case Animation.ANIMATIONTYPE_VECTOR3:
  50035. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50036. switch (loopMode) {
  50037. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50038. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50039. return vec3Value;
  50040. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50041. return vec3Value.add(offsetValue.scale(repeatCount));
  50042. }
  50043. // Vector2
  50044. case Animation.ANIMATIONTYPE_VECTOR2:
  50045. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50046. switch (loopMode) {
  50047. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50048. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50049. return vec2Value;
  50050. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50051. return vec2Value.add(offsetValue.scale(repeatCount));
  50052. }
  50053. // Size
  50054. case Animation.ANIMATIONTYPE_SIZE:
  50055. switch (loopMode) {
  50056. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50057. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50058. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50059. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50060. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50061. }
  50062. // Color3
  50063. case Animation.ANIMATIONTYPE_COLOR3:
  50064. switch (loopMode) {
  50065. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50066. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50067. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50068. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50069. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50070. }
  50071. // Matrix
  50072. case Animation.ANIMATIONTYPE_MATRIX:
  50073. switch (loopMode) {
  50074. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50075. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50076. if (Animation.AllowMatricesInterpolation) {
  50077. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50078. }
  50079. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50080. return startValue;
  50081. }
  50082. default:
  50083. break;
  50084. }
  50085. break;
  50086. }
  50087. }
  50088. return this._getKeyValue(keys[keys.length - 1].value);
  50089. };
  50090. /**
  50091. * Defines the function to use to interpolate matrices
  50092. * @param startValue defines the start matrix
  50093. * @param endValue defines the end matrix
  50094. * @param gradient defines the gradient between both matrices
  50095. * @param result defines an optional target matrix where to store the interpolation
  50096. * @returns the interpolated matrix
  50097. */
  50098. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50099. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50100. if (result) {
  50101. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50102. return result;
  50103. }
  50104. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50105. }
  50106. if (result) {
  50107. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50108. return result;
  50109. }
  50110. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50111. };
  50112. /**
  50113. * Makes a copy of the animation
  50114. * @returns Cloned animation
  50115. */
  50116. Animation.prototype.clone = function () {
  50117. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50118. clone.enableBlending = this.enableBlending;
  50119. clone.blendingSpeed = this.blendingSpeed;
  50120. if (this._keys) {
  50121. clone.setKeys(this._keys);
  50122. }
  50123. if (this._ranges) {
  50124. clone._ranges = {};
  50125. for (var name in this._ranges) {
  50126. var range = this._ranges[name];
  50127. if (!range) {
  50128. continue;
  50129. }
  50130. clone._ranges[name] = range.clone();
  50131. }
  50132. }
  50133. return clone;
  50134. };
  50135. /**
  50136. * Sets the key frames of the animation
  50137. * @param values The animation key frames to set
  50138. */
  50139. Animation.prototype.setKeys = function (values) {
  50140. this._keys = values.slice(0);
  50141. };
  50142. /**
  50143. * Serializes the animation to an object
  50144. * @returns Serialized object
  50145. */
  50146. Animation.prototype.serialize = function () {
  50147. var serializationObject = {};
  50148. serializationObject.name = this.name;
  50149. serializationObject.property = this.targetProperty;
  50150. serializationObject.framePerSecond = this.framePerSecond;
  50151. serializationObject.dataType = this.dataType;
  50152. serializationObject.loopBehavior = this.loopMode;
  50153. serializationObject.enableBlending = this.enableBlending;
  50154. serializationObject.blendingSpeed = this.blendingSpeed;
  50155. var dataType = this.dataType;
  50156. serializationObject.keys = [];
  50157. var keys = this.getKeys();
  50158. for (var index = 0; index < keys.length; index++) {
  50159. var animationKey = keys[index];
  50160. var key = {};
  50161. key.frame = animationKey.frame;
  50162. switch (dataType) {
  50163. case Animation.ANIMATIONTYPE_FLOAT:
  50164. key.values = [animationKey.value];
  50165. break;
  50166. case Animation.ANIMATIONTYPE_QUATERNION:
  50167. case Animation.ANIMATIONTYPE_MATRIX:
  50168. case Animation.ANIMATIONTYPE_VECTOR3:
  50169. case Animation.ANIMATIONTYPE_COLOR3:
  50170. key.values = animationKey.value.asArray();
  50171. break;
  50172. }
  50173. serializationObject.keys.push(key);
  50174. }
  50175. serializationObject.ranges = [];
  50176. for (var name in this._ranges) {
  50177. var source = this._ranges[name];
  50178. if (!source) {
  50179. continue;
  50180. }
  50181. var range = {};
  50182. range.name = name;
  50183. range.from = source.from;
  50184. range.to = source.to;
  50185. serializationObject.ranges.push(range);
  50186. }
  50187. return serializationObject;
  50188. };
  50189. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50190. /**
  50191. * Get the float animation type
  50192. */
  50193. get: function () {
  50194. return Animation._ANIMATIONTYPE_FLOAT;
  50195. },
  50196. enumerable: true,
  50197. configurable: true
  50198. });
  50199. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50200. /**
  50201. * Get the Vector3 animation type
  50202. */
  50203. get: function () {
  50204. return Animation._ANIMATIONTYPE_VECTOR3;
  50205. },
  50206. enumerable: true,
  50207. configurable: true
  50208. });
  50209. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50210. /**
  50211. * Get the Vectpr2 animation type
  50212. */
  50213. get: function () {
  50214. return Animation._ANIMATIONTYPE_VECTOR2;
  50215. },
  50216. enumerable: true,
  50217. configurable: true
  50218. });
  50219. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50220. /**
  50221. * Get the Size animation type
  50222. */
  50223. get: function () {
  50224. return Animation._ANIMATIONTYPE_SIZE;
  50225. },
  50226. enumerable: true,
  50227. configurable: true
  50228. });
  50229. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50230. /**
  50231. * Get the Quaternion animation type
  50232. */
  50233. get: function () {
  50234. return Animation._ANIMATIONTYPE_QUATERNION;
  50235. },
  50236. enumerable: true,
  50237. configurable: true
  50238. });
  50239. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50240. /**
  50241. * Get the Matrix animation type
  50242. */
  50243. get: function () {
  50244. return Animation._ANIMATIONTYPE_MATRIX;
  50245. },
  50246. enumerable: true,
  50247. configurable: true
  50248. });
  50249. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50250. /**
  50251. * Get the Color3 animation type
  50252. */
  50253. get: function () {
  50254. return Animation._ANIMATIONTYPE_COLOR3;
  50255. },
  50256. enumerable: true,
  50257. configurable: true
  50258. });
  50259. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50260. /**
  50261. * Get the Relative Loop Mode
  50262. */
  50263. get: function () {
  50264. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50265. },
  50266. enumerable: true,
  50267. configurable: true
  50268. });
  50269. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50270. /**
  50271. * Get the Cycle Loop Mode
  50272. */
  50273. get: function () {
  50274. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50275. },
  50276. enumerable: true,
  50277. configurable: true
  50278. });
  50279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50280. /**
  50281. * Get the Constant Loop Mode
  50282. */
  50283. get: function () {
  50284. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50285. },
  50286. enumerable: true,
  50287. configurable: true
  50288. });
  50289. /** @hidden */
  50290. Animation._UniversalLerp = function (left, right, amount) {
  50291. var constructor = left.constructor;
  50292. if (constructor.Lerp) { // Lerp supported
  50293. return constructor.Lerp(left, right, amount);
  50294. }
  50295. else if (constructor.Slerp) { // Slerp supported
  50296. return constructor.Slerp(left, right, amount);
  50297. }
  50298. else if (left.toFixed) { // Number
  50299. return left * (1.0 - amount) + amount * right;
  50300. }
  50301. else { // Blending not supported
  50302. return right;
  50303. }
  50304. };
  50305. /**
  50306. * Parses an animation object and creates an animation
  50307. * @param parsedAnimation Parsed animation object
  50308. * @returns Animation object
  50309. */
  50310. Animation.Parse = function (parsedAnimation) {
  50311. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50312. var dataType = parsedAnimation.dataType;
  50313. var keys = [];
  50314. var data;
  50315. var index;
  50316. if (parsedAnimation.enableBlending) {
  50317. animation.enableBlending = parsedAnimation.enableBlending;
  50318. }
  50319. if (parsedAnimation.blendingSpeed) {
  50320. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50321. }
  50322. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50323. var key = parsedAnimation.keys[index];
  50324. var inTangent;
  50325. var outTangent;
  50326. switch (dataType) {
  50327. case Animation.ANIMATIONTYPE_FLOAT:
  50328. data = key.values[0];
  50329. if (key.values.length >= 1) {
  50330. inTangent = key.values[1];
  50331. }
  50332. if (key.values.length >= 2) {
  50333. outTangent = key.values[2];
  50334. }
  50335. break;
  50336. case Animation.ANIMATIONTYPE_QUATERNION:
  50337. data = BABYLON.Quaternion.FromArray(key.values);
  50338. if (key.values.length >= 8) {
  50339. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50340. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50341. inTangent = _inTangent;
  50342. }
  50343. }
  50344. if (key.values.length >= 12) {
  50345. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50346. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50347. outTangent = _outTangent;
  50348. }
  50349. }
  50350. break;
  50351. case Animation.ANIMATIONTYPE_MATRIX:
  50352. data = BABYLON.Matrix.FromArray(key.values);
  50353. break;
  50354. case Animation.ANIMATIONTYPE_COLOR3:
  50355. data = BABYLON.Color3.FromArray(key.values);
  50356. break;
  50357. case Animation.ANIMATIONTYPE_VECTOR3:
  50358. default:
  50359. data = BABYLON.Vector3.FromArray(key.values);
  50360. break;
  50361. }
  50362. var keyData = {};
  50363. keyData.frame = key.frame;
  50364. keyData.value = data;
  50365. if (inTangent != undefined) {
  50366. keyData.inTangent = inTangent;
  50367. }
  50368. if (outTangent != undefined) {
  50369. keyData.outTangent = outTangent;
  50370. }
  50371. keys.push(keyData);
  50372. }
  50373. animation.setKeys(keys);
  50374. if (parsedAnimation.ranges) {
  50375. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50376. data = parsedAnimation.ranges[index];
  50377. animation.createRange(data.name, data.from, data.to);
  50378. }
  50379. }
  50380. return animation;
  50381. };
  50382. /**
  50383. * Appends the serialized animations from the source animations
  50384. * @param source Source containing the animations
  50385. * @param destination Target to store the animations
  50386. */
  50387. Animation.AppendSerializedAnimations = function (source, destination) {
  50388. if (source.animations) {
  50389. destination.animations = [];
  50390. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50391. var animation = source.animations[animationIndex];
  50392. destination.animations.push(animation.serialize());
  50393. }
  50394. }
  50395. };
  50396. /**
  50397. * Use matrix interpolation instead of using direct key value when animating matrices
  50398. */
  50399. Animation.AllowMatricesInterpolation = false;
  50400. /**
  50401. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50402. */
  50403. Animation.AllowMatrixDecomposeForInterpolation = true;
  50404. // Statics
  50405. /**
  50406. * Float animation type
  50407. */
  50408. Animation._ANIMATIONTYPE_FLOAT = 0;
  50409. /**
  50410. * Vector3 animation type
  50411. */
  50412. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50413. /**
  50414. * Quaternion animation type
  50415. */
  50416. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50417. /**
  50418. * Matrix animation type
  50419. */
  50420. Animation._ANIMATIONTYPE_MATRIX = 3;
  50421. /**
  50422. * Color3 animation type
  50423. */
  50424. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50425. /**
  50426. * Vector2 animation type
  50427. */
  50428. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50429. /**
  50430. * Size animation type
  50431. */
  50432. Animation._ANIMATIONTYPE_SIZE = 6;
  50433. /**
  50434. * Relative Loop Mode
  50435. */
  50436. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50437. /**
  50438. * Cycle Loop Mode
  50439. */
  50440. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50441. /**
  50442. * Constant Loop Mode
  50443. */
  50444. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50445. return Animation;
  50446. }());
  50447. BABYLON.Animation = Animation;
  50448. })(BABYLON || (BABYLON = {}));
  50449. //# sourceMappingURL=babylon.animation.js.map
  50450. var BABYLON;
  50451. (function (BABYLON) {
  50452. /**
  50453. * This class defines the direct association between an animation and a target
  50454. */
  50455. var TargetedAnimation = /** @class */ (function () {
  50456. function TargetedAnimation() {
  50457. }
  50458. return TargetedAnimation;
  50459. }());
  50460. BABYLON.TargetedAnimation = TargetedAnimation;
  50461. /**
  50462. * Use this class to create coordinated animations on multiple targets
  50463. */
  50464. var AnimationGroup = /** @class */ (function () {
  50465. function AnimationGroup(name, scene) {
  50466. if (scene === void 0) { scene = null; }
  50467. this.name = name;
  50468. this._targetedAnimations = new Array();
  50469. this._animatables = new Array();
  50470. this._from = Number.MAX_VALUE;
  50471. this._to = -Number.MAX_VALUE;
  50472. this._speedRatio = 1;
  50473. this.onAnimationEndObservable = new BABYLON.Observable();
  50474. /**
  50475. * This observable will notify when all animations have ended.
  50476. */
  50477. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50478. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50479. this._scene.animationGroups.push(this);
  50480. }
  50481. Object.defineProperty(AnimationGroup.prototype, "from", {
  50482. /**
  50483. * Gets the first frame
  50484. */
  50485. get: function () {
  50486. return this._from;
  50487. },
  50488. enumerable: true,
  50489. configurable: true
  50490. });
  50491. Object.defineProperty(AnimationGroup.prototype, "to", {
  50492. /**
  50493. * Gets the last frame
  50494. */
  50495. get: function () {
  50496. return this._to;
  50497. },
  50498. enumerable: true,
  50499. configurable: true
  50500. });
  50501. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50502. /**
  50503. * Define if the animations are started
  50504. */
  50505. get: function () {
  50506. return this._isStarted;
  50507. },
  50508. enumerable: true,
  50509. configurable: true
  50510. });
  50511. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50512. /**
  50513. * Gets or sets the speed ratio to use for all animations
  50514. */
  50515. get: function () {
  50516. return this._speedRatio;
  50517. },
  50518. /**
  50519. * Gets or sets the speed ratio to use for all animations
  50520. */
  50521. set: function (value) {
  50522. if (this._speedRatio === value) {
  50523. return;
  50524. }
  50525. this._speedRatio = value;
  50526. for (var index = 0; index < this._animatables.length; index++) {
  50527. var animatable = this._animatables[index];
  50528. animatable.speedRatio = this._speedRatio;
  50529. }
  50530. },
  50531. enumerable: true,
  50532. configurable: true
  50533. });
  50534. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50535. /**
  50536. * Gets the targeted animations for this animation group
  50537. */
  50538. get: function () {
  50539. return this._targetedAnimations;
  50540. },
  50541. enumerable: true,
  50542. configurable: true
  50543. });
  50544. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50545. /**
  50546. * returning the list of animatables controlled by this animation group.
  50547. */
  50548. get: function () {
  50549. return this._animatables;
  50550. },
  50551. enumerable: true,
  50552. configurable: true
  50553. });
  50554. /**
  50555. * Add an animation (with its target) in the group
  50556. * @param animation defines the animation we want to add
  50557. * @param target defines the target of the animation
  50558. * @returns the {BABYLON.TargetedAnimation} object
  50559. */
  50560. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50561. var targetedAnimation = {
  50562. animation: animation,
  50563. target: target
  50564. };
  50565. var keys = animation.getKeys();
  50566. if (this._from > keys[0].frame) {
  50567. this._from = keys[0].frame;
  50568. }
  50569. if (this._to < keys[keys.length - 1].frame) {
  50570. this._to = keys[keys.length - 1].frame;
  50571. }
  50572. this._targetedAnimations.push(targetedAnimation);
  50573. return targetedAnimation;
  50574. };
  50575. /**
  50576. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50577. * It can add constant keys at begin or end
  50578. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50579. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50580. */
  50581. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50582. if (beginFrame === void 0) { beginFrame = null; }
  50583. if (endFrame === void 0) { endFrame = null; }
  50584. if (beginFrame == null)
  50585. beginFrame = this._from;
  50586. if (endFrame == null)
  50587. endFrame = this._to;
  50588. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50589. var targetedAnimation = this._targetedAnimations[index];
  50590. var keys = targetedAnimation.animation.getKeys();
  50591. var startKey = keys[0];
  50592. var endKey = keys[keys.length - 1];
  50593. if (startKey.frame > beginFrame) {
  50594. var newKey = {
  50595. frame: beginFrame,
  50596. value: startKey.value,
  50597. inTangent: startKey.inTangent,
  50598. outTangent: startKey.outTangent,
  50599. interpolation: startKey.interpolation
  50600. };
  50601. keys.splice(0, 0, newKey);
  50602. }
  50603. if (endKey.frame < endFrame) {
  50604. var newKey = {
  50605. frame: endFrame,
  50606. value: endKey.value,
  50607. inTangent: endKey.outTangent,
  50608. outTangent: endKey.outTangent,
  50609. interpolation: endKey.interpolation
  50610. };
  50611. keys.push(newKey);
  50612. }
  50613. }
  50614. this._from = beginFrame;
  50615. this._to = endFrame;
  50616. return this;
  50617. };
  50618. /**
  50619. * Start all animations on given targets
  50620. * @param loop defines if animations must loop
  50621. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50622. * @param from defines the from key (optional)
  50623. * @param to defines the to key (optional)
  50624. * @returns the current animation group
  50625. */
  50626. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50627. var _this = this;
  50628. if (loop === void 0) { loop = false; }
  50629. if (speedRatio === void 0) { speedRatio = 1; }
  50630. if (this._isStarted || this._targetedAnimations.length === 0) {
  50631. return this;
  50632. }
  50633. var _loop_1 = function (targetedAnimation) {
  50634. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50635. animatable.onAnimationEnd = function () {
  50636. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50637. _this._checkAnimationGroupEnded(animatable);
  50638. };
  50639. this_1._animatables.push(animatable);
  50640. };
  50641. var this_1 = this;
  50642. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50643. var targetedAnimation = _a[_i];
  50644. _loop_1(targetedAnimation);
  50645. }
  50646. this._speedRatio = speedRatio;
  50647. this._isStarted = true;
  50648. return this;
  50649. };
  50650. /**
  50651. * Pause all animations
  50652. */
  50653. AnimationGroup.prototype.pause = function () {
  50654. if (!this._isStarted) {
  50655. return this;
  50656. }
  50657. for (var index = 0; index < this._animatables.length; index++) {
  50658. var animatable = this._animatables[index];
  50659. animatable.pause();
  50660. }
  50661. return this;
  50662. };
  50663. /**
  50664. * Play all animations to initial state
  50665. * This function will start() the animations if they were not started or will restart() them if they were paused
  50666. * @param loop defines if animations must loop
  50667. */
  50668. AnimationGroup.prototype.play = function (loop) {
  50669. // only if all animatables are ready and exist
  50670. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50671. if (loop !== undefined) {
  50672. for (var index = 0; index < this._animatables.length; index++) {
  50673. var animatable = this._animatables[index];
  50674. animatable.loopAnimation = loop;
  50675. }
  50676. }
  50677. this.restart();
  50678. }
  50679. else {
  50680. this.stop();
  50681. this.start(loop, this._speedRatio);
  50682. }
  50683. return this;
  50684. };
  50685. /**
  50686. * Reset all animations to initial state
  50687. */
  50688. AnimationGroup.prototype.reset = function () {
  50689. if (!this._isStarted) {
  50690. return this;
  50691. }
  50692. for (var index = 0; index < this._animatables.length; index++) {
  50693. var animatable = this._animatables[index];
  50694. animatable.reset();
  50695. }
  50696. return this;
  50697. };
  50698. /**
  50699. * Restart animations from key 0
  50700. */
  50701. AnimationGroup.prototype.restart = function () {
  50702. if (!this._isStarted) {
  50703. return this;
  50704. }
  50705. for (var index = 0; index < this._animatables.length; index++) {
  50706. var animatable = this._animatables[index];
  50707. animatable.restart();
  50708. }
  50709. return this;
  50710. };
  50711. /**
  50712. * Stop all animations
  50713. */
  50714. AnimationGroup.prototype.stop = function () {
  50715. if (!this._isStarted) {
  50716. return this;
  50717. }
  50718. var list = this._animatables.slice();
  50719. for (var index = 0; index < list.length; index++) {
  50720. list[index].stop();
  50721. }
  50722. this._isStarted = false;
  50723. return this;
  50724. };
  50725. /**
  50726. * Set animation weight for all animatables
  50727. * @param weight defines the weight to use
  50728. * @return the animationGroup
  50729. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50730. */
  50731. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50732. for (var index = 0; index < this._animatables.length; index++) {
  50733. var animatable = this._animatables[index];
  50734. animatable.weight = weight;
  50735. }
  50736. return this;
  50737. };
  50738. /**
  50739. * Synchronize and normalize all animatables with a source animatable
  50740. * @param root defines the root animatable to synchronize with
  50741. * @return the animationGroup
  50742. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50743. */
  50744. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50745. for (var index = 0; index < this._animatables.length; index++) {
  50746. var animatable = this._animatables[index];
  50747. animatable.syncWith(root);
  50748. }
  50749. return this;
  50750. };
  50751. /**
  50752. * Goes to a specific frame in this animation group
  50753. * @param frame the frame number to go to
  50754. * @return the animationGroup
  50755. */
  50756. AnimationGroup.prototype.goToFrame = function (frame) {
  50757. if (!this._isStarted) {
  50758. return this;
  50759. }
  50760. for (var index = 0; index < this._animatables.length; index++) {
  50761. var animatable = this._animatables[index];
  50762. animatable.goToFrame(frame);
  50763. }
  50764. return this;
  50765. };
  50766. /**
  50767. * Dispose all associated resources
  50768. */
  50769. AnimationGroup.prototype.dispose = function () {
  50770. this._targetedAnimations = [];
  50771. this._animatables = [];
  50772. var index = this._scene.animationGroups.indexOf(this);
  50773. if (index > -1) {
  50774. this._scene.animationGroups.splice(index, 1);
  50775. }
  50776. };
  50777. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50778. // animatable should be taken out of the array
  50779. var idx = this._animatables.indexOf(animatable);
  50780. if (idx > -1) {
  50781. this._animatables.splice(idx, 1);
  50782. }
  50783. // all animatables were removed? animation group ended!
  50784. if (this._animatables.length === 0) {
  50785. this._isStarted = false;
  50786. this.onAnimationGroupEndObservable.notifyObservers(this);
  50787. }
  50788. };
  50789. return AnimationGroup;
  50790. }());
  50791. BABYLON.AnimationGroup = AnimationGroup;
  50792. })(BABYLON || (BABYLON = {}));
  50793. //# sourceMappingURL=babylon.animationGroup.js.map
  50794. var BABYLON;
  50795. (function (BABYLON) {
  50796. /**
  50797. * Defines a runtime animation
  50798. */
  50799. var RuntimeAnimation = /** @class */ (function () {
  50800. /**
  50801. * Create a new RuntimeAnimation object
  50802. * @param target defines the target of the animation
  50803. * @param animation defines the source animation object
  50804. * @param scene defines the hosting scene
  50805. * @param host defines the initiating Animatable
  50806. */
  50807. function RuntimeAnimation(target, animation, scene, host) {
  50808. var _this = this;
  50809. this._events = new Array();
  50810. /**
  50811. * The current frame of the runtime animation
  50812. */
  50813. this._currentFrame = 0;
  50814. /**
  50815. * The original value of the runtime animation
  50816. */
  50817. this._originalValue = new Array();
  50818. /**
  50819. * The offsets cache of the runtime animation
  50820. */
  50821. this._offsetsCache = {};
  50822. /**
  50823. * The high limits cache of the runtime animation
  50824. */
  50825. this._highLimitsCache = {};
  50826. /**
  50827. * Specifies if the runtime animation has been stopped
  50828. */
  50829. this._stopped = false;
  50830. /**
  50831. * The blending factor of the runtime animation
  50832. */
  50833. this._blendingFactor = 0;
  50834. /**
  50835. * The target path of the runtime animation
  50836. */
  50837. this._targetPath = "";
  50838. /**
  50839. * The weight of the runtime animation
  50840. */
  50841. this._weight = 1.0;
  50842. /**
  50843. * The ratio offset of the runtime animation
  50844. */
  50845. this._ratioOffset = 0;
  50846. /**
  50847. * The previous delay of the runtime animation
  50848. */
  50849. this._previousDelay = 0;
  50850. /**
  50851. * The previous ratio of the runtime animation
  50852. */
  50853. this._previousRatio = 0;
  50854. this._animation = animation;
  50855. this._target = target;
  50856. this._scene = scene;
  50857. this._host = host;
  50858. animation._runtimeAnimations.push(this);
  50859. // Cloning events locally
  50860. var events = animation.getEvents();
  50861. if (events && events.length > 0) {
  50862. events.forEach(function (e) {
  50863. _this._events.push(e._clone());
  50864. });
  50865. }
  50866. }
  50867. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50868. /**
  50869. * Gets the current frame of the runtime animation
  50870. */
  50871. get: function () {
  50872. return this._currentFrame;
  50873. },
  50874. enumerable: true,
  50875. configurable: true
  50876. });
  50877. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  50878. /**
  50879. * Gets the weight of the runtime animation
  50880. */
  50881. get: function () {
  50882. return this._weight;
  50883. },
  50884. enumerable: true,
  50885. configurable: true
  50886. });
  50887. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  50888. /**
  50889. * Gets the current value of the runtime animation
  50890. */
  50891. get: function () {
  50892. return this._currentValue;
  50893. },
  50894. enumerable: true,
  50895. configurable: true
  50896. });
  50897. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  50898. /**
  50899. * Gets the target path of the runtime animation
  50900. */
  50901. get: function () {
  50902. return this._targetPath;
  50903. },
  50904. enumerable: true,
  50905. configurable: true
  50906. });
  50907. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  50908. /**
  50909. * Gets the actual target of the runtime animation
  50910. */
  50911. get: function () {
  50912. return this._activeTarget;
  50913. },
  50914. enumerable: true,
  50915. configurable: true
  50916. });
  50917. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  50918. /**
  50919. * Gets the animation from the runtime animation
  50920. */
  50921. get: function () {
  50922. return this._animation;
  50923. },
  50924. enumerable: true,
  50925. configurable: true
  50926. });
  50927. /**
  50928. * Resets the runtime animation to the beginning
  50929. * @param restoreOriginal defines whether to restore the target property to the original value
  50930. */
  50931. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  50932. if (restoreOriginal === void 0) { restoreOriginal = false; }
  50933. if (restoreOriginal) {
  50934. if (this._target instanceof Array) {
  50935. var index = 0;
  50936. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  50937. var target = _a[_i];
  50938. if (this._originalValue[index] !== undefined) {
  50939. this._setValue(target, this._originalValue[index], -1);
  50940. }
  50941. index++;
  50942. }
  50943. }
  50944. else {
  50945. if (this._originalValue[0] !== undefined) {
  50946. this._setValue(this._target, this._originalValue[0], -1);
  50947. }
  50948. }
  50949. }
  50950. this._offsetsCache = {};
  50951. this._highLimitsCache = {};
  50952. this._currentFrame = 0;
  50953. this._blendingFactor = 0;
  50954. this._originalValue = new Array();
  50955. // Events
  50956. for (var index = 0; index < this._events.length; index++) {
  50957. this._events[index].isDone = false;
  50958. }
  50959. };
  50960. /**
  50961. * Specifies if the runtime animation is stopped
  50962. * @returns Boolean specifying if the runtime animation is stopped
  50963. */
  50964. RuntimeAnimation.prototype.isStopped = function () {
  50965. return this._stopped;
  50966. };
  50967. /**
  50968. * Disposes of the runtime animation
  50969. */
  50970. RuntimeAnimation.prototype.dispose = function () {
  50971. var index = this._animation.runtimeAnimations.indexOf(this);
  50972. if (index > -1) {
  50973. this._animation.runtimeAnimations.splice(index, 1);
  50974. }
  50975. };
  50976. /**
  50977. * Interpolates the animation from the current frame
  50978. * @param currentFrame The frame to interpolate the animation to
  50979. * @param repeatCount The number of times that the animation should loop
  50980. * @param loopMode The type of looping mode to use
  50981. * @param offsetValue Animation offset value
  50982. * @param highLimitValue The high limit value
  50983. * @returns The interpolated value
  50984. */
  50985. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  50986. this._currentFrame = currentFrame;
  50987. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  50988. this._workValue = BABYLON.Matrix.Zero();
  50989. }
  50990. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  50991. };
  50992. /**
  50993. * Apply the interpolated value to the target
  50994. * @param currentValue defines the value computed by the animation
  50995. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  50996. */
  50997. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  50998. if (weight === void 0) { weight = 1.0; }
  50999. if (this._target instanceof Array) {
  51000. var index = 0;
  51001. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51002. var target = _a[_i];
  51003. this._setValue(target, currentValue, weight, index);
  51004. index++;
  51005. }
  51006. }
  51007. else {
  51008. this._setValue(this._target, currentValue, weight);
  51009. }
  51010. };
  51011. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51012. if (targetIndex === void 0) { targetIndex = 0; }
  51013. // Set value
  51014. var path;
  51015. var destination;
  51016. var targetPropertyPath = this._animation.targetPropertyPath;
  51017. if (targetPropertyPath.length > 1) {
  51018. var property = target[targetPropertyPath[0]];
  51019. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51020. property = property[targetPropertyPath[index]];
  51021. }
  51022. path = targetPropertyPath[targetPropertyPath.length - 1];
  51023. destination = property;
  51024. }
  51025. else {
  51026. path = targetPropertyPath[0];
  51027. destination = target;
  51028. }
  51029. this._targetPath = path;
  51030. this._activeTarget = destination;
  51031. this._weight = weight;
  51032. if (this._originalValue[targetIndex] === undefined) {
  51033. var originalValue = void 0;
  51034. if (destination.getRestPose && path === "_matrix") { // For bones
  51035. originalValue = destination.getRestPose();
  51036. }
  51037. else {
  51038. originalValue = destination[path];
  51039. }
  51040. if (originalValue && originalValue.clone) {
  51041. this._originalValue[targetIndex] = originalValue.clone();
  51042. }
  51043. else {
  51044. this._originalValue[targetIndex] = originalValue;
  51045. }
  51046. }
  51047. // Blending
  51048. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51049. if (enableBlending && this._blendingFactor <= 1.0) {
  51050. if (!this._originalBlendValue) {
  51051. var originalValue = destination[path];
  51052. if (originalValue.clone) {
  51053. this._originalBlendValue = originalValue.clone();
  51054. }
  51055. else {
  51056. this._originalBlendValue = originalValue;
  51057. }
  51058. }
  51059. if (this._originalBlendValue.m) { // Matrix
  51060. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51061. if (this._currentValue) {
  51062. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51063. }
  51064. else {
  51065. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51066. }
  51067. }
  51068. else {
  51069. if (this._currentValue) {
  51070. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51071. }
  51072. else {
  51073. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51074. }
  51075. }
  51076. }
  51077. else {
  51078. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51079. }
  51080. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51081. this._blendingFactor += blendingSpeed;
  51082. }
  51083. else {
  51084. this._currentValue = currentValue;
  51085. }
  51086. if (weight !== -1.0) {
  51087. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51088. }
  51089. else {
  51090. destination[path] = this._currentValue;
  51091. }
  51092. if (target.markAsDirty) {
  51093. target.markAsDirty(this._animation.targetProperty);
  51094. }
  51095. };
  51096. /**
  51097. * Gets the loop pmode of the runtime animation
  51098. * @returns Loop Mode
  51099. */
  51100. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51101. if (this._target && this._target.animationPropertiesOverride) {
  51102. return this._target.animationPropertiesOverride.loopMode;
  51103. }
  51104. return this._animation.loopMode;
  51105. };
  51106. /**
  51107. * Move the current animation to a given frame
  51108. * @param frame defines the frame to move to
  51109. */
  51110. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51111. var keys = this._animation.getKeys();
  51112. if (frame < keys[0].frame) {
  51113. frame = keys[0].frame;
  51114. }
  51115. else if (frame > keys[keys.length - 1].frame) {
  51116. frame = keys[keys.length - 1].frame;
  51117. }
  51118. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51119. this.setValue(currentValue, -1);
  51120. };
  51121. /**
  51122. * @hidden Internal use only
  51123. */
  51124. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51125. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51126. this._ratioOffset = this._previousRatio - newRatio;
  51127. };
  51128. /**
  51129. * Execute the current animation
  51130. * @param delay defines the delay to add to the current frame
  51131. * @param from defines the lower bound of the animation range
  51132. * @param to defines the upper bound of the animation range
  51133. * @param loop defines if the current animation must loop
  51134. * @param speedRatio defines the current speed ratio
  51135. * @param weight defines the weight of the animation (default is -1 so no weight)
  51136. * @returns a boolean indicating if the animation has ended
  51137. */
  51138. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51139. if (weight === void 0) { weight = -1.0; }
  51140. var targetPropertyPath = this._animation.targetPropertyPath;
  51141. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51142. this._stopped = true;
  51143. return false;
  51144. }
  51145. var keys = this._animation.getKeys();
  51146. // Return immediately if there is only one key frame.
  51147. if (keys.length === 1) {
  51148. this.setValue(keys[0].value, weight);
  51149. return !loop;
  51150. }
  51151. var returnValue = true;
  51152. // Adding a start key at frame 0 if missing
  51153. if (keys[0].frame !== 0) {
  51154. var newKey = { frame: 0, value: keys[0].value };
  51155. keys.splice(0, 0, newKey);
  51156. }
  51157. // Check limits
  51158. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51159. from = keys[0].frame;
  51160. }
  51161. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51162. to = keys[keys.length - 1].frame;
  51163. }
  51164. //to and from cannot be the same key
  51165. if (from === to) {
  51166. if (from > keys[0].frame) {
  51167. from--;
  51168. }
  51169. else if (to < keys[keys.length - 1].frame) {
  51170. to++;
  51171. }
  51172. }
  51173. // Compute ratio
  51174. var range = to - from;
  51175. var offsetValue;
  51176. // ratio represents the frame delta between from and to
  51177. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51178. var highLimitValue = 0;
  51179. this._previousDelay = delay;
  51180. this._previousRatio = ratio;
  51181. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51182. returnValue = false;
  51183. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51184. }
  51185. else {
  51186. // Get max value if required
  51187. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51188. var keyOffset = to.toString() + from.toString();
  51189. if (!this._offsetsCache[keyOffset]) {
  51190. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51191. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51192. switch (this._animation.dataType) {
  51193. // Float
  51194. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51195. this._offsetsCache[keyOffset] = toValue - fromValue;
  51196. break;
  51197. // Quaternion
  51198. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51199. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51200. break;
  51201. // Vector3
  51202. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51203. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51204. // Vector2
  51205. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51206. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51207. // Size
  51208. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51209. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51210. // Color3
  51211. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51212. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51213. default:
  51214. break;
  51215. }
  51216. this._highLimitsCache[keyOffset] = toValue;
  51217. }
  51218. highLimitValue = this._highLimitsCache[keyOffset];
  51219. offsetValue = this._offsetsCache[keyOffset];
  51220. }
  51221. }
  51222. if (offsetValue === undefined) {
  51223. switch (this._animation.dataType) {
  51224. // Float
  51225. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51226. offsetValue = 0;
  51227. break;
  51228. // Quaternion
  51229. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51230. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51231. break;
  51232. // Vector3
  51233. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51234. offsetValue = BABYLON.Vector3.Zero();
  51235. break;
  51236. // Vector2
  51237. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51238. offsetValue = BABYLON.Vector2.Zero();
  51239. break;
  51240. // Size
  51241. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51242. offsetValue = BABYLON.Size.Zero();
  51243. break;
  51244. // Color3
  51245. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51246. offsetValue = BABYLON.Color3.Black();
  51247. }
  51248. }
  51249. // Compute value
  51250. var repeatCount = (ratio / range) >> 0;
  51251. var currentFrame = returnValue ? from + ratio % range : to;
  51252. // Need to normalize?
  51253. if (this._host && this._host.syncRoot) {
  51254. var syncRoot = this._host.syncRoot;
  51255. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51256. currentFrame = from + (to - from) * hostNormalizedFrame;
  51257. }
  51258. // Reset events if looping
  51259. var events = this._events;
  51260. if (range > 0 && this.currentFrame > currentFrame ||
  51261. range < 0 && this.currentFrame < currentFrame) {
  51262. // Need to reset animation events
  51263. for (var index = 0; index < events.length; index++) {
  51264. if (!events[index].onlyOnce) {
  51265. // reset event, the animation is looping
  51266. events[index].isDone = false;
  51267. }
  51268. }
  51269. }
  51270. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51271. // Set value
  51272. this.setValue(currentValue, weight);
  51273. // Check events
  51274. for (var index = 0; index < events.length; index++) {
  51275. // Make sure current frame has passed event frame and that event frame is within the current range
  51276. // Also, handle both forward and reverse animations
  51277. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51278. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51279. var event = events[index];
  51280. if (!event.isDone) {
  51281. // If event should be done only once, remove it.
  51282. if (event.onlyOnce) {
  51283. events.splice(index, 1);
  51284. index--;
  51285. }
  51286. event.isDone = true;
  51287. event.action();
  51288. } // Don't do anything if the event has already be done.
  51289. }
  51290. }
  51291. if (!returnValue) {
  51292. this._stopped = true;
  51293. }
  51294. return returnValue;
  51295. };
  51296. return RuntimeAnimation;
  51297. }());
  51298. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51299. })(BABYLON || (BABYLON = {}));
  51300. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51301. var BABYLON;
  51302. (function (BABYLON) {
  51303. var Animatable = /** @class */ (function () {
  51304. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51305. if (fromFrame === void 0) { fromFrame = 0; }
  51306. if (toFrame === void 0) { toFrame = 100; }
  51307. if (loopAnimation === void 0) { loopAnimation = false; }
  51308. if (speedRatio === void 0) { speedRatio = 1.0; }
  51309. this.target = target;
  51310. this.fromFrame = fromFrame;
  51311. this.toFrame = toFrame;
  51312. this.loopAnimation = loopAnimation;
  51313. this.onAnimationEnd = onAnimationEnd;
  51314. this._localDelayOffset = null;
  51315. this._pausedDelay = null;
  51316. this._runtimeAnimations = new Array();
  51317. this._paused = false;
  51318. this._speedRatio = 1;
  51319. this._weight = -1.0;
  51320. this.animationStarted = false;
  51321. /**
  51322. * Observer raised when the animation ends
  51323. */
  51324. this.onAnimationEndObservable = new BABYLON.Observable();
  51325. this._scene = scene;
  51326. if (animations) {
  51327. this.appendAnimations(target, animations);
  51328. }
  51329. this._speedRatio = speedRatio;
  51330. scene._activeAnimatables.push(this);
  51331. }
  51332. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51333. /**
  51334. * Gets the root Animatable used to synchronize and normalize animations
  51335. */
  51336. get: function () {
  51337. return this._syncRoot;
  51338. },
  51339. enumerable: true,
  51340. configurable: true
  51341. });
  51342. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51343. /**
  51344. * Gets the current frame of the first RuntimeAnimation
  51345. * Used to synchronize Animatables
  51346. */
  51347. get: function () {
  51348. if (this._runtimeAnimations.length === 0) {
  51349. return 0;
  51350. }
  51351. return this._runtimeAnimations[0].currentFrame;
  51352. },
  51353. enumerable: true,
  51354. configurable: true
  51355. });
  51356. Object.defineProperty(Animatable.prototype, "weight", {
  51357. /**
  51358. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51359. */
  51360. get: function () {
  51361. return this._weight;
  51362. },
  51363. set: function (value) {
  51364. if (value === -1) { // -1 is ok and means no weight
  51365. this._weight = -1;
  51366. return;
  51367. }
  51368. // Else weight must be in [0, 1] range
  51369. this._weight = Math.min(Math.max(value, 0), 1.0);
  51370. },
  51371. enumerable: true,
  51372. configurable: true
  51373. });
  51374. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51375. /**
  51376. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51377. */
  51378. get: function () {
  51379. return this._speedRatio;
  51380. },
  51381. set: function (value) {
  51382. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51383. var animation = this._runtimeAnimations[index];
  51384. animation._prepareForSpeedRatioChange(value);
  51385. }
  51386. this._speedRatio = value;
  51387. },
  51388. enumerable: true,
  51389. configurable: true
  51390. });
  51391. // Methods
  51392. /**
  51393. * Synchronize and normalize current Animatable with a source Animatable
  51394. * This is useful when using animation weights and when animations are not of the same length
  51395. * @param root defines the root Animatable to synchronize with
  51396. * @returns the current Animatable
  51397. */
  51398. Animatable.prototype.syncWith = function (root) {
  51399. this._syncRoot = root;
  51400. if (root) {
  51401. // Make sure this animatable will animate after the root
  51402. var index = this._scene._activeAnimatables.indexOf(this);
  51403. if (index > -1) {
  51404. this._scene._activeAnimatables.splice(index, 1);
  51405. this._scene._activeAnimatables.push(this);
  51406. }
  51407. }
  51408. return this;
  51409. };
  51410. Animatable.prototype.getAnimations = function () {
  51411. return this._runtimeAnimations;
  51412. };
  51413. Animatable.prototype.appendAnimations = function (target, animations) {
  51414. for (var index = 0; index < animations.length; index++) {
  51415. var animation = animations[index];
  51416. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51417. }
  51418. };
  51419. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51420. var runtimeAnimations = this._runtimeAnimations;
  51421. for (var index = 0; index < runtimeAnimations.length; index++) {
  51422. if (runtimeAnimations[index].animation.targetProperty === property) {
  51423. return runtimeAnimations[index].animation;
  51424. }
  51425. }
  51426. return null;
  51427. };
  51428. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51429. var runtimeAnimations = this._runtimeAnimations;
  51430. for (var index = 0; index < runtimeAnimations.length; index++) {
  51431. if (runtimeAnimations[index].animation.targetProperty === property) {
  51432. return runtimeAnimations[index];
  51433. }
  51434. }
  51435. return null;
  51436. };
  51437. Animatable.prototype.reset = function () {
  51438. var runtimeAnimations = this._runtimeAnimations;
  51439. for (var index = 0; index < runtimeAnimations.length; index++) {
  51440. runtimeAnimations[index].reset(true);
  51441. }
  51442. this._localDelayOffset = null;
  51443. this._pausedDelay = null;
  51444. };
  51445. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51446. var runtimeAnimations = this._runtimeAnimations;
  51447. for (var index = 0; index < runtimeAnimations.length; index++) {
  51448. runtimeAnimations[index].animation.enableBlending = true;
  51449. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51450. }
  51451. };
  51452. Animatable.prototype.disableBlending = function () {
  51453. var runtimeAnimations = this._runtimeAnimations;
  51454. for (var index = 0; index < runtimeAnimations.length; index++) {
  51455. runtimeAnimations[index].animation.enableBlending = false;
  51456. }
  51457. };
  51458. Animatable.prototype.goToFrame = function (frame) {
  51459. var runtimeAnimations = this._runtimeAnimations;
  51460. if (runtimeAnimations[0]) {
  51461. var fps = runtimeAnimations[0].animation.framePerSecond;
  51462. var currentFrame = runtimeAnimations[0].currentFrame;
  51463. var adjustTime = frame - currentFrame;
  51464. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51465. if (this._localDelayOffset === null) {
  51466. this._localDelayOffset = 0;
  51467. }
  51468. this._localDelayOffset -= delay;
  51469. }
  51470. for (var index = 0; index < runtimeAnimations.length; index++) {
  51471. runtimeAnimations[index].goToFrame(frame);
  51472. }
  51473. };
  51474. Animatable.prototype.pause = function () {
  51475. if (this._paused) {
  51476. return;
  51477. }
  51478. this._paused = true;
  51479. };
  51480. Animatable.prototype.restart = function () {
  51481. this._paused = false;
  51482. };
  51483. Animatable.prototype._raiseOnAnimationEnd = function () {
  51484. if (this.onAnimationEnd) {
  51485. this.onAnimationEnd();
  51486. }
  51487. this.onAnimationEndObservable.notifyObservers(this);
  51488. };
  51489. Animatable.prototype.stop = function (animationName) {
  51490. if (animationName) {
  51491. var idx = this._scene._activeAnimatables.indexOf(this);
  51492. if (idx > -1) {
  51493. var runtimeAnimations = this._runtimeAnimations;
  51494. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51495. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51496. continue;
  51497. }
  51498. runtimeAnimations[index].dispose();
  51499. runtimeAnimations.splice(index, 1);
  51500. }
  51501. if (runtimeAnimations.length == 0) {
  51502. this._scene._activeAnimatables.splice(idx, 1);
  51503. this._raiseOnAnimationEnd();
  51504. }
  51505. }
  51506. }
  51507. else {
  51508. var index = this._scene._activeAnimatables.indexOf(this);
  51509. if (index > -1) {
  51510. this._scene._activeAnimatables.splice(index, 1);
  51511. var runtimeAnimations = this._runtimeAnimations;
  51512. for (var index = 0; index < runtimeAnimations.length; index++) {
  51513. runtimeAnimations[index].dispose();
  51514. }
  51515. this._raiseOnAnimationEnd();
  51516. }
  51517. }
  51518. };
  51519. /**
  51520. * Wait asynchronously for the animation to end
  51521. * @returns a promise which will be fullfilled when the animation ends
  51522. */
  51523. Animatable.prototype.waitAsync = function () {
  51524. var _this = this;
  51525. return new Promise(function (resolve, reject) {
  51526. _this.onAnimationEndObservable.add(function () {
  51527. resolve(_this);
  51528. }, undefined, undefined, _this, true);
  51529. });
  51530. };
  51531. /** @hidden */
  51532. Animatable.prototype._animate = function (delay) {
  51533. if (this._paused) {
  51534. this.animationStarted = false;
  51535. if (this._pausedDelay === null) {
  51536. this._pausedDelay = delay;
  51537. }
  51538. return true;
  51539. }
  51540. if (this._localDelayOffset === null) {
  51541. this._localDelayOffset = delay;
  51542. this._pausedDelay = null;
  51543. }
  51544. else if (this._pausedDelay !== null) {
  51545. this._localDelayOffset += delay - this._pausedDelay;
  51546. this._pausedDelay = null;
  51547. }
  51548. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51549. return true;
  51550. }
  51551. // Animating
  51552. var running = false;
  51553. var runtimeAnimations = this._runtimeAnimations;
  51554. var index;
  51555. for (index = 0; index < runtimeAnimations.length; index++) {
  51556. var animation = runtimeAnimations[index];
  51557. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51558. running = running || isRunning;
  51559. }
  51560. this.animationStarted = running;
  51561. if (!running) {
  51562. // Remove from active animatables
  51563. index = this._scene._activeAnimatables.indexOf(this);
  51564. this._scene._activeAnimatables.splice(index, 1);
  51565. // Dispose all runtime animations
  51566. for (index = 0; index < runtimeAnimations.length; index++) {
  51567. runtimeAnimations[index].dispose();
  51568. }
  51569. this._raiseOnAnimationEnd();
  51570. this.onAnimationEnd = null;
  51571. this.onAnimationEndObservable.clear();
  51572. }
  51573. return running;
  51574. };
  51575. return Animatable;
  51576. }());
  51577. BABYLON.Animatable = Animatable;
  51578. })(BABYLON || (BABYLON = {}));
  51579. //# sourceMappingURL=babylon.animatable.js.map
  51580. var BABYLON;
  51581. (function (BABYLON) {
  51582. var EasingFunction = /** @class */ (function () {
  51583. function EasingFunction() {
  51584. // Properties
  51585. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51586. }
  51587. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51588. get: function () {
  51589. return EasingFunction._EASINGMODE_EASEIN;
  51590. },
  51591. enumerable: true,
  51592. configurable: true
  51593. });
  51594. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51595. get: function () {
  51596. return EasingFunction._EASINGMODE_EASEOUT;
  51597. },
  51598. enumerable: true,
  51599. configurable: true
  51600. });
  51601. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51602. get: function () {
  51603. return EasingFunction._EASINGMODE_EASEINOUT;
  51604. },
  51605. enumerable: true,
  51606. configurable: true
  51607. });
  51608. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51609. var n = Math.min(Math.max(easingMode, 0), 2);
  51610. this._easingMode = n;
  51611. };
  51612. EasingFunction.prototype.getEasingMode = function () {
  51613. return this._easingMode;
  51614. };
  51615. EasingFunction.prototype.easeInCore = function (gradient) {
  51616. throw new Error('You must implement this method');
  51617. };
  51618. EasingFunction.prototype.ease = function (gradient) {
  51619. switch (this._easingMode) {
  51620. case EasingFunction.EASINGMODE_EASEIN:
  51621. return this.easeInCore(gradient);
  51622. case EasingFunction.EASINGMODE_EASEOUT:
  51623. return (1 - this.easeInCore(1 - gradient));
  51624. }
  51625. if (gradient >= 0.5) {
  51626. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51627. }
  51628. return (this.easeInCore(gradient * 2) * 0.5);
  51629. };
  51630. //Statics
  51631. EasingFunction._EASINGMODE_EASEIN = 0;
  51632. EasingFunction._EASINGMODE_EASEOUT = 1;
  51633. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51634. return EasingFunction;
  51635. }());
  51636. BABYLON.EasingFunction = EasingFunction;
  51637. var CircleEase = /** @class */ (function (_super) {
  51638. __extends(CircleEase, _super);
  51639. function CircleEase() {
  51640. return _super !== null && _super.apply(this, arguments) || this;
  51641. }
  51642. CircleEase.prototype.easeInCore = function (gradient) {
  51643. gradient = Math.max(0, Math.min(1, gradient));
  51644. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51645. };
  51646. return CircleEase;
  51647. }(EasingFunction));
  51648. BABYLON.CircleEase = CircleEase;
  51649. var BackEase = /** @class */ (function (_super) {
  51650. __extends(BackEase, _super);
  51651. function BackEase(amplitude) {
  51652. if (amplitude === void 0) { amplitude = 1; }
  51653. var _this = _super.call(this) || this;
  51654. _this.amplitude = amplitude;
  51655. return _this;
  51656. }
  51657. BackEase.prototype.easeInCore = function (gradient) {
  51658. var num = Math.max(0, this.amplitude);
  51659. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51660. };
  51661. return BackEase;
  51662. }(EasingFunction));
  51663. BABYLON.BackEase = BackEase;
  51664. var BounceEase = /** @class */ (function (_super) {
  51665. __extends(BounceEase, _super);
  51666. function BounceEase(bounces, bounciness) {
  51667. if (bounces === void 0) { bounces = 3; }
  51668. if (bounciness === void 0) { bounciness = 2; }
  51669. var _this = _super.call(this) || this;
  51670. _this.bounces = bounces;
  51671. _this.bounciness = bounciness;
  51672. return _this;
  51673. }
  51674. BounceEase.prototype.easeInCore = function (gradient) {
  51675. var y = Math.max(0.0, this.bounces);
  51676. var bounciness = this.bounciness;
  51677. if (bounciness <= 1.0) {
  51678. bounciness = 1.001;
  51679. }
  51680. var num9 = Math.pow(bounciness, y);
  51681. var num5 = 1.0 - bounciness;
  51682. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51683. var num15 = gradient * num4;
  51684. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51685. var num3 = Math.floor(num65);
  51686. var num13 = num3 + 1.0;
  51687. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51688. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51689. var num7 = (num8 + num12) * 0.5;
  51690. var num6 = gradient - num7;
  51691. var num2 = num7 - num8;
  51692. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51693. };
  51694. return BounceEase;
  51695. }(EasingFunction));
  51696. BABYLON.BounceEase = BounceEase;
  51697. var CubicEase = /** @class */ (function (_super) {
  51698. __extends(CubicEase, _super);
  51699. function CubicEase() {
  51700. return _super !== null && _super.apply(this, arguments) || this;
  51701. }
  51702. CubicEase.prototype.easeInCore = function (gradient) {
  51703. return (gradient * gradient * gradient);
  51704. };
  51705. return CubicEase;
  51706. }(EasingFunction));
  51707. BABYLON.CubicEase = CubicEase;
  51708. var ElasticEase = /** @class */ (function (_super) {
  51709. __extends(ElasticEase, _super);
  51710. function ElasticEase(oscillations, springiness) {
  51711. if (oscillations === void 0) { oscillations = 3; }
  51712. if (springiness === void 0) { springiness = 3; }
  51713. var _this = _super.call(this) || this;
  51714. _this.oscillations = oscillations;
  51715. _this.springiness = springiness;
  51716. return _this;
  51717. }
  51718. ElasticEase.prototype.easeInCore = function (gradient) {
  51719. var num2;
  51720. var num3 = Math.max(0.0, this.oscillations);
  51721. var num = Math.max(0.0, this.springiness);
  51722. if (num == 0) {
  51723. num2 = gradient;
  51724. }
  51725. else {
  51726. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51727. }
  51728. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51729. };
  51730. return ElasticEase;
  51731. }(EasingFunction));
  51732. BABYLON.ElasticEase = ElasticEase;
  51733. var ExponentialEase = /** @class */ (function (_super) {
  51734. __extends(ExponentialEase, _super);
  51735. function ExponentialEase(exponent) {
  51736. if (exponent === void 0) { exponent = 2; }
  51737. var _this = _super.call(this) || this;
  51738. _this.exponent = exponent;
  51739. return _this;
  51740. }
  51741. ExponentialEase.prototype.easeInCore = function (gradient) {
  51742. if (this.exponent <= 0) {
  51743. return gradient;
  51744. }
  51745. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51746. };
  51747. return ExponentialEase;
  51748. }(EasingFunction));
  51749. BABYLON.ExponentialEase = ExponentialEase;
  51750. var PowerEase = /** @class */ (function (_super) {
  51751. __extends(PowerEase, _super);
  51752. function PowerEase(power) {
  51753. if (power === void 0) { power = 2; }
  51754. var _this = _super.call(this) || this;
  51755. _this.power = power;
  51756. return _this;
  51757. }
  51758. PowerEase.prototype.easeInCore = function (gradient) {
  51759. var y = Math.max(0.0, this.power);
  51760. return Math.pow(gradient, y);
  51761. };
  51762. return PowerEase;
  51763. }(EasingFunction));
  51764. BABYLON.PowerEase = PowerEase;
  51765. var QuadraticEase = /** @class */ (function (_super) {
  51766. __extends(QuadraticEase, _super);
  51767. function QuadraticEase() {
  51768. return _super !== null && _super.apply(this, arguments) || this;
  51769. }
  51770. QuadraticEase.prototype.easeInCore = function (gradient) {
  51771. return (gradient * gradient);
  51772. };
  51773. return QuadraticEase;
  51774. }(EasingFunction));
  51775. BABYLON.QuadraticEase = QuadraticEase;
  51776. var QuarticEase = /** @class */ (function (_super) {
  51777. __extends(QuarticEase, _super);
  51778. function QuarticEase() {
  51779. return _super !== null && _super.apply(this, arguments) || this;
  51780. }
  51781. QuarticEase.prototype.easeInCore = function (gradient) {
  51782. return (gradient * gradient * gradient * gradient);
  51783. };
  51784. return QuarticEase;
  51785. }(EasingFunction));
  51786. BABYLON.QuarticEase = QuarticEase;
  51787. var QuinticEase = /** @class */ (function (_super) {
  51788. __extends(QuinticEase, _super);
  51789. function QuinticEase() {
  51790. return _super !== null && _super.apply(this, arguments) || this;
  51791. }
  51792. QuinticEase.prototype.easeInCore = function (gradient) {
  51793. return (gradient * gradient * gradient * gradient * gradient);
  51794. };
  51795. return QuinticEase;
  51796. }(EasingFunction));
  51797. BABYLON.QuinticEase = QuinticEase;
  51798. var SineEase = /** @class */ (function (_super) {
  51799. __extends(SineEase, _super);
  51800. function SineEase() {
  51801. return _super !== null && _super.apply(this, arguments) || this;
  51802. }
  51803. SineEase.prototype.easeInCore = function (gradient) {
  51804. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51805. };
  51806. return SineEase;
  51807. }(EasingFunction));
  51808. BABYLON.SineEase = SineEase;
  51809. var BezierCurveEase = /** @class */ (function (_super) {
  51810. __extends(BezierCurveEase, _super);
  51811. function BezierCurveEase(x1, y1, x2, y2) {
  51812. if (x1 === void 0) { x1 = 0; }
  51813. if (y1 === void 0) { y1 = 0; }
  51814. if (x2 === void 0) { x2 = 1; }
  51815. if (y2 === void 0) { y2 = 1; }
  51816. var _this = _super.call(this) || this;
  51817. _this.x1 = x1;
  51818. _this.y1 = y1;
  51819. _this.x2 = x2;
  51820. _this.y2 = y2;
  51821. return _this;
  51822. }
  51823. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51824. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51825. };
  51826. return BezierCurveEase;
  51827. }(EasingFunction));
  51828. BABYLON.BezierCurveEase = BezierCurveEase;
  51829. })(BABYLON || (BABYLON = {}));
  51830. //# sourceMappingURL=babylon.easing.js.map
  51831. var BABYLON;
  51832. (function (BABYLON) {
  51833. /**
  51834. * A Condition applied to an Action
  51835. */
  51836. var Condition = /** @class */ (function () {
  51837. /**
  51838. * Creates a new Condition
  51839. * @param actionManager the manager of the action the condition is applied to
  51840. */
  51841. function Condition(actionManager) {
  51842. this._actionManager = actionManager;
  51843. }
  51844. /**
  51845. * Check if the current condition is valid
  51846. * @returns a boolean
  51847. */
  51848. Condition.prototype.isValid = function () {
  51849. return true;
  51850. };
  51851. /**
  51852. * Internal only
  51853. * @hidden
  51854. */
  51855. Condition.prototype._getProperty = function (propertyPath) {
  51856. return this._actionManager._getProperty(propertyPath);
  51857. };
  51858. /**
  51859. * Internal only
  51860. * @hidden
  51861. */
  51862. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51863. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51864. };
  51865. /**
  51866. * Serialize placeholder for child classes
  51867. * @returns the serialized object
  51868. */
  51869. Condition.prototype.serialize = function () {
  51870. };
  51871. /**
  51872. * Internal only
  51873. * @hidden
  51874. */
  51875. Condition.prototype._serialize = function (serializedCondition) {
  51876. return {
  51877. type: 2,
  51878. children: [],
  51879. name: serializedCondition.name,
  51880. properties: serializedCondition.properties
  51881. };
  51882. };
  51883. return Condition;
  51884. }());
  51885. BABYLON.Condition = Condition;
  51886. /**
  51887. * Defines specific conditional operators as extensions of Condition
  51888. */
  51889. var ValueCondition = /** @class */ (function (_super) {
  51890. __extends(ValueCondition, _super);
  51891. /**
  51892. * Creates a new ValueCondition
  51893. * @param actionManager manager for the action the condition applies to
  51894. * @param target for the action
  51895. * @param propertyPath path to specify the property of the target the conditional operator uses
  51896. * @param value the value compared by the conditional operator against the current value of the property
  51897. * @param operator the conditional operator, default ValueCondition.IsEqual
  51898. */
  51899. function ValueCondition(actionManager, target,
  51900. /** path to specify the property of the target the conditional operator uses */
  51901. propertyPath,
  51902. /** the value compared by the conditional operator against the current value of the property */
  51903. value,
  51904. /** the conditional operator, default ValueCondition.IsEqual */
  51905. operator) {
  51906. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  51907. var _this = _super.call(this, actionManager) || this;
  51908. _this.propertyPath = propertyPath;
  51909. _this.value = value;
  51910. _this.operator = operator;
  51911. _this._target = target;
  51912. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  51913. _this._property = _this._getProperty(_this.propertyPath);
  51914. return _this;
  51915. }
  51916. Object.defineProperty(ValueCondition, "IsEqual", {
  51917. /**
  51918. * returns the number for IsEqual
  51919. */
  51920. get: function () {
  51921. return ValueCondition._IsEqual;
  51922. },
  51923. enumerable: true,
  51924. configurable: true
  51925. });
  51926. Object.defineProperty(ValueCondition, "IsDifferent", {
  51927. /**
  51928. * Returns the number for IsDifferent
  51929. */
  51930. get: function () {
  51931. return ValueCondition._IsDifferent;
  51932. },
  51933. enumerable: true,
  51934. configurable: true
  51935. });
  51936. Object.defineProperty(ValueCondition, "IsGreater", {
  51937. /**
  51938. * Returns the number for IsGreater
  51939. */
  51940. get: function () {
  51941. return ValueCondition._IsGreater;
  51942. },
  51943. enumerable: true,
  51944. configurable: true
  51945. });
  51946. Object.defineProperty(ValueCondition, "IsLesser", {
  51947. /**
  51948. * Returns the number for IsLesser
  51949. */
  51950. get: function () {
  51951. return ValueCondition._IsLesser;
  51952. },
  51953. enumerable: true,
  51954. configurable: true
  51955. });
  51956. /**
  51957. * Compares the given value with the property value for the specified conditional operator
  51958. * @returns the result of the comparison
  51959. */
  51960. ValueCondition.prototype.isValid = function () {
  51961. switch (this.operator) {
  51962. case ValueCondition.IsGreater:
  51963. return this._effectiveTarget[this._property] > this.value;
  51964. case ValueCondition.IsLesser:
  51965. return this._effectiveTarget[this._property] < this.value;
  51966. case ValueCondition.IsEqual:
  51967. case ValueCondition.IsDifferent:
  51968. var check;
  51969. if (this.value.equals) {
  51970. check = this.value.equals(this._effectiveTarget[this._property]);
  51971. }
  51972. else {
  51973. check = this.value === this._effectiveTarget[this._property];
  51974. }
  51975. return this.operator === ValueCondition.IsEqual ? check : !check;
  51976. }
  51977. return false;
  51978. };
  51979. /**
  51980. * Serialize the ValueCondition into a JSON compatible object
  51981. * @returns serialization object
  51982. */
  51983. ValueCondition.prototype.serialize = function () {
  51984. return this._serialize({
  51985. name: "ValueCondition",
  51986. properties: [
  51987. BABYLON.Action._GetTargetProperty(this._target),
  51988. { name: "propertyPath", value: this.propertyPath },
  51989. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  51990. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  51991. ]
  51992. });
  51993. };
  51994. /**
  51995. * Gets the name of the conditional operator for the ValueCondition
  51996. * @param operator the conditional operator
  51997. * @returns the name
  51998. */
  51999. ValueCondition.GetOperatorName = function (operator) {
  52000. switch (operator) {
  52001. case ValueCondition._IsEqual: return "IsEqual";
  52002. case ValueCondition._IsDifferent: return "IsDifferent";
  52003. case ValueCondition._IsGreater: return "IsGreater";
  52004. case ValueCondition._IsLesser: return "IsLesser";
  52005. default: return "";
  52006. }
  52007. };
  52008. /**
  52009. * Internal only
  52010. * @hidden
  52011. */
  52012. ValueCondition._IsEqual = 0;
  52013. /**
  52014. * Internal only
  52015. * @hidden
  52016. */
  52017. ValueCondition._IsDifferent = 1;
  52018. /**
  52019. * Internal only
  52020. * @hidden
  52021. */
  52022. ValueCondition._IsGreater = 2;
  52023. /**
  52024. * Internal only
  52025. * @hidden
  52026. */
  52027. ValueCondition._IsLesser = 3;
  52028. return ValueCondition;
  52029. }(Condition));
  52030. BABYLON.ValueCondition = ValueCondition;
  52031. /**
  52032. * Defines a predicate condition as an extension of Condition
  52033. */
  52034. var PredicateCondition = /** @class */ (function (_super) {
  52035. __extends(PredicateCondition, _super);
  52036. /**
  52037. * Creates a new PredicateCondition
  52038. * @param actionManager manager for the action the condition applies to
  52039. * @param predicate defines the predicate function used to validate the condition
  52040. */
  52041. function PredicateCondition(actionManager,
  52042. /** defines the predicate function used to validate the condition */
  52043. predicate) {
  52044. var _this = _super.call(this, actionManager) || this;
  52045. _this.predicate = predicate;
  52046. return _this;
  52047. }
  52048. /**
  52049. * @returns the validity of the predicate condition
  52050. */
  52051. PredicateCondition.prototype.isValid = function () {
  52052. return this.predicate();
  52053. };
  52054. return PredicateCondition;
  52055. }(Condition));
  52056. BABYLON.PredicateCondition = PredicateCondition;
  52057. /**
  52058. * Defines a state condition as an extension of Condition
  52059. */
  52060. var StateCondition = /** @class */ (function (_super) {
  52061. __extends(StateCondition, _super);
  52062. /**
  52063. * Creates a new StateCondition
  52064. * @param actionManager manager for the action the condition applies to
  52065. * @param target of the condition
  52066. * @param value to compare with target state
  52067. */
  52068. function StateCondition(actionManager, target, value) {
  52069. var _this = _super.call(this, actionManager) || this;
  52070. _this.value = value;
  52071. _this._target = target;
  52072. return _this;
  52073. }
  52074. /**
  52075. * @returns the validity of the state
  52076. */
  52077. StateCondition.prototype.isValid = function () {
  52078. return this._target.state === this.value;
  52079. };
  52080. /**
  52081. * Serialize the StateCondition into a JSON compatible object
  52082. * @returns serialization object
  52083. */
  52084. StateCondition.prototype.serialize = function () {
  52085. return this._serialize({
  52086. name: "StateCondition",
  52087. properties: [
  52088. BABYLON.Action._GetTargetProperty(this._target),
  52089. { name: "value", value: this.value }
  52090. ]
  52091. });
  52092. };
  52093. return StateCondition;
  52094. }(Condition));
  52095. BABYLON.StateCondition = StateCondition;
  52096. })(BABYLON || (BABYLON = {}));
  52097. //# sourceMappingURL=babylon.condition.js.map
  52098. var BABYLON;
  52099. (function (BABYLON) {
  52100. /**
  52101. * The action to be carried out following a trigger
  52102. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52103. */
  52104. var Action = /** @class */ (function () {
  52105. /**
  52106. * Creates a new Action
  52107. * @param triggerOptions the trigger, with or without parameters, for the action
  52108. * @param condition an optional determinant of action
  52109. */
  52110. function Action(
  52111. /** the trigger, with or without parameters, for the action */
  52112. triggerOptions, condition) {
  52113. this.triggerOptions = triggerOptions;
  52114. /**
  52115. * An event triggered prior to action being executed.
  52116. */
  52117. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52118. if (triggerOptions.parameter) {
  52119. this.trigger = triggerOptions.trigger;
  52120. this._triggerParameter = triggerOptions.parameter;
  52121. }
  52122. else {
  52123. this.trigger = triggerOptions;
  52124. }
  52125. this._nextActiveAction = this;
  52126. this._condition = condition;
  52127. }
  52128. /**
  52129. * Internal only
  52130. * @hidden
  52131. */
  52132. Action.prototype._prepare = function () {
  52133. };
  52134. /**
  52135. * Gets the trigger parameters
  52136. * @returns the trigger parameters
  52137. */
  52138. Action.prototype.getTriggerParameter = function () {
  52139. return this._triggerParameter;
  52140. };
  52141. /**
  52142. * Internal only - executes current action event
  52143. * @hidden
  52144. */
  52145. Action.prototype._executeCurrent = function (evt) {
  52146. if (this._nextActiveAction._condition) {
  52147. var condition = this._nextActiveAction._condition;
  52148. var currentRenderId = this._actionManager.getScene().getRenderId();
  52149. // We cache the current evaluation for the current frame
  52150. if (condition._evaluationId === currentRenderId) {
  52151. if (!condition._currentResult) {
  52152. return;
  52153. }
  52154. }
  52155. else {
  52156. condition._evaluationId = currentRenderId;
  52157. if (!condition.isValid()) {
  52158. condition._currentResult = false;
  52159. return;
  52160. }
  52161. condition._currentResult = true;
  52162. }
  52163. }
  52164. this.onBeforeExecuteObservable.notifyObservers(this);
  52165. this._nextActiveAction.execute(evt);
  52166. this.skipToNextActiveAction();
  52167. };
  52168. /**
  52169. * Execute placeholder for child classes
  52170. * @param evt optional action event
  52171. */
  52172. Action.prototype.execute = function (evt) {
  52173. };
  52174. /**
  52175. * Skips to next active action
  52176. */
  52177. Action.prototype.skipToNextActiveAction = function () {
  52178. if (this._nextActiveAction._child) {
  52179. if (!this._nextActiveAction._child._actionManager) {
  52180. this._nextActiveAction._child._actionManager = this._actionManager;
  52181. }
  52182. this._nextActiveAction = this._nextActiveAction._child;
  52183. }
  52184. else {
  52185. this._nextActiveAction = this;
  52186. }
  52187. };
  52188. /**
  52189. * Adds action to chain of actions, may be a DoNothingAction
  52190. * @param action defines the next action to execute
  52191. * @returns The action passed in
  52192. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52193. */
  52194. Action.prototype.then = function (action) {
  52195. this._child = action;
  52196. action._actionManager = this._actionManager;
  52197. action._prepare();
  52198. return action;
  52199. };
  52200. /**
  52201. * Internal only
  52202. * @hidden
  52203. */
  52204. Action.prototype._getProperty = function (propertyPath) {
  52205. return this._actionManager._getProperty(propertyPath);
  52206. };
  52207. /**
  52208. * Internal only
  52209. * @hidden
  52210. */
  52211. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52212. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52213. };
  52214. /**
  52215. * Serialize placeholder for child classes
  52216. * @param parent of child
  52217. * @returns the serialized object
  52218. */
  52219. Action.prototype.serialize = function (parent) {
  52220. };
  52221. /**
  52222. * Internal only called by serialize
  52223. * @hidden
  52224. */
  52225. Action.prototype._serialize = function (serializedAction, parent) {
  52226. var serializationObject = {
  52227. type: 1,
  52228. children: [],
  52229. name: serializedAction.name,
  52230. properties: serializedAction.properties || []
  52231. };
  52232. // Serialize child
  52233. if (this._child) {
  52234. this._child.serialize(serializationObject);
  52235. }
  52236. // Check if "this" has a condition
  52237. if (this._condition) {
  52238. var serializedCondition = this._condition.serialize();
  52239. serializedCondition.children.push(serializationObject);
  52240. if (parent) {
  52241. parent.children.push(serializedCondition);
  52242. }
  52243. return serializedCondition;
  52244. }
  52245. if (parent) {
  52246. parent.children.push(serializationObject);
  52247. }
  52248. return serializationObject;
  52249. };
  52250. /**
  52251. * Internal only
  52252. * @hidden
  52253. */
  52254. Action._SerializeValueAsString = function (value) {
  52255. if (typeof value === "number") {
  52256. return value.toString();
  52257. }
  52258. if (typeof value === "boolean") {
  52259. return value ? "true" : "false";
  52260. }
  52261. if (value instanceof BABYLON.Vector2) {
  52262. return value.x + ", " + value.y;
  52263. }
  52264. if (value instanceof BABYLON.Vector3) {
  52265. return value.x + ", " + value.y + ", " + value.z;
  52266. }
  52267. if (value instanceof BABYLON.Color3) {
  52268. return value.r + ", " + value.g + ", " + value.b;
  52269. }
  52270. if (value instanceof BABYLON.Color4) {
  52271. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52272. }
  52273. return value; // string
  52274. };
  52275. /**
  52276. * Internal only
  52277. * @hidden
  52278. */
  52279. Action._GetTargetProperty = function (target) {
  52280. return {
  52281. name: "target",
  52282. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52283. : target instanceof BABYLON.Light ? "LightProperties"
  52284. : target instanceof BABYLON.Camera ? "CameraProperties"
  52285. : "SceneProperties",
  52286. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52287. };
  52288. };
  52289. return Action;
  52290. }());
  52291. BABYLON.Action = Action;
  52292. })(BABYLON || (BABYLON = {}));
  52293. //# sourceMappingURL=babylon.action.js.map
  52294. var BABYLON;
  52295. (function (BABYLON) {
  52296. /**
  52297. * ActionEvent is the event being sent when an action is triggered.
  52298. */
  52299. var ActionEvent = /** @class */ (function () {
  52300. /**
  52301. * Creates a new ActionEvent
  52302. * @param source The mesh or sprite that triggered the action
  52303. * @param pointerX The X mouse cursor position at the time of the event
  52304. * @param pointerY The Y mouse cursor position at the time of the event
  52305. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52306. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52307. * @param additionalData additional data for the event
  52308. */
  52309. function ActionEvent(
  52310. /** The mesh or sprite that triggered the action */
  52311. source,
  52312. /** The X mouse cursor position at the time of the event */
  52313. pointerX,
  52314. /** The Y mouse cursor position at the time of the event */
  52315. pointerY,
  52316. /** The mesh that is currently pointed at (can be null) */
  52317. meshUnderPointer,
  52318. /** the original (browser) event that triggered the ActionEvent */
  52319. sourceEvent,
  52320. /** additional data for the event */
  52321. additionalData) {
  52322. this.source = source;
  52323. this.pointerX = pointerX;
  52324. this.pointerY = pointerY;
  52325. this.meshUnderPointer = meshUnderPointer;
  52326. this.sourceEvent = sourceEvent;
  52327. this.additionalData = additionalData;
  52328. }
  52329. /**
  52330. * Helper function to auto-create an ActionEvent from a source mesh.
  52331. * @param source The source mesh that triggered the event
  52332. * @param evt The original (browser) event
  52333. * @param additionalData additional data for the event
  52334. * @returns the new ActionEvent
  52335. */
  52336. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52337. var scene = source.getScene();
  52338. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52339. };
  52340. /**
  52341. * Helper function to auto-create an ActionEvent from a source sprite
  52342. * @param source The source sprite that triggered the event
  52343. * @param scene Scene associated with the sprite
  52344. * @param evt The original (browser) event
  52345. * @param additionalData additional data for the event
  52346. * @returns the new ActionEvent
  52347. */
  52348. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52349. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52350. };
  52351. /**
  52352. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52353. * @param scene the scene where the event occurred
  52354. * @param evt The original (browser) event
  52355. * @returns the new ActionEvent
  52356. */
  52357. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52358. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52359. };
  52360. /**
  52361. * Helper function to auto-create an ActionEvent from a primitive
  52362. * @param prim defines the target primitive
  52363. * @param pointerPos defines the pointer position
  52364. * @param evt The original (browser) event
  52365. * @param additionalData additional data for the event
  52366. * @returns the new ActionEvent
  52367. */
  52368. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52369. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52370. };
  52371. return ActionEvent;
  52372. }());
  52373. BABYLON.ActionEvent = ActionEvent;
  52374. /**
  52375. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52376. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52377. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52378. */
  52379. var ActionManager = /** @class */ (function () {
  52380. /**
  52381. * Creates a new action manager
  52382. * @param scene defines the hosting scene
  52383. */
  52384. function ActionManager(scene) {
  52385. // Members
  52386. /** Gets the list of actions */
  52387. this.actions = new Array();
  52388. /** Gets the cursor to use when hovering items */
  52389. this.hoverCursor = '';
  52390. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52391. scene._actionManagers.push(this);
  52392. }
  52393. Object.defineProperty(ActionManager, "NothingTrigger", {
  52394. /**
  52395. * Nothing
  52396. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52397. */
  52398. get: function () {
  52399. return ActionManager._NothingTrigger;
  52400. },
  52401. enumerable: true,
  52402. configurable: true
  52403. });
  52404. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52405. /**
  52406. * On pick
  52407. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52408. */
  52409. get: function () {
  52410. return ActionManager._OnPickTrigger;
  52411. },
  52412. enumerable: true,
  52413. configurable: true
  52414. });
  52415. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52416. /**
  52417. * On left pick
  52418. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52419. */
  52420. get: function () {
  52421. return ActionManager._OnLeftPickTrigger;
  52422. },
  52423. enumerable: true,
  52424. configurable: true
  52425. });
  52426. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52427. /**
  52428. * On right pick
  52429. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52430. */
  52431. get: function () {
  52432. return ActionManager._OnRightPickTrigger;
  52433. },
  52434. enumerable: true,
  52435. configurable: true
  52436. });
  52437. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52438. /**
  52439. * On center pick
  52440. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52441. */
  52442. get: function () {
  52443. return ActionManager._OnCenterPickTrigger;
  52444. },
  52445. enumerable: true,
  52446. configurable: true
  52447. });
  52448. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52449. /**
  52450. * On pick down
  52451. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52452. */
  52453. get: function () {
  52454. return ActionManager._OnPickDownTrigger;
  52455. },
  52456. enumerable: true,
  52457. configurable: true
  52458. });
  52459. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52460. /**
  52461. * On double pick
  52462. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52463. */
  52464. get: function () {
  52465. return ActionManager._OnDoublePickTrigger;
  52466. },
  52467. enumerable: true,
  52468. configurable: true
  52469. });
  52470. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52471. /**
  52472. * On pick up
  52473. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52474. */
  52475. get: function () {
  52476. return ActionManager._OnPickUpTrigger;
  52477. },
  52478. enumerable: true,
  52479. configurable: true
  52480. });
  52481. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52482. /**
  52483. * On pick out.
  52484. * This trigger will only be raised if you also declared a OnPickDown
  52485. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52486. */
  52487. get: function () {
  52488. return ActionManager._OnPickOutTrigger;
  52489. },
  52490. enumerable: true,
  52491. configurable: true
  52492. });
  52493. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52494. /**
  52495. * On long press
  52496. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52497. */
  52498. get: function () {
  52499. return ActionManager._OnLongPressTrigger;
  52500. },
  52501. enumerable: true,
  52502. configurable: true
  52503. });
  52504. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52505. /**
  52506. * On pointer over
  52507. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52508. */
  52509. get: function () {
  52510. return ActionManager._OnPointerOverTrigger;
  52511. },
  52512. enumerable: true,
  52513. configurable: true
  52514. });
  52515. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52516. /**
  52517. * On pointer out
  52518. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52519. */
  52520. get: function () {
  52521. return ActionManager._OnPointerOutTrigger;
  52522. },
  52523. enumerable: true,
  52524. configurable: true
  52525. });
  52526. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52527. /**
  52528. * On every frame
  52529. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52530. */
  52531. get: function () {
  52532. return ActionManager._OnEveryFrameTrigger;
  52533. },
  52534. enumerable: true,
  52535. configurable: true
  52536. });
  52537. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52538. /**
  52539. * On intersection enter
  52540. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52541. */
  52542. get: function () {
  52543. return ActionManager._OnIntersectionEnterTrigger;
  52544. },
  52545. enumerable: true,
  52546. configurable: true
  52547. });
  52548. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52549. /**
  52550. * On intersection exit
  52551. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52552. */
  52553. get: function () {
  52554. return ActionManager._OnIntersectionExitTrigger;
  52555. },
  52556. enumerable: true,
  52557. configurable: true
  52558. });
  52559. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52560. /**
  52561. * On key down
  52562. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52563. */
  52564. get: function () {
  52565. return ActionManager._OnKeyDownTrigger;
  52566. },
  52567. enumerable: true,
  52568. configurable: true
  52569. });
  52570. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52571. /**
  52572. * On key up
  52573. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52574. */
  52575. get: function () {
  52576. return ActionManager._OnKeyUpTrigger;
  52577. },
  52578. enumerable: true,
  52579. configurable: true
  52580. });
  52581. // Methods
  52582. /**
  52583. * Releases all associated resources
  52584. */
  52585. ActionManager.prototype.dispose = function () {
  52586. var index = this._scene._actionManagers.indexOf(this);
  52587. for (var i = 0; i < this.actions.length; i++) {
  52588. var action = this.actions[i];
  52589. ActionManager.Triggers[action.trigger]--;
  52590. if (ActionManager.Triggers[action.trigger] === 0) {
  52591. delete ActionManager.Triggers[action.trigger];
  52592. }
  52593. }
  52594. if (index > -1) {
  52595. this._scene._actionManagers.splice(index, 1);
  52596. }
  52597. };
  52598. /**
  52599. * Gets hosting scene
  52600. * @returns the hosting scene
  52601. */
  52602. ActionManager.prototype.getScene = function () {
  52603. return this._scene;
  52604. };
  52605. /**
  52606. * Does this action manager handles actions of any of the given triggers
  52607. * @param triggers defines the triggers to be tested
  52608. * @return a boolean indicating whether one (or more) of the triggers is handled
  52609. */
  52610. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52611. for (var index = 0; index < this.actions.length; index++) {
  52612. var action = this.actions[index];
  52613. if (triggers.indexOf(action.trigger) > -1) {
  52614. return true;
  52615. }
  52616. }
  52617. return false;
  52618. };
  52619. /**
  52620. * Does this action manager handles actions of a given trigger
  52621. * @param trigger defines the trigger to be tested
  52622. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52623. * @return whether the trigger is handled
  52624. */
  52625. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52626. for (var index = 0; index < this.actions.length; index++) {
  52627. var action = this.actions[index];
  52628. if (action.trigger === trigger) {
  52629. if (parameterPredicate) {
  52630. if (parameterPredicate(action.getTriggerParameter())) {
  52631. return true;
  52632. }
  52633. }
  52634. else {
  52635. return true;
  52636. }
  52637. }
  52638. }
  52639. return false;
  52640. };
  52641. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52642. /**
  52643. * Does this action manager has pointer triggers
  52644. */
  52645. get: function () {
  52646. for (var index = 0; index < this.actions.length; index++) {
  52647. var action = this.actions[index];
  52648. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52649. return true;
  52650. }
  52651. }
  52652. return false;
  52653. },
  52654. enumerable: true,
  52655. configurable: true
  52656. });
  52657. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52658. /**
  52659. * Does this action manager has pick triggers
  52660. */
  52661. get: function () {
  52662. for (var index = 0; index < this.actions.length; index++) {
  52663. var action = this.actions[index];
  52664. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52665. return true;
  52666. }
  52667. }
  52668. return false;
  52669. },
  52670. enumerable: true,
  52671. configurable: true
  52672. });
  52673. Object.defineProperty(ActionManager, "HasTriggers", {
  52674. /**
  52675. * Does exist one action manager with at least one trigger
  52676. **/
  52677. get: function () {
  52678. for (var t in ActionManager.Triggers) {
  52679. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52680. return true;
  52681. }
  52682. }
  52683. return false;
  52684. },
  52685. enumerable: true,
  52686. configurable: true
  52687. });
  52688. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52689. /**
  52690. * Does exist one action manager with at least one pick trigger
  52691. **/
  52692. get: function () {
  52693. for (var t in ActionManager.Triggers) {
  52694. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52695. var t_int = parseInt(t);
  52696. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52697. return true;
  52698. }
  52699. }
  52700. }
  52701. return false;
  52702. },
  52703. enumerable: true,
  52704. configurable: true
  52705. });
  52706. /**
  52707. * Does exist one action manager that handles actions of a given trigger
  52708. * @param trigger defines the trigger to be tested
  52709. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52710. **/
  52711. ActionManager.HasSpecificTrigger = function (trigger) {
  52712. for (var t in ActionManager.Triggers) {
  52713. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52714. var t_int = parseInt(t);
  52715. if (t_int === trigger) {
  52716. return true;
  52717. }
  52718. }
  52719. }
  52720. return false;
  52721. };
  52722. /**
  52723. * Registers an action to this action manager
  52724. * @param action defines the action to be registered
  52725. * @return the action amended (prepared) after registration
  52726. */
  52727. ActionManager.prototype.registerAction = function (action) {
  52728. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52729. if (this.getScene().actionManager !== this) {
  52730. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52731. return null;
  52732. }
  52733. }
  52734. this.actions.push(action);
  52735. if (ActionManager.Triggers[action.trigger]) {
  52736. ActionManager.Triggers[action.trigger]++;
  52737. }
  52738. else {
  52739. ActionManager.Triggers[action.trigger] = 1;
  52740. }
  52741. action._actionManager = this;
  52742. action._prepare();
  52743. return action;
  52744. };
  52745. /**
  52746. * Unregisters an action to this action manager
  52747. * @param action defines the action to be unregistered
  52748. * @return a boolean indicating whether the action has been unregistered
  52749. */
  52750. ActionManager.prototype.unregisterAction = function (action) {
  52751. var index = this.actions.indexOf(action);
  52752. if (index !== -1) {
  52753. this.actions.splice(index, 1);
  52754. ActionManager.Triggers[action.trigger] -= 1;
  52755. if (ActionManager.Triggers[action.trigger] === 0) {
  52756. delete ActionManager.Triggers[action.trigger];
  52757. }
  52758. delete action._actionManager;
  52759. return true;
  52760. }
  52761. return false;
  52762. };
  52763. /**
  52764. * Process a specific trigger
  52765. * @param trigger defines the trigger to process
  52766. * @param evt defines the event details to be processed
  52767. */
  52768. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52769. for (var index = 0; index < this.actions.length; index++) {
  52770. var action = this.actions[index];
  52771. if (action.trigger === trigger) {
  52772. if (evt) {
  52773. if (trigger === ActionManager.OnKeyUpTrigger
  52774. || trigger === ActionManager.OnKeyDownTrigger) {
  52775. var parameter = action.getTriggerParameter();
  52776. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52777. if (!parameter.toLowerCase) {
  52778. continue;
  52779. }
  52780. var lowerCase = parameter.toLowerCase();
  52781. if (lowerCase !== evt.sourceEvent.key) {
  52782. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52783. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52784. if (actualkey !== lowerCase) {
  52785. continue;
  52786. }
  52787. }
  52788. }
  52789. }
  52790. }
  52791. action._executeCurrent(evt);
  52792. }
  52793. }
  52794. };
  52795. /** @hidden */
  52796. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52797. var properties = propertyPath.split(".");
  52798. for (var index = 0; index < properties.length - 1; index++) {
  52799. target = target[properties[index]];
  52800. }
  52801. return target;
  52802. };
  52803. /** @hidden */
  52804. ActionManager.prototype._getProperty = function (propertyPath) {
  52805. var properties = propertyPath.split(".");
  52806. return properties[properties.length - 1];
  52807. };
  52808. /**
  52809. * Serialize this manager to a JSON object
  52810. * @param name defines the property name to store this manager
  52811. * @returns a JSON representation of this manager
  52812. */
  52813. ActionManager.prototype.serialize = function (name) {
  52814. var root = {
  52815. children: new Array(),
  52816. name: name,
  52817. type: 3,
  52818. properties: new Array() // Empty for root but required
  52819. };
  52820. for (var i = 0; i < this.actions.length; i++) {
  52821. var triggerObject = {
  52822. type: 0,
  52823. children: new Array(),
  52824. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52825. properties: new Array()
  52826. };
  52827. var triggerOptions = this.actions[i].triggerOptions;
  52828. if (triggerOptions && typeof triggerOptions !== "number") {
  52829. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52830. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52831. }
  52832. else {
  52833. var parameter = {};
  52834. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52835. if (triggerOptions.parameter.mesh) {
  52836. parameter._meshId = triggerOptions.parameter.mesh.id;
  52837. }
  52838. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52839. }
  52840. }
  52841. // Serialize child action, recursively
  52842. this.actions[i].serialize(triggerObject);
  52843. // Add serialized trigger
  52844. root.children.push(triggerObject);
  52845. }
  52846. return root;
  52847. };
  52848. /**
  52849. * Creates a new ActionManager from a JSON data
  52850. * @param parsedActions defines the JSON data to read from
  52851. * @param object defines the hosting mesh
  52852. * @param scene defines the hosting scene
  52853. */
  52854. ActionManager.Parse = function (parsedActions, object, scene) {
  52855. var actionManager = new ActionManager(scene);
  52856. if (object === null)
  52857. scene.actionManager = actionManager;
  52858. else
  52859. object.actionManager = actionManager;
  52860. // instanciate a new object
  52861. var instanciate = function (name, params) {
  52862. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52863. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52864. newInstance.constructor.apply(newInstance, params);
  52865. return newInstance;
  52866. };
  52867. var parseParameter = function (name, value, target, propertyPath) {
  52868. if (propertyPath === null) {
  52869. // String, boolean or float
  52870. var floatValue = parseFloat(value);
  52871. if (value === "true" || value === "false")
  52872. return value === "true";
  52873. else
  52874. return isNaN(floatValue) ? value : floatValue;
  52875. }
  52876. var effectiveTarget = propertyPath.split(".");
  52877. var values = value.split(",");
  52878. // Get effective Target
  52879. for (var i = 0; i < effectiveTarget.length; i++) {
  52880. target = target[effectiveTarget[i]];
  52881. }
  52882. // Return appropriate value with its type
  52883. if (typeof (target) === "boolean")
  52884. return values[0] === "true";
  52885. if (typeof (target) === "string")
  52886. return values[0];
  52887. // Parameters with multiple values such as Vector3 etc.
  52888. var split = new Array();
  52889. for (var i = 0; i < values.length; i++)
  52890. split.push(parseFloat(values[i]));
  52891. if (target instanceof BABYLON.Vector3)
  52892. return BABYLON.Vector3.FromArray(split);
  52893. if (target instanceof BABYLON.Vector4)
  52894. return BABYLON.Vector4.FromArray(split);
  52895. if (target instanceof BABYLON.Color3)
  52896. return BABYLON.Color3.FromArray(split);
  52897. if (target instanceof BABYLON.Color4)
  52898. return BABYLON.Color4.FromArray(split);
  52899. return parseFloat(values[0]);
  52900. };
  52901. // traverse graph per trigger
  52902. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  52903. if (combineArray === void 0) { combineArray = null; }
  52904. if (parsedAction.detached)
  52905. return;
  52906. var parameters = new Array();
  52907. var target = null;
  52908. var propertyPath = null;
  52909. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  52910. // Parameters
  52911. if (parsedAction.type === 2)
  52912. parameters.push(actionManager);
  52913. else
  52914. parameters.push(trigger);
  52915. if (combine) {
  52916. var actions = new Array();
  52917. for (var j = 0; j < parsedAction.combine.length; j++) {
  52918. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  52919. }
  52920. parameters.push(actions);
  52921. }
  52922. else {
  52923. for (var i = 0; i < parsedAction.properties.length; i++) {
  52924. var value = parsedAction.properties[i].value;
  52925. var name = parsedAction.properties[i].name;
  52926. var targetType = parsedAction.properties[i].targetType;
  52927. if (name === "target")
  52928. if (targetType !== null && targetType === "SceneProperties")
  52929. value = target = scene;
  52930. else
  52931. value = target = scene.getNodeByName(value);
  52932. else if (name === "parent")
  52933. value = scene.getNodeByName(value);
  52934. else if (name === "sound")
  52935. value = scene.getSoundByName(value);
  52936. else if (name !== "propertyPath") {
  52937. if (parsedAction.type === 2 && name === "operator")
  52938. value = BABYLON.ValueCondition[value];
  52939. else
  52940. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  52941. }
  52942. else {
  52943. propertyPath = value;
  52944. }
  52945. parameters.push(value);
  52946. }
  52947. }
  52948. if (combineArray === null) {
  52949. parameters.push(condition);
  52950. }
  52951. else {
  52952. parameters.push(null);
  52953. }
  52954. // If interpolate value action
  52955. if (parsedAction.name === "InterpolateValueAction") {
  52956. var param = parameters[parameters.length - 2];
  52957. parameters[parameters.length - 1] = param;
  52958. parameters[parameters.length - 2] = condition;
  52959. }
  52960. // Action or condition(s) and not CombineAction
  52961. var newAction = instanciate(parsedAction.name, parameters);
  52962. if (newAction instanceof BABYLON.Condition && condition !== null) {
  52963. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  52964. if (action)
  52965. action.then(nothing);
  52966. else
  52967. actionManager.registerAction(nothing);
  52968. action = nothing;
  52969. }
  52970. if (combineArray === null) {
  52971. if (newAction instanceof BABYLON.Condition) {
  52972. condition = newAction;
  52973. newAction = action;
  52974. }
  52975. else {
  52976. condition = null;
  52977. if (action)
  52978. action.then(newAction);
  52979. else
  52980. actionManager.registerAction(newAction);
  52981. }
  52982. }
  52983. else {
  52984. combineArray.push(newAction);
  52985. }
  52986. for (var i = 0; i < parsedAction.children.length; i++)
  52987. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  52988. };
  52989. // triggers
  52990. for (var i = 0; i < parsedActions.children.length; i++) {
  52991. var triggerParams;
  52992. var trigger = parsedActions.children[i];
  52993. if (trigger.properties.length > 0) {
  52994. var param = trigger.properties[0].value;
  52995. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  52996. if (value._meshId) {
  52997. value.mesh = scene.getMeshByID(value._meshId);
  52998. }
  52999. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53000. }
  53001. else
  53002. triggerParams = ActionManager[trigger.name];
  53003. for (var j = 0; j < trigger.children.length; j++) {
  53004. if (!trigger.detached)
  53005. traverse(trigger.children[j], triggerParams, null, null);
  53006. }
  53007. }
  53008. };
  53009. /**
  53010. * Get a trigger name by index
  53011. * @param trigger defines the trigger index
  53012. * @returns a trigger name
  53013. */
  53014. ActionManager.GetTriggerName = function (trigger) {
  53015. switch (trigger) {
  53016. case 0: return "NothingTrigger";
  53017. case 1: return "OnPickTrigger";
  53018. case 2: return "OnLeftPickTrigger";
  53019. case 3: return "OnRightPickTrigger";
  53020. case 4: return "OnCenterPickTrigger";
  53021. case 5: return "OnPickDownTrigger";
  53022. case 6: return "OnPickUpTrigger";
  53023. case 7: return "OnLongPressTrigger";
  53024. case 8: return "OnPointerOverTrigger";
  53025. case 9: return "OnPointerOutTrigger";
  53026. case 10: return "OnEveryFrameTrigger";
  53027. case 11: return "OnIntersectionEnterTrigger";
  53028. case 12: return "OnIntersectionExitTrigger";
  53029. case 13: return "OnKeyDownTrigger";
  53030. case 14: return "OnKeyUpTrigger";
  53031. case 15: return "OnPickOutTrigger";
  53032. default: return "";
  53033. }
  53034. };
  53035. // Statics
  53036. ActionManager._NothingTrigger = 0;
  53037. ActionManager._OnPickTrigger = 1;
  53038. ActionManager._OnLeftPickTrigger = 2;
  53039. ActionManager._OnRightPickTrigger = 3;
  53040. ActionManager._OnCenterPickTrigger = 4;
  53041. ActionManager._OnPickDownTrigger = 5;
  53042. ActionManager._OnDoublePickTrigger = 6;
  53043. ActionManager._OnPickUpTrigger = 7;
  53044. ActionManager._OnLongPressTrigger = 8;
  53045. ActionManager._OnPointerOverTrigger = 9;
  53046. ActionManager._OnPointerOutTrigger = 10;
  53047. ActionManager._OnEveryFrameTrigger = 11;
  53048. ActionManager._OnIntersectionEnterTrigger = 12;
  53049. ActionManager._OnIntersectionExitTrigger = 13;
  53050. ActionManager._OnKeyDownTrigger = 14;
  53051. ActionManager._OnKeyUpTrigger = 15;
  53052. ActionManager._OnPickOutTrigger = 16;
  53053. /** Gets the list of active triggers */
  53054. ActionManager.Triggers = {};
  53055. return ActionManager;
  53056. }());
  53057. BABYLON.ActionManager = ActionManager;
  53058. })(BABYLON || (BABYLON = {}));
  53059. //# sourceMappingURL=babylon.actionManager.js.map
  53060. var BABYLON;
  53061. (function (BABYLON) {
  53062. var InterpolateValueAction = /** @class */ (function (_super) {
  53063. __extends(InterpolateValueAction, _super);
  53064. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53065. if (duration === void 0) { duration = 1000; }
  53066. var _this = _super.call(this, triggerOptions, condition) || this;
  53067. _this.propertyPath = propertyPath;
  53068. _this.value = value;
  53069. _this.duration = duration;
  53070. _this.stopOtherAnimations = stopOtherAnimations;
  53071. _this.onInterpolationDone = onInterpolationDone;
  53072. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53073. _this._target = _this._effectiveTarget = target;
  53074. return _this;
  53075. }
  53076. InterpolateValueAction.prototype._prepare = function () {
  53077. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53078. this._property = this._getProperty(this.propertyPath);
  53079. };
  53080. InterpolateValueAction.prototype.execute = function () {
  53081. var _this = this;
  53082. var scene = this._actionManager.getScene();
  53083. var keys = [
  53084. {
  53085. frame: 0,
  53086. value: this._effectiveTarget[this._property]
  53087. }, {
  53088. frame: 100,
  53089. value: this.value
  53090. }
  53091. ];
  53092. var dataType;
  53093. if (typeof this.value === "number") {
  53094. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53095. }
  53096. else if (this.value instanceof BABYLON.Color3) {
  53097. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53098. }
  53099. else if (this.value instanceof BABYLON.Vector3) {
  53100. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53101. }
  53102. else if (this.value instanceof BABYLON.Matrix) {
  53103. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53104. }
  53105. else if (this.value instanceof BABYLON.Quaternion) {
  53106. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53107. }
  53108. else {
  53109. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53110. return;
  53111. }
  53112. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53113. animation.setKeys(keys);
  53114. if (this.stopOtherAnimations) {
  53115. scene.stopAnimation(this._effectiveTarget);
  53116. }
  53117. var wrapper = function () {
  53118. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53119. if (_this.onInterpolationDone) {
  53120. _this.onInterpolationDone();
  53121. }
  53122. };
  53123. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53124. };
  53125. InterpolateValueAction.prototype.serialize = function (parent) {
  53126. return _super.prototype._serialize.call(this, {
  53127. name: "InterpolateValueAction",
  53128. properties: [
  53129. BABYLON.Action._GetTargetProperty(this._target),
  53130. { name: "propertyPath", value: this.propertyPath },
  53131. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53132. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53133. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53134. ]
  53135. }, parent);
  53136. };
  53137. return InterpolateValueAction;
  53138. }(BABYLON.Action));
  53139. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53140. })(BABYLON || (BABYLON = {}));
  53141. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53142. var BABYLON;
  53143. (function (BABYLON) {
  53144. var SwitchBooleanAction = /** @class */ (function (_super) {
  53145. __extends(SwitchBooleanAction, _super);
  53146. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53147. var _this = _super.call(this, triggerOptions, condition) || this;
  53148. _this.propertyPath = propertyPath;
  53149. _this._target = _this._effectiveTarget = target;
  53150. return _this;
  53151. }
  53152. SwitchBooleanAction.prototype._prepare = function () {
  53153. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53154. this._property = this._getProperty(this.propertyPath);
  53155. };
  53156. SwitchBooleanAction.prototype.execute = function () {
  53157. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53158. };
  53159. SwitchBooleanAction.prototype.serialize = function (parent) {
  53160. return _super.prototype._serialize.call(this, {
  53161. name: "SwitchBooleanAction",
  53162. properties: [
  53163. BABYLON.Action._GetTargetProperty(this._target),
  53164. { name: "propertyPath", value: this.propertyPath }
  53165. ]
  53166. }, parent);
  53167. };
  53168. return SwitchBooleanAction;
  53169. }(BABYLON.Action));
  53170. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53171. var SetStateAction = /** @class */ (function (_super) {
  53172. __extends(SetStateAction, _super);
  53173. function SetStateAction(triggerOptions, target, value, condition) {
  53174. var _this = _super.call(this, triggerOptions, condition) || this;
  53175. _this.value = value;
  53176. _this._target = target;
  53177. return _this;
  53178. }
  53179. SetStateAction.prototype.execute = function () {
  53180. this._target.state = this.value;
  53181. };
  53182. SetStateAction.prototype.serialize = function (parent) {
  53183. return _super.prototype._serialize.call(this, {
  53184. name: "SetStateAction",
  53185. properties: [
  53186. BABYLON.Action._GetTargetProperty(this._target),
  53187. { name: "value", value: this.value }
  53188. ]
  53189. }, parent);
  53190. };
  53191. return SetStateAction;
  53192. }(BABYLON.Action));
  53193. BABYLON.SetStateAction = SetStateAction;
  53194. var SetValueAction = /** @class */ (function (_super) {
  53195. __extends(SetValueAction, _super);
  53196. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53197. var _this = _super.call(this, triggerOptions, condition) || this;
  53198. _this.propertyPath = propertyPath;
  53199. _this.value = value;
  53200. _this._target = _this._effectiveTarget = target;
  53201. return _this;
  53202. }
  53203. SetValueAction.prototype._prepare = function () {
  53204. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53205. this._property = this._getProperty(this.propertyPath);
  53206. };
  53207. SetValueAction.prototype.execute = function () {
  53208. this._effectiveTarget[this._property] = this.value;
  53209. if (this._target.markAsDirty) {
  53210. this._target.markAsDirty(this._property);
  53211. }
  53212. };
  53213. SetValueAction.prototype.serialize = function (parent) {
  53214. return _super.prototype._serialize.call(this, {
  53215. name: "SetValueAction",
  53216. properties: [
  53217. BABYLON.Action._GetTargetProperty(this._target),
  53218. { name: "propertyPath", value: this.propertyPath },
  53219. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53220. ]
  53221. }, parent);
  53222. };
  53223. return SetValueAction;
  53224. }(BABYLON.Action));
  53225. BABYLON.SetValueAction = SetValueAction;
  53226. var IncrementValueAction = /** @class */ (function (_super) {
  53227. __extends(IncrementValueAction, _super);
  53228. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53229. var _this = _super.call(this, triggerOptions, condition) || this;
  53230. _this.propertyPath = propertyPath;
  53231. _this.value = value;
  53232. _this._target = _this._effectiveTarget = target;
  53233. return _this;
  53234. }
  53235. IncrementValueAction.prototype._prepare = function () {
  53236. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53237. this._property = this._getProperty(this.propertyPath);
  53238. if (typeof this._effectiveTarget[this._property] !== "number") {
  53239. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53240. }
  53241. };
  53242. IncrementValueAction.prototype.execute = function () {
  53243. this._effectiveTarget[this._property] += this.value;
  53244. if (this._target.markAsDirty) {
  53245. this._target.markAsDirty(this._property);
  53246. }
  53247. };
  53248. IncrementValueAction.prototype.serialize = function (parent) {
  53249. return _super.prototype._serialize.call(this, {
  53250. name: "IncrementValueAction",
  53251. properties: [
  53252. BABYLON.Action._GetTargetProperty(this._target),
  53253. { name: "propertyPath", value: this.propertyPath },
  53254. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53255. ]
  53256. }, parent);
  53257. };
  53258. return IncrementValueAction;
  53259. }(BABYLON.Action));
  53260. BABYLON.IncrementValueAction = IncrementValueAction;
  53261. var PlayAnimationAction = /** @class */ (function (_super) {
  53262. __extends(PlayAnimationAction, _super);
  53263. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53264. var _this = _super.call(this, triggerOptions, condition) || this;
  53265. _this.from = from;
  53266. _this.to = to;
  53267. _this.loop = loop;
  53268. _this._target = target;
  53269. return _this;
  53270. }
  53271. PlayAnimationAction.prototype._prepare = function () {
  53272. };
  53273. PlayAnimationAction.prototype.execute = function () {
  53274. var scene = this._actionManager.getScene();
  53275. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53276. };
  53277. PlayAnimationAction.prototype.serialize = function (parent) {
  53278. return _super.prototype._serialize.call(this, {
  53279. name: "PlayAnimationAction",
  53280. properties: [
  53281. BABYLON.Action._GetTargetProperty(this._target),
  53282. { name: "from", value: String(this.from) },
  53283. { name: "to", value: String(this.to) },
  53284. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53285. ]
  53286. }, parent);
  53287. };
  53288. return PlayAnimationAction;
  53289. }(BABYLON.Action));
  53290. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53291. var StopAnimationAction = /** @class */ (function (_super) {
  53292. __extends(StopAnimationAction, _super);
  53293. function StopAnimationAction(triggerOptions, target, condition) {
  53294. var _this = _super.call(this, triggerOptions, condition) || this;
  53295. _this._target = target;
  53296. return _this;
  53297. }
  53298. StopAnimationAction.prototype._prepare = function () {
  53299. };
  53300. StopAnimationAction.prototype.execute = function () {
  53301. var scene = this._actionManager.getScene();
  53302. scene.stopAnimation(this._target);
  53303. };
  53304. StopAnimationAction.prototype.serialize = function (parent) {
  53305. return _super.prototype._serialize.call(this, {
  53306. name: "StopAnimationAction",
  53307. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53308. }, parent);
  53309. };
  53310. return StopAnimationAction;
  53311. }(BABYLON.Action));
  53312. BABYLON.StopAnimationAction = StopAnimationAction;
  53313. var DoNothingAction = /** @class */ (function (_super) {
  53314. __extends(DoNothingAction, _super);
  53315. function DoNothingAction(triggerOptions, condition) {
  53316. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53317. return _super.call(this, triggerOptions, condition) || this;
  53318. }
  53319. DoNothingAction.prototype.execute = function () {
  53320. };
  53321. DoNothingAction.prototype.serialize = function (parent) {
  53322. return _super.prototype._serialize.call(this, {
  53323. name: "DoNothingAction",
  53324. properties: []
  53325. }, parent);
  53326. };
  53327. return DoNothingAction;
  53328. }(BABYLON.Action));
  53329. BABYLON.DoNothingAction = DoNothingAction;
  53330. var CombineAction = /** @class */ (function (_super) {
  53331. __extends(CombineAction, _super);
  53332. function CombineAction(triggerOptions, children, condition) {
  53333. var _this = _super.call(this, triggerOptions, condition) || this;
  53334. _this.children = children;
  53335. return _this;
  53336. }
  53337. CombineAction.prototype._prepare = function () {
  53338. for (var index = 0; index < this.children.length; index++) {
  53339. this.children[index]._actionManager = this._actionManager;
  53340. this.children[index]._prepare();
  53341. }
  53342. };
  53343. CombineAction.prototype.execute = function (evt) {
  53344. for (var index = 0; index < this.children.length; index++) {
  53345. this.children[index].execute(evt);
  53346. }
  53347. };
  53348. CombineAction.prototype.serialize = function (parent) {
  53349. var serializationObject = _super.prototype._serialize.call(this, {
  53350. name: "CombineAction",
  53351. properties: [],
  53352. combine: []
  53353. }, parent);
  53354. for (var i = 0; i < this.children.length; i++) {
  53355. serializationObject.combine.push(this.children[i].serialize(null));
  53356. }
  53357. return serializationObject;
  53358. };
  53359. return CombineAction;
  53360. }(BABYLON.Action));
  53361. BABYLON.CombineAction = CombineAction;
  53362. var ExecuteCodeAction = /** @class */ (function (_super) {
  53363. __extends(ExecuteCodeAction, _super);
  53364. function ExecuteCodeAction(triggerOptions, func, condition) {
  53365. var _this = _super.call(this, triggerOptions, condition) || this;
  53366. _this.func = func;
  53367. return _this;
  53368. }
  53369. ExecuteCodeAction.prototype.execute = function (evt) {
  53370. this.func(evt);
  53371. };
  53372. return ExecuteCodeAction;
  53373. }(BABYLON.Action));
  53374. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53375. var SetParentAction = /** @class */ (function (_super) {
  53376. __extends(SetParentAction, _super);
  53377. function SetParentAction(triggerOptions, target, parent, condition) {
  53378. var _this = _super.call(this, triggerOptions, condition) || this;
  53379. _this._target = target;
  53380. _this._parent = parent;
  53381. return _this;
  53382. }
  53383. SetParentAction.prototype._prepare = function () {
  53384. };
  53385. SetParentAction.prototype.execute = function () {
  53386. if (this._target.parent === this._parent) {
  53387. return;
  53388. }
  53389. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53390. invertParentWorldMatrix.invert();
  53391. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53392. this._target.parent = this._parent;
  53393. };
  53394. SetParentAction.prototype.serialize = function (parent) {
  53395. return _super.prototype._serialize.call(this, {
  53396. name: "SetParentAction",
  53397. properties: [
  53398. BABYLON.Action._GetTargetProperty(this._target),
  53399. BABYLON.Action._GetTargetProperty(this._parent),
  53400. ]
  53401. }, parent);
  53402. };
  53403. return SetParentAction;
  53404. }(BABYLON.Action));
  53405. BABYLON.SetParentAction = SetParentAction;
  53406. var PlaySoundAction = /** @class */ (function (_super) {
  53407. __extends(PlaySoundAction, _super);
  53408. function PlaySoundAction(triggerOptions, sound, condition) {
  53409. var _this = _super.call(this, triggerOptions, condition) || this;
  53410. _this._sound = sound;
  53411. return _this;
  53412. }
  53413. PlaySoundAction.prototype._prepare = function () {
  53414. };
  53415. PlaySoundAction.prototype.execute = function () {
  53416. if (this._sound !== undefined)
  53417. this._sound.play();
  53418. };
  53419. PlaySoundAction.prototype.serialize = function (parent) {
  53420. return _super.prototype._serialize.call(this, {
  53421. name: "PlaySoundAction",
  53422. properties: [{ name: "sound", value: this._sound.name }]
  53423. }, parent);
  53424. };
  53425. return PlaySoundAction;
  53426. }(BABYLON.Action));
  53427. BABYLON.PlaySoundAction = PlaySoundAction;
  53428. var StopSoundAction = /** @class */ (function (_super) {
  53429. __extends(StopSoundAction, _super);
  53430. function StopSoundAction(triggerOptions, sound, condition) {
  53431. var _this = _super.call(this, triggerOptions, condition) || this;
  53432. _this._sound = sound;
  53433. return _this;
  53434. }
  53435. StopSoundAction.prototype._prepare = function () {
  53436. };
  53437. StopSoundAction.prototype.execute = function () {
  53438. if (this._sound !== undefined)
  53439. this._sound.stop();
  53440. };
  53441. StopSoundAction.prototype.serialize = function (parent) {
  53442. return _super.prototype._serialize.call(this, {
  53443. name: "StopSoundAction",
  53444. properties: [{ name: "sound", value: this._sound.name }]
  53445. }, parent);
  53446. };
  53447. return StopSoundAction;
  53448. }(BABYLON.Action));
  53449. BABYLON.StopSoundAction = StopSoundAction;
  53450. })(BABYLON || (BABYLON = {}));
  53451. //# sourceMappingURL=babylon.directActions.js.map
  53452. var BABYLON;
  53453. (function (BABYLON) {
  53454. var SpriteManager = /** @class */ (function () {
  53455. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53456. if (epsilon === void 0) { epsilon = 0.01; }
  53457. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53458. this.name = name;
  53459. this.sprites = new Array();
  53460. this.renderingGroupId = 0;
  53461. this.layerMask = 0x0FFFFFFF;
  53462. this.fogEnabled = true;
  53463. this.isPickable = false;
  53464. /**
  53465. * An event triggered when the manager is disposed.
  53466. */
  53467. this.onDisposeObservable = new BABYLON.Observable();
  53468. this._vertexBuffers = {};
  53469. this._capacity = capacity;
  53470. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53471. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53472. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53473. if (cellSize.width && cellSize.height) {
  53474. this.cellWidth = cellSize.width;
  53475. this.cellHeight = cellSize.height;
  53476. }
  53477. else if (cellSize !== undefined) {
  53478. this.cellWidth = cellSize;
  53479. this.cellHeight = cellSize;
  53480. }
  53481. else {
  53482. return;
  53483. }
  53484. this._epsilon = epsilon;
  53485. this._scene = scene;
  53486. this._scene.spriteManagers.push(this);
  53487. var indices = [];
  53488. var index = 0;
  53489. for (var count = 0; count < capacity; count++) {
  53490. indices.push(index);
  53491. indices.push(index + 1);
  53492. indices.push(index + 2);
  53493. indices.push(index);
  53494. indices.push(index + 2);
  53495. indices.push(index + 3);
  53496. index += 4;
  53497. }
  53498. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53499. // VBO
  53500. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53501. this._vertexData = new Float32Array(capacity * 16 * 4);
  53502. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53503. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53504. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53505. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53506. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53507. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53508. this._vertexBuffers["options"] = options;
  53509. this._vertexBuffers["cellInfo"] = cellInfo;
  53510. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53511. // Effects
  53512. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53513. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53514. }
  53515. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53516. set: function (callback) {
  53517. if (this._onDisposeObserver) {
  53518. this.onDisposeObservable.remove(this._onDisposeObserver);
  53519. }
  53520. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53521. },
  53522. enumerable: true,
  53523. configurable: true
  53524. });
  53525. Object.defineProperty(SpriteManager.prototype, "texture", {
  53526. get: function () {
  53527. return this._spriteTexture;
  53528. },
  53529. set: function (value) {
  53530. this._spriteTexture = value;
  53531. },
  53532. enumerable: true,
  53533. configurable: true
  53534. });
  53535. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53536. var arrayOffset = index * 16;
  53537. if (offsetX === 0)
  53538. offsetX = this._epsilon;
  53539. else if (offsetX === 1)
  53540. offsetX = 1 - this._epsilon;
  53541. if (offsetY === 0)
  53542. offsetY = this._epsilon;
  53543. else if (offsetY === 1)
  53544. offsetY = 1 - this._epsilon;
  53545. this._vertexData[arrayOffset] = sprite.position.x;
  53546. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53547. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53548. this._vertexData[arrayOffset + 3] = sprite.angle;
  53549. this._vertexData[arrayOffset + 4] = sprite.width;
  53550. this._vertexData[arrayOffset + 5] = sprite.height;
  53551. this._vertexData[arrayOffset + 6] = offsetX;
  53552. this._vertexData[arrayOffset + 7] = offsetY;
  53553. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53554. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53555. var offset = (sprite.cellIndex / rowSize) >> 0;
  53556. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53557. this._vertexData[arrayOffset + 11] = offset;
  53558. // Color
  53559. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53560. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53561. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53562. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53563. };
  53564. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53565. var count = Math.min(this._capacity, this.sprites.length);
  53566. var min = BABYLON.Vector3.Zero();
  53567. var max = BABYLON.Vector3.Zero();
  53568. var distance = Number.MAX_VALUE;
  53569. var currentSprite = null;
  53570. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53571. var cameraView = camera.getViewMatrix();
  53572. for (var index = 0; index < count; index++) {
  53573. var sprite = this.sprites[index];
  53574. if (!sprite) {
  53575. continue;
  53576. }
  53577. if (predicate) {
  53578. if (!predicate(sprite)) {
  53579. continue;
  53580. }
  53581. }
  53582. else if (!sprite.isPickable) {
  53583. continue;
  53584. }
  53585. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53586. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53587. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53588. if (ray.intersectsBoxMinMax(min, max)) {
  53589. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53590. if (distance > currentDistance) {
  53591. distance = currentDistance;
  53592. currentSprite = sprite;
  53593. if (fastCheck) {
  53594. break;
  53595. }
  53596. }
  53597. }
  53598. }
  53599. if (currentSprite) {
  53600. var result = new BABYLON.PickingInfo();
  53601. result.hit = true;
  53602. result.pickedSprite = currentSprite;
  53603. result.distance = distance;
  53604. return result;
  53605. }
  53606. return null;
  53607. };
  53608. SpriteManager.prototype.render = function () {
  53609. // Check
  53610. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53611. return;
  53612. var engine = this._scene.getEngine();
  53613. var baseSize = this._spriteTexture.getBaseSize();
  53614. // Sprites
  53615. var deltaTime = engine.getDeltaTime();
  53616. var max = Math.min(this._capacity, this.sprites.length);
  53617. var rowSize = baseSize.width / this.cellWidth;
  53618. var offset = 0;
  53619. for (var index = 0; index < max; index++) {
  53620. var sprite = this.sprites[index];
  53621. if (!sprite || !sprite.isVisible) {
  53622. continue;
  53623. }
  53624. sprite._animate(deltaTime);
  53625. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53626. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53627. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53628. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53629. }
  53630. this._buffer.update(this._vertexData);
  53631. // Render
  53632. var effect = this._effectBase;
  53633. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53634. effect = this._effectFog;
  53635. }
  53636. engine.enableEffect(effect);
  53637. var viewMatrix = this._scene.getViewMatrix();
  53638. effect.setTexture("diffuseSampler", this._spriteTexture);
  53639. effect.setMatrix("view", viewMatrix);
  53640. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53641. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53642. // Fog
  53643. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53644. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53645. effect.setColor3("vFogColor", this._scene.fogColor);
  53646. }
  53647. // VBOs
  53648. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53649. // Draw order
  53650. engine.setDepthFunctionToLessOrEqual();
  53651. effect.setBool("alphaTest", true);
  53652. engine.setColorWrite(false);
  53653. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53654. engine.setColorWrite(true);
  53655. effect.setBool("alphaTest", false);
  53656. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53657. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53658. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53659. };
  53660. SpriteManager.prototype.dispose = function () {
  53661. if (this._buffer) {
  53662. this._buffer.dispose();
  53663. this._buffer = null;
  53664. }
  53665. if (this._indexBuffer) {
  53666. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53667. this._indexBuffer = null;
  53668. }
  53669. if (this._spriteTexture) {
  53670. this._spriteTexture.dispose();
  53671. this._spriteTexture = null;
  53672. }
  53673. // Remove from scene
  53674. var index = this._scene.spriteManagers.indexOf(this);
  53675. this._scene.spriteManagers.splice(index, 1);
  53676. // Callback
  53677. this.onDisposeObservable.notifyObservers(this);
  53678. this.onDisposeObservable.clear();
  53679. };
  53680. return SpriteManager;
  53681. }());
  53682. BABYLON.SpriteManager = SpriteManager;
  53683. })(BABYLON || (BABYLON = {}));
  53684. //# sourceMappingURL=babylon.spriteManager.js.map
  53685. var BABYLON;
  53686. (function (BABYLON) {
  53687. var Sprite = /** @class */ (function () {
  53688. function Sprite(name, manager) {
  53689. this.name = name;
  53690. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53691. this.width = 1.0;
  53692. this.height = 1.0;
  53693. this.angle = 0;
  53694. this.cellIndex = 0;
  53695. this.invertU = 0;
  53696. this.invertV = 0;
  53697. this.animations = new Array();
  53698. this.isPickable = false;
  53699. this._animationStarted = false;
  53700. this._loopAnimation = false;
  53701. this._fromIndex = 0;
  53702. this._toIndex = 0;
  53703. this._delay = 0;
  53704. this._direction = 1;
  53705. this._time = 0;
  53706. /**
  53707. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53708. */
  53709. this.isVisible = true;
  53710. this._manager = manager;
  53711. this._manager.sprites.push(this);
  53712. this.position = BABYLON.Vector3.Zero();
  53713. }
  53714. Object.defineProperty(Sprite.prototype, "size", {
  53715. get: function () {
  53716. return this.width;
  53717. },
  53718. set: function (value) {
  53719. this.width = value;
  53720. this.height = value;
  53721. },
  53722. enumerable: true,
  53723. configurable: true
  53724. });
  53725. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53726. this._fromIndex = from;
  53727. this._toIndex = to;
  53728. this._loopAnimation = loop;
  53729. this._delay = delay;
  53730. this._animationStarted = true;
  53731. this._direction = from < to ? 1 : -1;
  53732. this.cellIndex = from;
  53733. this._time = 0;
  53734. this._onAnimationEnd = onAnimationEnd;
  53735. };
  53736. Sprite.prototype.stopAnimation = function () {
  53737. this._animationStarted = false;
  53738. };
  53739. Sprite.prototype._animate = function (deltaTime) {
  53740. if (!this._animationStarted)
  53741. return;
  53742. this._time += deltaTime;
  53743. if (this._time > this._delay) {
  53744. this._time = this._time % this._delay;
  53745. this.cellIndex += this._direction;
  53746. if (this.cellIndex > this._toIndex) {
  53747. if (this._loopAnimation) {
  53748. this.cellIndex = this._fromIndex;
  53749. }
  53750. else {
  53751. this.cellIndex = this._toIndex;
  53752. this._animationStarted = false;
  53753. if (this._onAnimationEnd) {
  53754. this._onAnimationEnd();
  53755. }
  53756. if (this.disposeWhenFinishedAnimating) {
  53757. this.dispose();
  53758. }
  53759. }
  53760. }
  53761. }
  53762. };
  53763. Sprite.prototype.dispose = function () {
  53764. for (var i = 0; i < this._manager.sprites.length; i++) {
  53765. if (this._manager.sprites[i] == this) {
  53766. this._manager.sprites.splice(i, 1);
  53767. }
  53768. }
  53769. };
  53770. return Sprite;
  53771. }());
  53772. BABYLON.Sprite = Sprite;
  53773. })(BABYLON || (BABYLON = {}));
  53774. //# sourceMappingURL=babylon.sprite.js.map
  53775. var BABYLON;
  53776. (function (BABYLON) {
  53777. var IntersectionInfo = /** @class */ (function () {
  53778. function IntersectionInfo(bu, bv, distance) {
  53779. this.bu = bu;
  53780. this.bv = bv;
  53781. this.distance = distance;
  53782. this.faceId = 0;
  53783. this.subMeshId = 0;
  53784. }
  53785. return IntersectionInfo;
  53786. }());
  53787. BABYLON.IntersectionInfo = IntersectionInfo;
  53788. /**
  53789. * Information about the result of picking within a scene
  53790. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53791. */
  53792. var PickingInfo = /** @class */ (function () {
  53793. function PickingInfo() {
  53794. /**
  53795. * If the pick collided with an object
  53796. */
  53797. this.hit = false;
  53798. /**
  53799. * Distance away where the pick collided
  53800. */
  53801. this.distance = 0;
  53802. /**
  53803. * The location of pick collision
  53804. */
  53805. this.pickedPoint = null;
  53806. /**
  53807. * The mesh corrisponding the the pick collision
  53808. */
  53809. this.pickedMesh = null;
  53810. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53811. this.bu = 0;
  53812. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53813. this.bv = 0;
  53814. /** The id of the face on the mesh that was picked */
  53815. this.faceId = -1;
  53816. /** Id of the the submesh that was picked */
  53817. this.subMeshId = 0;
  53818. /** If a sprite was picked, this will be the sprite the pick collided with */
  53819. this.pickedSprite = null;
  53820. /**
  53821. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53822. */
  53823. this.originMesh = null;
  53824. /**
  53825. * The ray that was used to perform the picking.
  53826. */
  53827. this.ray = null;
  53828. }
  53829. /**
  53830. * Gets the normal corrispodning to the face the pick collided with
  53831. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53832. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53833. * @returns The normal corrispodning to the face the pick collided with
  53834. */
  53835. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53836. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53837. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53838. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53839. return null;
  53840. }
  53841. var indices = this.pickedMesh.getIndices();
  53842. if (!indices) {
  53843. return null;
  53844. }
  53845. var result;
  53846. if (useVerticesNormals) {
  53847. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53848. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53849. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53850. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53851. normal0 = normal0.scale(this.bu);
  53852. normal1 = normal1.scale(this.bv);
  53853. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53854. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53855. }
  53856. else {
  53857. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53858. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53859. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53860. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53861. var p1p2 = vertex1.subtract(vertex2);
  53862. var p3p2 = vertex3.subtract(vertex2);
  53863. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53864. }
  53865. if (useWorldCoordinates) {
  53866. var wm = this.pickedMesh.getWorldMatrix();
  53867. if (this.pickedMesh.nonUniformScaling) {
  53868. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53869. wm = BABYLON.Tmp.Matrix[0];
  53870. wm.setTranslationFromFloats(0, 0, 0);
  53871. wm.invert();
  53872. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53873. wm = BABYLON.Tmp.Matrix[1];
  53874. }
  53875. result = BABYLON.Vector3.TransformNormal(result, wm);
  53876. }
  53877. result.normalize();
  53878. return result;
  53879. };
  53880. /**
  53881. * Gets the texture coordinates of where the pick occured
  53882. * @returns the vector containing the coordnates of the texture
  53883. */
  53884. PickingInfo.prototype.getTextureCoordinates = function () {
  53885. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53886. return null;
  53887. }
  53888. var indices = this.pickedMesh.getIndices();
  53889. if (!indices) {
  53890. return null;
  53891. }
  53892. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  53893. if (!uvs) {
  53894. return null;
  53895. }
  53896. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  53897. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  53898. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  53899. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  53900. uv1 = uv1.scale(this.bu);
  53901. uv2 = uv2.scale(this.bv);
  53902. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  53903. };
  53904. return PickingInfo;
  53905. }());
  53906. BABYLON.PickingInfo = PickingInfo;
  53907. })(BABYLON || (BABYLON = {}));
  53908. //# sourceMappingURL=babylon.pickingInfo.js.map
  53909. var BABYLON;
  53910. (function (BABYLON) {
  53911. var Ray = /** @class */ (function () {
  53912. function Ray(origin, direction, length) {
  53913. if (length === void 0) { length = Number.MAX_VALUE; }
  53914. this.origin = origin;
  53915. this.direction = direction;
  53916. this.length = length;
  53917. }
  53918. // Methods
  53919. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  53920. var d = 0.0;
  53921. var maxValue = Number.MAX_VALUE;
  53922. var inv;
  53923. var min;
  53924. var max;
  53925. var temp;
  53926. if (Math.abs(this.direction.x) < 0.0000001) {
  53927. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  53928. return false;
  53929. }
  53930. }
  53931. else {
  53932. inv = 1.0 / this.direction.x;
  53933. min = (minimum.x - this.origin.x) * inv;
  53934. max = (maximum.x - this.origin.x) * inv;
  53935. if (max === -Infinity) {
  53936. max = Infinity;
  53937. }
  53938. if (min > max) {
  53939. temp = min;
  53940. min = max;
  53941. max = temp;
  53942. }
  53943. d = Math.max(min, d);
  53944. maxValue = Math.min(max, maxValue);
  53945. if (d > maxValue) {
  53946. return false;
  53947. }
  53948. }
  53949. if (Math.abs(this.direction.y) < 0.0000001) {
  53950. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  53951. return false;
  53952. }
  53953. }
  53954. else {
  53955. inv = 1.0 / this.direction.y;
  53956. min = (minimum.y - this.origin.y) * inv;
  53957. max = (maximum.y - this.origin.y) * inv;
  53958. if (max === -Infinity) {
  53959. max = Infinity;
  53960. }
  53961. if (min > max) {
  53962. temp = min;
  53963. min = max;
  53964. max = temp;
  53965. }
  53966. d = Math.max(min, d);
  53967. maxValue = Math.min(max, maxValue);
  53968. if (d > maxValue) {
  53969. return false;
  53970. }
  53971. }
  53972. if (Math.abs(this.direction.z) < 0.0000001) {
  53973. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  53974. return false;
  53975. }
  53976. }
  53977. else {
  53978. inv = 1.0 / this.direction.z;
  53979. min = (minimum.z - this.origin.z) * inv;
  53980. max = (maximum.z - this.origin.z) * inv;
  53981. if (max === -Infinity) {
  53982. max = Infinity;
  53983. }
  53984. if (min > max) {
  53985. temp = min;
  53986. min = max;
  53987. max = temp;
  53988. }
  53989. d = Math.max(min, d);
  53990. maxValue = Math.min(max, maxValue);
  53991. if (d > maxValue) {
  53992. return false;
  53993. }
  53994. }
  53995. return true;
  53996. };
  53997. Ray.prototype.intersectsBox = function (box) {
  53998. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  53999. };
  54000. Ray.prototype.intersectsSphere = function (sphere) {
  54001. var x = sphere.center.x - this.origin.x;
  54002. var y = sphere.center.y - this.origin.y;
  54003. var z = sphere.center.z - this.origin.z;
  54004. var pyth = (x * x) + (y * y) + (z * z);
  54005. var rr = sphere.radius * sphere.radius;
  54006. if (pyth <= rr) {
  54007. return true;
  54008. }
  54009. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54010. if (dot < 0.0) {
  54011. return false;
  54012. }
  54013. var temp = pyth - (dot * dot);
  54014. return temp <= rr;
  54015. };
  54016. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54017. if (!this._edge1) {
  54018. this._edge1 = BABYLON.Vector3.Zero();
  54019. this._edge2 = BABYLON.Vector3.Zero();
  54020. this._pvec = BABYLON.Vector3.Zero();
  54021. this._tvec = BABYLON.Vector3.Zero();
  54022. this._qvec = BABYLON.Vector3.Zero();
  54023. }
  54024. vertex1.subtractToRef(vertex0, this._edge1);
  54025. vertex2.subtractToRef(vertex0, this._edge2);
  54026. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54027. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54028. if (det === 0) {
  54029. return null;
  54030. }
  54031. var invdet = 1 / det;
  54032. this.origin.subtractToRef(vertex0, this._tvec);
  54033. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54034. if (bu < 0 || bu > 1.0) {
  54035. return null;
  54036. }
  54037. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54038. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54039. if (bv < 0 || bu + bv > 1.0) {
  54040. return null;
  54041. }
  54042. //check if the distance is longer than the predefined length.
  54043. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54044. if (distance > this.length) {
  54045. return null;
  54046. }
  54047. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54048. };
  54049. Ray.prototype.intersectsPlane = function (plane) {
  54050. var distance;
  54051. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54052. if (Math.abs(result1) < 9.99999997475243E-07) {
  54053. return null;
  54054. }
  54055. else {
  54056. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54057. distance = (-plane.d - result2) / result1;
  54058. if (distance < 0.0) {
  54059. if (distance < -9.99999997475243E-07) {
  54060. return null;
  54061. }
  54062. else {
  54063. return 0;
  54064. }
  54065. }
  54066. return distance;
  54067. }
  54068. };
  54069. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54070. var tm = BABYLON.Tmp.Matrix[0];
  54071. mesh.getWorldMatrix().invertToRef(tm);
  54072. if (this._tmpRay) {
  54073. Ray.TransformToRef(this, tm, this._tmpRay);
  54074. }
  54075. else {
  54076. this._tmpRay = Ray.Transform(this, tm);
  54077. }
  54078. return mesh.intersects(this._tmpRay, fastCheck);
  54079. };
  54080. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54081. if (results) {
  54082. results.length = 0;
  54083. }
  54084. else {
  54085. results = [];
  54086. }
  54087. for (var i = 0; i < meshes.length; i++) {
  54088. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54089. if (pickInfo.hit) {
  54090. results.push(pickInfo);
  54091. }
  54092. }
  54093. results.sort(this._comparePickingInfo);
  54094. return results;
  54095. };
  54096. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54097. if (pickingInfoA.distance < pickingInfoB.distance) {
  54098. return -1;
  54099. }
  54100. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54101. return 1;
  54102. }
  54103. else {
  54104. return 0;
  54105. }
  54106. };
  54107. /**
  54108. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54109. * @param sega the first point of the segment to test the intersection against
  54110. * @param segb the second point of the segment to test the intersection against
  54111. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54112. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54113. */
  54114. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54115. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54116. var u = segb.subtract(sega);
  54117. var v = rsegb.subtract(this.origin);
  54118. var w = sega.subtract(this.origin);
  54119. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54120. var b = BABYLON.Vector3.Dot(u, v);
  54121. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54122. var d = BABYLON.Vector3.Dot(u, w);
  54123. var e = BABYLON.Vector3.Dot(v, w);
  54124. var D = a * c - b * b; // always >= 0
  54125. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54126. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54127. // compute the line parameters of the two closest points
  54128. if (D < Ray.smallnum) { // the lines are almost parallel
  54129. sN = 0.0; // force using point P0 on segment S1
  54130. sD = 1.0; // to prevent possible division by 0.0 later
  54131. tN = e;
  54132. tD = c;
  54133. }
  54134. else { // get the closest points on the infinite lines
  54135. sN = (b * e - c * d);
  54136. tN = (a * e - b * d);
  54137. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54138. sN = 0.0;
  54139. tN = e;
  54140. tD = c;
  54141. }
  54142. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54143. sN = sD;
  54144. tN = e + b;
  54145. tD = c;
  54146. }
  54147. }
  54148. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54149. tN = 0.0;
  54150. // recompute sc for this edge
  54151. if (-d < 0.0) {
  54152. sN = 0.0;
  54153. }
  54154. else if (-d > a)
  54155. sN = sD;
  54156. else {
  54157. sN = -d;
  54158. sD = a;
  54159. }
  54160. }
  54161. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54162. tN = tD;
  54163. // recompute sc for this edge
  54164. if ((-d + b) < 0.0) {
  54165. sN = 0;
  54166. }
  54167. else if ((-d + b) > a) {
  54168. sN = sD;
  54169. }
  54170. else {
  54171. sN = (-d + b);
  54172. sD = a;
  54173. }
  54174. }
  54175. // finally do the division to get sc and tc
  54176. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54177. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54178. // get the difference of the two closest points
  54179. var qtc = v.multiplyByFloats(tc, tc, tc);
  54180. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54181. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54182. if (isIntersected) {
  54183. return qtc.length();
  54184. }
  54185. return -1;
  54186. };
  54187. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54188. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54189. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54190. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54191. this.direction.normalize();
  54192. return this;
  54193. };
  54194. // Statics
  54195. Ray.Zero = function () {
  54196. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54197. };
  54198. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54199. var result = Ray.Zero();
  54200. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54201. };
  54202. /**
  54203. * 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
  54204. * transformed to the given world matrix.
  54205. * @param origin The origin point
  54206. * @param end The end point
  54207. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54208. */
  54209. Ray.CreateNewFromTo = function (origin, end, world) {
  54210. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54211. var direction = end.subtract(origin);
  54212. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54213. direction.normalize();
  54214. return Ray.Transform(new Ray(origin, direction, length), world);
  54215. };
  54216. Ray.Transform = function (ray, matrix) {
  54217. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54218. Ray.TransformToRef(ray, matrix, result);
  54219. return result;
  54220. };
  54221. Ray.TransformToRef = function (ray, matrix, result) {
  54222. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54223. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54224. result.length = ray.length;
  54225. var dir = result.direction;
  54226. var len = dir.length();
  54227. if (!(len === 0 || len === 1)) {
  54228. var num = 1.0 / len;
  54229. dir.x *= num;
  54230. dir.y *= num;
  54231. dir.z *= num;
  54232. result.length *= len;
  54233. }
  54234. };
  54235. Ray.smallnum = 0.00000001;
  54236. Ray.rayl = 10e8;
  54237. return Ray;
  54238. }());
  54239. BABYLON.Ray = Ray;
  54240. })(BABYLON || (BABYLON = {}));
  54241. //# sourceMappingURL=babylon.ray.js.map
  54242. var BABYLON;
  54243. (function (BABYLON) {
  54244. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54245. if (boxMin.x > sphereCenter.x + sphereRadius)
  54246. return false;
  54247. if (sphereCenter.x - sphereRadius > boxMax.x)
  54248. return false;
  54249. if (boxMin.y > sphereCenter.y + sphereRadius)
  54250. return false;
  54251. if (sphereCenter.y - sphereRadius > boxMax.y)
  54252. return false;
  54253. if (boxMin.z > sphereCenter.z + sphereRadius)
  54254. return false;
  54255. if (sphereCenter.z - sphereRadius > boxMax.z)
  54256. return false;
  54257. return true;
  54258. };
  54259. var getLowestRoot = (function () {
  54260. var result = { root: 0, found: false };
  54261. return function (a, b, c, maxR) {
  54262. result.root = 0;
  54263. result.found = false;
  54264. var determinant = b * b - 4.0 * a * c;
  54265. if (determinant < 0)
  54266. return result;
  54267. var sqrtD = Math.sqrt(determinant);
  54268. var r1 = (-b - sqrtD) / (2.0 * a);
  54269. var r2 = (-b + sqrtD) / (2.0 * a);
  54270. if (r1 > r2) {
  54271. var temp = r2;
  54272. r2 = r1;
  54273. r1 = temp;
  54274. }
  54275. if (r1 > 0 && r1 < maxR) {
  54276. result.root = r1;
  54277. result.found = true;
  54278. return result;
  54279. }
  54280. if (r2 > 0 && r2 < maxR) {
  54281. result.root = r2;
  54282. result.found = true;
  54283. return result;
  54284. }
  54285. return result;
  54286. };
  54287. })();
  54288. var Collider = /** @class */ (function () {
  54289. function Collider() {
  54290. this._collisionPoint = BABYLON.Vector3.Zero();
  54291. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54292. this._tempVector = BABYLON.Vector3.Zero();
  54293. this._tempVector2 = BABYLON.Vector3.Zero();
  54294. this._tempVector3 = BABYLON.Vector3.Zero();
  54295. this._tempVector4 = BABYLON.Vector3.Zero();
  54296. this._edge = BABYLON.Vector3.Zero();
  54297. this._baseToVertex = BABYLON.Vector3.Zero();
  54298. this._destinationPoint = BABYLON.Vector3.Zero();
  54299. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54300. this._displacementVector = BABYLON.Vector3.Zero();
  54301. this._radius = BABYLON.Vector3.One();
  54302. this._retry = 0;
  54303. this._basePointWorld = BABYLON.Vector3.Zero();
  54304. this._velocityWorld = BABYLON.Vector3.Zero();
  54305. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54306. this._collisionMask = -1;
  54307. }
  54308. Object.defineProperty(Collider.prototype, "collisionMask", {
  54309. get: function () {
  54310. return this._collisionMask;
  54311. },
  54312. set: function (mask) {
  54313. this._collisionMask = !isNaN(mask) ? mask : -1;
  54314. },
  54315. enumerable: true,
  54316. configurable: true
  54317. });
  54318. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54319. /**
  54320. * Gets the plane normal used to compute the sliding response (in local space)
  54321. */
  54322. get: function () {
  54323. return this._slidePlaneNormal;
  54324. },
  54325. enumerable: true,
  54326. configurable: true
  54327. });
  54328. // Methods
  54329. Collider.prototype._initialize = function (source, dir, e) {
  54330. this._velocity = dir;
  54331. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54332. this._basePoint = source;
  54333. source.multiplyToRef(this._radius, this._basePointWorld);
  54334. dir.multiplyToRef(this._radius, this._velocityWorld);
  54335. this._velocityWorldLength = this._velocityWorld.length();
  54336. this._epsilon = e;
  54337. this.collisionFound = false;
  54338. };
  54339. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54340. pa.subtractToRef(point, this._tempVector);
  54341. pb.subtractToRef(point, this._tempVector2);
  54342. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54343. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54344. if (d < 0)
  54345. return false;
  54346. pc.subtractToRef(point, this._tempVector3);
  54347. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54348. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54349. if (d < 0)
  54350. return false;
  54351. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54352. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54353. return d >= 0;
  54354. };
  54355. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54356. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54357. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54358. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54359. return false;
  54360. }
  54361. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54362. return false;
  54363. return true;
  54364. };
  54365. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54366. var t0;
  54367. var embeddedInPlane = false;
  54368. //defensive programming, actually not needed.
  54369. if (!trianglePlaneArray) {
  54370. trianglePlaneArray = [];
  54371. }
  54372. if (!trianglePlaneArray[faceIndex]) {
  54373. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54374. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54375. }
  54376. var trianglePlane = trianglePlaneArray[faceIndex];
  54377. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54378. return;
  54379. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54380. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54381. if (normalDotVelocity == 0) {
  54382. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54383. return;
  54384. embeddedInPlane = true;
  54385. t0 = 0;
  54386. }
  54387. else {
  54388. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54389. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54390. if (t0 > t1) {
  54391. var temp = t1;
  54392. t1 = t0;
  54393. t0 = temp;
  54394. }
  54395. if (t0 > 1.0 || t1 < 0.0)
  54396. return;
  54397. if (t0 < 0)
  54398. t0 = 0;
  54399. if (t0 > 1.0)
  54400. t0 = 1.0;
  54401. }
  54402. this._collisionPoint.copyFromFloats(0, 0, 0);
  54403. var found = false;
  54404. var t = 1.0;
  54405. if (!embeddedInPlane) {
  54406. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54407. this._velocity.scaleToRef(t0, this._tempVector);
  54408. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54409. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54410. found = true;
  54411. t = t0;
  54412. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54413. }
  54414. }
  54415. if (!found) {
  54416. var velocitySquaredLength = this._velocity.lengthSquared();
  54417. var a = velocitySquaredLength;
  54418. this._basePoint.subtractToRef(p1, this._tempVector);
  54419. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54420. var c = this._tempVector.lengthSquared() - 1.0;
  54421. var lowestRoot = getLowestRoot(a, b, c, t);
  54422. if (lowestRoot.found) {
  54423. t = lowestRoot.root;
  54424. found = true;
  54425. this._collisionPoint.copyFrom(p1);
  54426. }
  54427. this._basePoint.subtractToRef(p2, this._tempVector);
  54428. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54429. c = this._tempVector.lengthSquared() - 1.0;
  54430. lowestRoot = getLowestRoot(a, b, c, t);
  54431. if (lowestRoot.found) {
  54432. t = lowestRoot.root;
  54433. found = true;
  54434. this._collisionPoint.copyFrom(p2);
  54435. }
  54436. this._basePoint.subtractToRef(p3, this._tempVector);
  54437. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54438. c = this._tempVector.lengthSquared() - 1.0;
  54439. lowestRoot = getLowestRoot(a, b, c, t);
  54440. if (lowestRoot.found) {
  54441. t = lowestRoot.root;
  54442. found = true;
  54443. this._collisionPoint.copyFrom(p3);
  54444. }
  54445. p2.subtractToRef(p1, this._edge);
  54446. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54447. var edgeSquaredLength = this._edge.lengthSquared();
  54448. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54449. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54450. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54451. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54452. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54453. lowestRoot = getLowestRoot(a, b, c, t);
  54454. if (lowestRoot.found) {
  54455. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54456. if (f >= 0.0 && f <= 1.0) {
  54457. t = lowestRoot.root;
  54458. found = true;
  54459. this._edge.scaleInPlace(f);
  54460. p1.addToRef(this._edge, this._collisionPoint);
  54461. }
  54462. }
  54463. p3.subtractToRef(p2, this._edge);
  54464. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54465. edgeSquaredLength = this._edge.lengthSquared();
  54466. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54467. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54468. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54469. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54470. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54471. lowestRoot = getLowestRoot(a, b, c, t);
  54472. if (lowestRoot.found) {
  54473. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54474. if (f >= 0.0 && f <= 1.0) {
  54475. t = lowestRoot.root;
  54476. found = true;
  54477. this._edge.scaleInPlace(f);
  54478. p2.addToRef(this._edge, this._collisionPoint);
  54479. }
  54480. }
  54481. p1.subtractToRef(p3, this._edge);
  54482. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54483. edgeSquaredLength = this._edge.lengthSquared();
  54484. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54485. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54486. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54487. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54488. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54489. lowestRoot = getLowestRoot(a, b, c, t);
  54490. if (lowestRoot.found) {
  54491. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54492. if (f >= 0.0 && f <= 1.0) {
  54493. t = lowestRoot.root;
  54494. found = true;
  54495. this._edge.scaleInPlace(f);
  54496. p3.addToRef(this._edge, this._collisionPoint);
  54497. }
  54498. }
  54499. }
  54500. if (found) {
  54501. var distToCollision = t * this._velocity.length();
  54502. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54503. if (!this.intersectionPoint) {
  54504. this.intersectionPoint = this._collisionPoint.clone();
  54505. }
  54506. else {
  54507. this.intersectionPoint.copyFrom(this._collisionPoint);
  54508. }
  54509. this._nearestDistance = distToCollision;
  54510. this.collisionFound = true;
  54511. }
  54512. }
  54513. };
  54514. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54515. for (var i = indexStart; i < indexEnd; i += 3) {
  54516. var p1 = pts[indices[i] - decal];
  54517. var p2 = pts[indices[i + 1] - decal];
  54518. var p3 = pts[indices[i + 2] - decal];
  54519. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54520. }
  54521. };
  54522. Collider.prototype._getResponse = function (pos, vel) {
  54523. pos.addToRef(vel, this._destinationPoint);
  54524. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54525. this._basePoint.addToRef(vel, pos);
  54526. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54527. this._slidePlaneNormal.normalize();
  54528. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54529. pos.addInPlace(this._displacementVector);
  54530. this.intersectionPoint.addInPlace(this._displacementVector);
  54531. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54532. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54533. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54534. };
  54535. return Collider;
  54536. }());
  54537. BABYLON.Collider = Collider;
  54538. })(BABYLON || (BABYLON = {}));
  54539. //# sourceMappingURL=babylon.collider.js.map
  54540. var BABYLON;
  54541. (function (BABYLON) {
  54542. //WebWorker code will be inserted to this variable.
  54543. BABYLON.CollisionWorker = "";
  54544. /** Defines supported task for worker process */
  54545. var WorkerTaskType;
  54546. (function (WorkerTaskType) {
  54547. /** Initialization */
  54548. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54549. /** Update of geometry */
  54550. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54551. /** Evaluate collision */
  54552. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54553. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54554. /** Defines kind of replies returned by worker */
  54555. var WorkerReplyType;
  54556. (function (WorkerReplyType) {
  54557. /** Success */
  54558. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54559. /** Unkown error */
  54560. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54561. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54562. var CollisionCoordinatorWorker = /** @class */ (function () {
  54563. function CollisionCoordinatorWorker() {
  54564. var _this = this;
  54565. this._scaledPosition = BABYLON.Vector3.Zero();
  54566. this._scaledVelocity = BABYLON.Vector3.Zero();
  54567. this.onMeshUpdated = function (transformNode) {
  54568. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54569. };
  54570. this.onGeometryUpdated = function (geometry) {
  54571. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54572. };
  54573. this._afterRender = function () {
  54574. if (!_this._init)
  54575. return;
  54576. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54577. return;
  54578. }
  54579. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54580. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54581. if (_this._runningUpdated > 4) {
  54582. return;
  54583. }
  54584. ++_this._runningUpdated;
  54585. var payload = {
  54586. updatedMeshes: _this._addUpdateMeshesList,
  54587. updatedGeometries: _this._addUpdateGeometriesList,
  54588. removedGeometries: _this._toRemoveGeometryArray,
  54589. removedMeshes: _this._toRemoveMeshesArray
  54590. };
  54591. var message = {
  54592. payload: payload,
  54593. taskType: WorkerTaskType.UPDATE
  54594. };
  54595. var serializable = [];
  54596. for (var id in payload.updatedGeometries) {
  54597. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54598. //prepare transferables
  54599. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54600. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54601. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54602. }
  54603. }
  54604. _this._worker.postMessage(message, serializable);
  54605. _this._addUpdateMeshesList = {};
  54606. _this._addUpdateGeometriesList = {};
  54607. _this._toRemoveGeometryArray = [];
  54608. _this._toRemoveMeshesArray = [];
  54609. };
  54610. this._onMessageFromWorker = function (e) {
  54611. var returnData = e.data;
  54612. if (returnData.error != WorkerReplyType.SUCCESS) {
  54613. //TODO what errors can be returned from the worker?
  54614. BABYLON.Tools.Warn("error returned from worker!");
  54615. return;
  54616. }
  54617. switch (returnData.taskType) {
  54618. case WorkerTaskType.INIT:
  54619. _this._init = true;
  54620. //Update the worked with ALL of the scene's current state
  54621. _this._scene.meshes.forEach(function (mesh) {
  54622. _this.onMeshAdded(mesh);
  54623. });
  54624. _this._scene.getGeometries().forEach(function (geometry) {
  54625. _this.onGeometryAdded(geometry);
  54626. });
  54627. break;
  54628. case WorkerTaskType.UPDATE:
  54629. _this._runningUpdated--;
  54630. break;
  54631. case WorkerTaskType.COLLIDE:
  54632. var returnPayload = returnData.payload;
  54633. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54634. return;
  54635. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54636. if (callback) {
  54637. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54638. if (mesh) {
  54639. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54640. }
  54641. }
  54642. //cleanup
  54643. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54644. break;
  54645. }
  54646. };
  54647. this._collisionsCallbackArray = [];
  54648. this._init = false;
  54649. this._runningUpdated = 0;
  54650. this._addUpdateMeshesList = {};
  54651. this._addUpdateGeometriesList = {};
  54652. this._toRemoveGeometryArray = [];
  54653. this._toRemoveMeshesArray = [];
  54654. }
  54655. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54656. if (!this._init)
  54657. return;
  54658. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54659. return;
  54660. position.divideToRef(collider._radius, this._scaledPosition);
  54661. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54662. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54663. var payload = {
  54664. collider: {
  54665. position: this._scaledPosition.asArray(),
  54666. velocity: this._scaledVelocity.asArray(),
  54667. radius: collider._radius.asArray()
  54668. },
  54669. collisionId: collisionIndex,
  54670. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54671. maximumRetry: maximumRetry
  54672. };
  54673. var message = {
  54674. payload: payload,
  54675. taskType: WorkerTaskType.COLLIDE
  54676. };
  54677. this._worker.postMessage(message);
  54678. };
  54679. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54680. this._scene = scene;
  54681. this._scene.registerAfterRender(this._afterRender);
  54682. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54683. this._worker = new Worker(workerUrl);
  54684. this._worker.onmessage = this._onMessageFromWorker;
  54685. var message = {
  54686. payload: {},
  54687. taskType: WorkerTaskType.INIT
  54688. };
  54689. this._worker.postMessage(message);
  54690. };
  54691. CollisionCoordinatorWorker.prototype.destroy = function () {
  54692. this._scene.unregisterAfterRender(this._afterRender);
  54693. this._worker.terminate();
  54694. };
  54695. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54696. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54697. this.onMeshUpdated(mesh);
  54698. };
  54699. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54700. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54701. };
  54702. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54703. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54704. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54705. this.onGeometryUpdated(geometry);
  54706. };
  54707. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54708. this._toRemoveGeometryArray.push(geometry.id);
  54709. };
  54710. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54711. var submeshes = [];
  54712. if (mesh.subMeshes) {
  54713. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54714. var boundingInfo = sm.getBoundingInfo();
  54715. return {
  54716. position: idx,
  54717. verticesStart: sm.verticesStart,
  54718. verticesCount: sm.verticesCount,
  54719. indexStart: sm.indexStart,
  54720. indexCount: sm.indexCount,
  54721. hasMaterial: !!sm.getMaterial(),
  54722. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54723. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54724. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54725. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54726. };
  54727. });
  54728. }
  54729. var geometryId = null;
  54730. if (mesh instanceof BABYLON.Mesh) {
  54731. var geometry = mesh.geometry;
  54732. geometryId = geometry ? geometry.id : null;
  54733. }
  54734. else if (mesh instanceof BABYLON.InstancedMesh) {
  54735. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54736. geometryId = geometry ? geometry.id : null;
  54737. }
  54738. var boundingInfo = mesh.getBoundingInfo();
  54739. return {
  54740. uniqueId: mesh.uniqueId,
  54741. id: mesh.id,
  54742. name: mesh.name,
  54743. geometryId: geometryId,
  54744. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54745. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54746. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54747. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54748. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54749. subMeshes: submeshes,
  54750. checkCollisions: mesh.checkCollisions
  54751. };
  54752. };
  54753. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54754. return {
  54755. id: geometry.id,
  54756. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54757. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54758. indices: new Uint32Array(geometry.getIndices() || []),
  54759. };
  54760. };
  54761. return CollisionCoordinatorWorker;
  54762. }());
  54763. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54764. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54765. function CollisionCoordinatorLegacy() {
  54766. this._scaledPosition = BABYLON.Vector3.Zero();
  54767. this._scaledVelocity = BABYLON.Vector3.Zero();
  54768. this._finalPosition = BABYLON.Vector3.Zero();
  54769. }
  54770. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54771. position.divideToRef(collider._radius, this._scaledPosition);
  54772. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54773. collider.collidedMesh = null;
  54774. collider._retry = 0;
  54775. collider._initialVelocity = this._scaledVelocity;
  54776. collider._initialPosition = this._scaledPosition;
  54777. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54778. this._finalPosition.multiplyInPlace(collider._radius);
  54779. //run the callback
  54780. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54781. };
  54782. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54783. this._scene = scene;
  54784. };
  54785. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54786. //Legacy need no destruction method.
  54787. };
  54788. //No update in legacy mode
  54789. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54790. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54791. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54792. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54793. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54794. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54795. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54796. if (excludedMesh === void 0) { excludedMesh = null; }
  54797. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54798. if (collider._retry >= maximumRetry) {
  54799. finalPosition.copyFrom(position);
  54800. return;
  54801. }
  54802. // Check if this is a mesh else camera or -1
  54803. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54804. collider._initialize(position, velocity, closeDistance);
  54805. // Check all meshes
  54806. for (var index = 0; index < this._scene.meshes.length; index++) {
  54807. var mesh = this._scene.meshes[index];
  54808. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54809. mesh._checkCollision(collider);
  54810. }
  54811. }
  54812. if (!collider.collisionFound) {
  54813. position.addToRef(velocity, finalPosition);
  54814. return;
  54815. }
  54816. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54817. collider._getResponse(position, velocity);
  54818. }
  54819. if (velocity.length() <= closeDistance) {
  54820. finalPosition.copyFrom(position);
  54821. return;
  54822. }
  54823. collider._retry++;
  54824. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54825. };
  54826. return CollisionCoordinatorLegacy;
  54827. }());
  54828. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54829. })(BABYLON || (BABYLON = {}));
  54830. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54831. var BABYLON;
  54832. (function (BABYLON) {
  54833. /**
  54834. * A particle represents one of the element emitted by a particle system.
  54835. * This is mainly define by its coordinates, direction, velocity and age.
  54836. */
  54837. var Particle = /** @class */ (function () {
  54838. /**
  54839. * Creates a new instance Particle
  54840. * @param particleSystem the particle system the particle belongs to
  54841. */
  54842. function Particle(
  54843. /**
  54844. * particleSystem the particle system the particle belongs to.
  54845. */
  54846. particleSystem) {
  54847. this.particleSystem = particleSystem;
  54848. /**
  54849. * The world position of the particle in the scene.
  54850. */
  54851. this.position = BABYLON.Vector3.Zero();
  54852. /**
  54853. * The world direction of the particle in the scene.
  54854. */
  54855. this.direction = BABYLON.Vector3.Zero();
  54856. /**
  54857. * The color of the particle.
  54858. */
  54859. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54860. /**
  54861. * The color change of the particle per step.
  54862. */
  54863. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54864. /**
  54865. * Defines how long will the life of the particle be.
  54866. */
  54867. this.lifeTime = 1.0;
  54868. /**
  54869. * The current age of the particle.
  54870. */
  54871. this.age = 0;
  54872. /**
  54873. * The current size of the particle.
  54874. */
  54875. this.size = 0;
  54876. /**
  54877. * The current scale of the particle.
  54878. */
  54879. this.scale = new BABYLON.Vector2(1, 1);
  54880. /**
  54881. * The current angle of the particle.
  54882. */
  54883. this.angle = 0;
  54884. /**
  54885. * Defines how fast is the angle changing.
  54886. */
  54887. this.angularSpeed = 0;
  54888. /**
  54889. * Defines the cell index used by the particle to be rendered from a sprite.
  54890. */
  54891. this.cellIndex = 0;
  54892. /** @hidden */
  54893. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  54894. /** @hidden */
  54895. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  54896. /** @hidden */
  54897. this._currentSize1 = 0;
  54898. /** @hidden */
  54899. this._currentSize2 = 0;
  54900. if (!this.particleSystem.isAnimationSheetEnabled) {
  54901. return;
  54902. }
  54903. this.updateCellInfoFromSystem();
  54904. }
  54905. Particle.prototype.updateCellInfoFromSystem = function () {
  54906. this.cellIndex = this.particleSystem.startSpriteCellID;
  54907. };
  54908. /**
  54909. * Defines how the sprite cell index is updated for the particle
  54910. */
  54911. Particle.prototype.updateCellIndex = function () {
  54912. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  54913. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) / this.lifeTime) % this.lifeTime);
  54914. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  54915. };
  54916. /**
  54917. * Copy the properties of particle to another one.
  54918. * @param other the particle to copy the information to.
  54919. */
  54920. Particle.prototype.copyTo = function (other) {
  54921. other.position.copyFrom(this.position);
  54922. if (this._initialDirection) {
  54923. if (other._initialDirection) {
  54924. other._initialDirection.copyFrom(this._initialDirection);
  54925. }
  54926. else {
  54927. other._initialDirection = this._initialDirection.clone();
  54928. }
  54929. }
  54930. else {
  54931. other._initialDirection = null;
  54932. }
  54933. other.direction.copyFrom(this.direction);
  54934. other.color.copyFrom(this.color);
  54935. other.colorStep.copyFrom(this.colorStep);
  54936. other.lifeTime = this.lifeTime;
  54937. other.age = this.age;
  54938. other.size = this.size;
  54939. other.scale.copyFrom(this.scale);
  54940. other.angle = this.angle;
  54941. other.angularSpeed = this.angularSpeed;
  54942. other.particleSystem = this.particleSystem;
  54943. other.cellIndex = this.cellIndex;
  54944. if (this._currentColorGradient) {
  54945. other._currentColorGradient = this._currentColorGradient;
  54946. other._currentColor1.copyFrom(this._currentColor1);
  54947. other._currentColor2.copyFrom(this._currentColor2);
  54948. }
  54949. if (this._currentSizeGradient) {
  54950. other._currentSizeGradient = this._currentSizeGradient;
  54951. other._currentSize1 = this._currentSize1;
  54952. other._currentSize2 = this._currentSize2;
  54953. }
  54954. if (this.particleSystem.isAnimationSheetEnabled) {
  54955. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  54956. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  54957. }
  54958. };
  54959. return Particle;
  54960. }());
  54961. BABYLON.Particle = Particle;
  54962. })(BABYLON || (BABYLON = {}));
  54963. //# sourceMappingURL=babylon.particle.js.map
  54964. var BABYLON;
  54965. (function (BABYLON) {
  54966. /**
  54967. * This represents a particle system in Babylon.
  54968. * 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.
  54969. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  54970. * @example https://doc.babylonjs.com/babylon101/particles
  54971. */
  54972. var ParticleSystem = /** @class */ (function () {
  54973. /**
  54974. * Instantiates a particle system.
  54975. * 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.
  54976. * @param name The name of the particle system
  54977. * @param capacity The max number of particles alive at the same time
  54978. * @param scene The scene the particle system belongs to
  54979. * @param customEffect a custom effect used to change the way particles are rendered by default
  54980. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  54981. * @param epsilon Offset used to render the particles
  54982. */
  54983. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  54984. if (customEffect === void 0) { customEffect = null; }
  54985. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  54986. if (epsilon === void 0) { epsilon = 0.01; }
  54987. var _this = this;
  54988. /**
  54989. * List of animations used by the particle system.
  54990. */
  54991. this.animations = [];
  54992. /**
  54993. * The rendering group used by the Particle system to chose when to render.
  54994. */
  54995. this.renderingGroupId = 0;
  54996. /**
  54997. * The emitter represents the Mesh or position we are attaching the particle system to.
  54998. */
  54999. this.emitter = null;
  55000. /**
  55001. * The maximum number of particles to emit per frame
  55002. */
  55003. this.emitRate = 10;
  55004. /**
  55005. * If you want to launch only a few particles at once, that can be done, as well.
  55006. */
  55007. this.manualEmitCount = -1;
  55008. /**
  55009. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55010. */
  55011. this.updateSpeed = 0.01;
  55012. /**
  55013. * The amount of time the particle system is running (depends of the overall update speed).
  55014. */
  55015. this.targetStopDuration = 0;
  55016. /**
  55017. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55018. */
  55019. this.disposeOnStop = false;
  55020. /**
  55021. * Minimum power of emitting particles.
  55022. */
  55023. this.minEmitPower = 1;
  55024. /**
  55025. * Maximum power of emitting particles.
  55026. */
  55027. this.maxEmitPower = 1;
  55028. /**
  55029. * Minimum life time of emitting particles.
  55030. */
  55031. this.minLifeTime = 1;
  55032. /**
  55033. * Maximum life time of emitting particles.
  55034. */
  55035. this.maxLifeTime = 1;
  55036. /**
  55037. * Minimum Size of emitting particles.
  55038. */
  55039. this.minSize = 1;
  55040. /**
  55041. * Maximum Size of emitting particles.
  55042. */
  55043. this.maxSize = 1;
  55044. /**
  55045. * Minimum scale of emitting particles on X axis.
  55046. */
  55047. this.minScaleX = 1;
  55048. /**
  55049. * Maximum scale of emitting particles on X axis.
  55050. */
  55051. this.maxScaleX = 1;
  55052. /**
  55053. * Minimum scale of emitting particles on Y axis.
  55054. */
  55055. this.minScaleY = 1;
  55056. /**
  55057. * Maximum scale of emitting particles on Y axis.
  55058. */
  55059. this.maxScaleY = 1;
  55060. /**
  55061. * Gets or sets the minimal initial rotation in radians.
  55062. */
  55063. this.minInitialRotation = 0;
  55064. /**
  55065. * Gets or sets the maximal initial rotation in radians.
  55066. */
  55067. this.maxInitialRotation = 0;
  55068. /**
  55069. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55070. */
  55071. this.minAngularSpeed = 0;
  55072. /**
  55073. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55074. */
  55075. this.maxAngularSpeed = 0;
  55076. /**
  55077. * The layer mask we are rendering the particles through.
  55078. */
  55079. this.layerMask = 0x0FFFFFFF;
  55080. /**
  55081. * This can help using your own shader to render the particle system.
  55082. * The according effect will be created
  55083. */
  55084. this.customShader = null;
  55085. /**
  55086. * By default particle system starts as soon as they are created. This prevents the
  55087. * automatic start to happen and let you decide when to start emitting particles.
  55088. */
  55089. this.preventAutoStart = false;
  55090. /**
  55091. * Callback triggered when the particle animation is ending.
  55092. */
  55093. this.onAnimationEnd = null;
  55094. /**
  55095. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55096. */
  55097. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55098. /**
  55099. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55100. * to override the particles.
  55101. */
  55102. this.forceDepthWrite = false;
  55103. /**
  55104. * You can use gravity if you want to give an orientation to your particles.
  55105. */
  55106. this.gravity = BABYLON.Vector3.Zero();
  55107. this._colorGradients = null;
  55108. this._sizeGradients = null;
  55109. this._lifeTimeGradients = null;
  55110. /**
  55111. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55112. */
  55113. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55114. /**
  55115. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55116. */
  55117. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55118. /**
  55119. * Color the particle will have at the end of its lifetime
  55120. */
  55121. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55122. /**
  55123. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55124. */
  55125. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55126. /**
  55127. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55128. */
  55129. this.spriteCellChangeSpeed = 1;
  55130. /**
  55131. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55132. */
  55133. this.startSpriteCellID = 0;
  55134. /**
  55135. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55136. */
  55137. this.endSpriteCellID = 0;
  55138. /**
  55139. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55140. */
  55141. this.spriteCellWidth = 0;
  55142. /**
  55143. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55144. */
  55145. this.spriteCellHeight = 0;
  55146. /** 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 */
  55147. this.preWarmCycles = 0;
  55148. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55149. this.preWarmStepOffset = 1;
  55150. /**
  55151. * An event triggered when the system is disposed
  55152. */
  55153. this.onDisposeObservable = new BABYLON.Observable();
  55154. this._particles = new Array();
  55155. this._stockParticles = new Array();
  55156. this._newPartsExcess = 0;
  55157. this._vertexBuffers = {};
  55158. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55159. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55160. this._scaledDirection = BABYLON.Vector3.Zero();
  55161. this._scaledGravity = BABYLON.Vector3.Zero();
  55162. this._currentRenderId = -1;
  55163. this._useInstancing = false;
  55164. this._started = false;
  55165. this._stopped = false;
  55166. this._actualFrame = 0;
  55167. this._isBillboardBased = true;
  55168. // start of sub system methods
  55169. /**
  55170. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55171. * Its lifetime will start back at 0.
  55172. */
  55173. this.recycleParticle = function (particle) {
  55174. var lastParticle = _this._particles.pop();
  55175. if (lastParticle !== particle) {
  55176. lastParticle.copyTo(particle);
  55177. }
  55178. _this._stockParticles.push(lastParticle);
  55179. };
  55180. this._createParticle = function () {
  55181. var particle;
  55182. if (_this._stockParticles.length !== 0) {
  55183. particle = _this._stockParticles.pop();
  55184. particle.age = 0;
  55185. particle._currentColorGradient = null;
  55186. particle.cellIndex = _this.startSpriteCellID;
  55187. }
  55188. else {
  55189. particle = new BABYLON.Particle(_this);
  55190. }
  55191. return particle;
  55192. };
  55193. this._emitFromParticle = function (particle) {
  55194. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55195. return;
  55196. }
  55197. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55198. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55199. subSystem._rootParticleSystem = _this;
  55200. _this.activeSubSystems.push(subSystem);
  55201. subSystem.start();
  55202. };
  55203. this.id = name;
  55204. this.name = name;
  55205. this._capacity = capacity;
  55206. this._epsilon = epsilon;
  55207. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55208. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55209. this._customEffect = customEffect;
  55210. scene.particleSystems.push(this);
  55211. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55212. this._createIndexBuffer();
  55213. this._createVertexBuffers();
  55214. // Default emitter type
  55215. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55216. this.updateFunction = function (particles) {
  55217. for (var index = 0; index < particles.length; index++) {
  55218. var particle = particles[index];
  55219. particle.age += _this._scaledUpdateSpeed;
  55220. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55221. _this._emitFromParticle(particle);
  55222. _this.recycleParticle(particle);
  55223. index--;
  55224. continue;
  55225. }
  55226. else {
  55227. var ratio = particle.age / particle.lifeTime;
  55228. // Color
  55229. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55230. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55231. if (currentGradient !== particle._currentColorGradient) {
  55232. particle._currentColor1.copyFrom(particle._currentColor2);
  55233. nextGradient.getColorToRef(particle._currentColor2);
  55234. particle._currentColorGradient = currentGradient;
  55235. }
  55236. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55237. });
  55238. }
  55239. else {
  55240. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55241. particle.color.addInPlace(_this._scaledColorStep);
  55242. if (particle.color.a < 0) {
  55243. particle.color.a = 0;
  55244. }
  55245. }
  55246. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55247. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55248. particle.position.addInPlace(_this._scaledDirection);
  55249. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55250. particle.direction.addInPlace(_this._scaledGravity);
  55251. // Gradient
  55252. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55253. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55254. if (currentGradient !== particle._currentSizeGradient) {
  55255. particle._currentSize1 = particle._currentSize2;
  55256. particle._currentSize2 = nextGradient.getFactor();
  55257. particle._currentSizeGradient = currentGradient;
  55258. }
  55259. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55260. });
  55261. }
  55262. if (_this._isAnimationSheetEnabled) {
  55263. particle.updateCellIndex();
  55264. }
  55265. }
  55266. }
  55267. };
  55268. }
  55269. /**
  55270. * Gets the current list of color gradients.
  55271. * You must use addColorGradient and removeColorGradient to udpate this list
  55272. * @returns the list of color gradients
  55273. */
  55274. ParticleSystem.prototype.getColorGradients = function () {
  55275. return this._colorGradients;
  55276. };
  55277. /**
  55278. * Gets the current list of size gradients.
  55279. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55280. * @returns the list of size gradients
  55281. */
  55282. ParticleSystem.prototype.getSizeGradients = function () {
  55283. return this._sizeGradients;
  55284. };
  55285. /**
  55286. * Gets the current list of life time gradients.
  55287. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55288. * @returns the list of life time gradients
  55289. */
  55290. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55291. return this._lifeTimeGradients;
  55292. };
  55293. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55294. /**
  55295. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55296. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55297. */
  55298. get: function () {
  55299. if (this.particleEmitterType.direction1) {
  55300. return this.particleEmitterType.direction1;
  55301. }
  55302. return BABYLON.Vector3.Zero();
  55303. },
  55304. set: function (value) {
  55305. if (this.particleEmitterType.direction1) {
  55306. this.particleEmitterType.direction1 = value;
  55307. }
  55308. },
  55309. enumerable: true,
  55310. configurable: true
  55311. });
  55312. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55313. /**
  55314. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55315. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55316. */
  55317. get: function () {
  55318. if (this.particleEmitterType.direction2) {
  55319. return this.particleEmitterType.direction2;
  55320. }
  55321. return BABYLON.Vector3.Zero();
  55322. },
  55323. set: function (value) {
  55324. if (this.particleEmitterType.direction2) {
  55325. this.particleEmitterType.direction2 = value;
  55326. }
  55327. },
  55328. enumerable: true,
  55329. configurable: true
  55330. });
  55331. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55332. /**
  55333. * 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.
  55334. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55335. */
  55336. get: function () {
  55337. if (this.particleEmitterType.minEmitBox) {
  55338. return this.particleEmitterType.minEmitBox;
  55339. }
  55340. return BABYLON.Vector3.Zero();
  55341. },
  55342. set: function (value) {
  55343. if (this.particleEmitterType.minEmitBox) {
  55344. this.particleEmitterType.minEmitBox = value;
  55345. }
  55346. },
  55347. enumerable: true,
  55348. configurable: true
  55349. });
  55350. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55351. /**
  55352. * 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.
  55353. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55354. */
  55355. get: function () {
  55356. if (this.particleEmitterType.maxEmitBox) {
  55357. return this.particleEmitterType.maxEmitBox;
  55358. }
  55359. return BABYLON.Vector3.Zero();
  55360. },
  55361. set: function (value) {
  55362. if (this.particleEmitterType.maxEmitBox) {
  55363. this.particleEmitterType.maxEmitBox = value;
  55364. }
  55365. },
  55366. enumerable: true,
  55367. configurable: true
  55368. });
  55369. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55370. /**
  55371. * Sets a callback that will be triggered when the system is disposed
  55372. */
  55373. set: function (callback) {
  55374. if (this._onDisposeObserver) {
  55375. this.onDisposeObservable.remove(this._onDisposeObserver);
  55376. }
  55377. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55378. },
  55379. enumerable: true,
  55380. configurable: true
  55381. });
  55382. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55383. /**
  55384. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55385. */
  55386. get: function () {
  55387. return this._isAnimationSheetEnabled;
  55388. },
  55389. enumerable: true,
  55390. configurable: true
  55391. });
  55392. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55393. /**
  55394. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55395. */
  55396. get: function () {
  55397. return this._isBillboardBased;
  55398. },
  55399. set: function (value) {
  55400. if (this._isBillboardBased === value) {
  55401. return;
  55402. }
  55403. this._isBillboardBased = value;
  55404. this._resetEffect();
  55405. },
  55406. enumerable: true,
  55407. configurable: true
  55408. });
  55409. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55410. //end of Sub-emitter
  55411. /**
  55412. * Gets the current list of active particles
  55413. */
  55414. get: function () {
  55415. return this._particles;
  55416. },
  55417. enumerable: true,
  55418. configurable: true
  55419. });
  55420. /**
  55421. * Returns the string "ParticleSystem"
  55422. * @returns a string containing the class name
  55423. */
  55424. ParticleSystem.prototype.getClassName = function () {
  55425. return "ParticleSystem";
  55426. };
  55427. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55428. var newGradient = new BABYLON.FactorGradient();
  55429. newGradient.gradient = gradient;
  55430. newGradient.factor1 = factor;
  55431. newGradient.factor2 = factor2;
  55432. factorGradients.push(newGradient);
  55433. factorGradients.sort(function (a, b) {
  55434. if (a.gradient < b.gradient) {
  55435. return -1;
  55436. }
  55437. else if (a.gradient > b.gradient) {
  55438. return 1;
  55439. }
  55440. return 0;
  55441. });
  55442. };
  55443. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55444. if (!factorGradients) {
  55445. return;
  55446. }
  55447. var index = 0;
  55448. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55449. var factorGradient = factorGradients_1[_i];
  55450. if (factorGradient.gradient === gradient) {
  55451. factorGradients.splice(index, 1);
  55452. break;
  55453. }
  55454. index++;
  55455. }
  55456. };
  55457. /**
  55458. * Adds a new life time gradient
  55459. * @param gradient defines the gradient to use (between 0 and 1)
  55460. * @param factor defines the life time factor to affect to the specified gradient
  55461. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55462. */
  55463. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55464. if (!this._lifeTimeGradients) {
  55465. this._lifeTimeGradients = [];
  55466. }
  55467. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55468. return this;
  55469. };
  55470. /**
  55471. * Remove a specific life time gradient
  55472. * @param gradient defines the gradient to remove
  55473. */
  55474. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55475. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55476. return this;
  55477. };
  55478. /**
  55479. * Adds a new size gradient
  55480. * @param gradient defines the gradient to use (between 0 and 1)
  55481. * @param factor defines the size factor to affect to the specified gradient
  55482. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55483. */
  55484. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55485. if (!this._sizeGradients) {
  55486. this._sizeGradients = [];
  55487. }
  55488. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55489. return this;
  55490. };
  55491. /**
  55492. * Remove a specific size gradient
  55493. * @param gradient defines the gradient to remove
  55494. */
  55495. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55496. this._removeFactorGradient(this._sizeGradients, gradient);
  55497. return this;
  55498. };
  55499. /**
  55500. * Adds a new color gradient
  55501. * @param gradient defines the gradient to use (between 0 and 1)
  55502. * @param color defines the color to affect to the specified gradient
  55503. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55504. */
  55505. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55506. if (!this._colorGradients) {
  55507. this._colorGradients = [];
  55508. }
  55509. var colorGradient = new BABYLON.ColorGradient();
  55510. colorGradient.gradient = gradient;
  55511. colorGradient.color1 = color;
  55512. colorGradient.color2 = color2;
  55513. this._colorGradients.push(colorGradient);
  55514. this._colorGradients.sort(function (a, b) {
  55515. if (a.gradient < b.gradient) {
  55516. return -1;
  55517. }
  55518. else if (a.gradient > b.gradient) {
  55519. return 1;
  55520. }
  55521. return 0;
  55522. });
  55523. return this;
  55524. };
  55525. /**
  55526. * Remove a specific color gradient
  55527. * @param gradient defines the gradient to remove
  55528. */
  55529. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55530. if (!this._colorGradients) {
  55531. return this;
  55532. }
  55533. var index = 0;
  55534. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55535. var colorGradient = _a[_i];
  55536. if (colorGradient.gradient === gradient) {
  55537. this._colorGradients.splice(index, 1);
  55538. break;
  55539. }
  55540. index++;
  55541. }
  55542. return this;
  55543. };
  55544. ParticleSystem.prototype._resetEffect = function () {
  55545. if (this._vertexBuffer) {
  55546. this._vertexBuffer.dispose();
  55547. this._vertexBuffer = null;
  55548. }
  55549. if (this._spriteBuffer) {
  55550. this._spriteBuffer.dispose();
  55551. this._spriteBuffer = null;
  55552. }
  55553. this._createVertexBuffers();
  55554. };
  55555. ParticleSystem.prototype._createVertexBuffers = function () {
  55556. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55557. if (this._isAnimationSheetEnabled) {
  55558. this._vertexBufferSize += 1;
  55559. }
  55560. if (!this._isBillboardBased) {
  55561. this._vertexBufferSize += 3;
  55562. }
  55563. var engine = this._scene.getEngine();
  55564. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55565. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55566. var dataOffset = 0;
  55567. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55568. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55569. dataOffset += 3;
  55570. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55571. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55572. dataOffset += 4;
  55573. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55574. this._vertexBuffers["angle"] = options;
  55575. dataOffset += 1;
  55576. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55577. this._vertexBuffers["size"] = size;
  55578. dataOffset += 2;
  55579. if (this._isAnimationSheetEnabled) {
  55580. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55581. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55582. dataOffset += 1;
  55583. }
  55584. if (!this._isBillboardBased) {
  55585. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55586. this._vertexBuffers["direction"] = directionBuffer;
  55587. dataOffset += 3;
  55588. }
  55589. var offsets;
  55590. if (this._useInstancing) {
  55591. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55592. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55593. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55594. }
  55595. else {
  55596. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55597. dataOffset += 2;
  55598. }
  55599. this._vertexBuffers["offset"] = offsets;
  55600. };
  55601. ParticleSystem.prototype._createIndexBuffer = function () {
  55602. if (this._useInstancing) {
  55603. return;
  55604. }
  55605. var indices = [];
  55606. var index = 0;
  55607. for (var count = 0; count < this._capacity; count++) {
  55608. indices.push(index);
  55609. indices.push(index + 1);
  55610. indices.push(index + 2);
  55611. indices.push(index);
  55612. indices.push(index + 2);
  55613. indices.push(index + 3);
  55614. index += 4;
  55615. }
  55616. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55617. };
  55618. /**
  55619. * Gets the maximum number of particles active at the same time.
  55620. * @returns The max number of active particles.
  55621. */
  55622. ParticleSystem.prototype.getCapacity = function () {
  55623. return this._capacity;
  55624. };
  55625. /**
  55626. * Gets Wether there are still active particles in the system.
  55627. * @returns True if it is alive, otherwise false.
  55628. */
  55629. ParticleSystem.prototype.isAlive = function () {
  55630. return this._alive;
  55631. };
  55632. /**
  55633. * Gets Wether the system has been started.
  55634. * @returns True if it has been started, otherwise false.
  55635. */
  55636. ParticleSystem.prototype.isStarted = function () {
  55637. return this._started;
  55638. };
  55639. /**
  55640. * Starts the particle system and begins to emit.
  55641. */
  55642. ParticleSystem.prototype.start = function () {
  55643. this._started = true;
  55644. this._stopped = false;
  55645. this._actualFrame = 0;
  55646. if (this.subEmitters && this.subEmitters.length != 0) {
  55647. this.activeSubSystems = new Array();
  55648. }
  55649. if (this.preWarmCycles) {
  55650. for (var index = 0; index < this.preWarmCycles; index++) {
  55651. this.animate(true);
  55652. }
  55653. }
  55654. };
  55655. /**
  55656. * Stops the particle system.
  55657. * @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.
  55658. */
  55659. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55660. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55661. this._stopped = true;
  55662. if (stopSubEmitters) {
  55663. this._stopSubEmitters();
  55664. }
  55665. };
  55666. // animation sheet
  55667. /**
  55668. * Remove all active particles
  55669. */
  55670. ParticleSystem.prototype.reset = function () {
  55671. this._stockParticles = [];
  55672. this._particles = [];
  55673. };
  55674. /**
  55675. * @hidden (for internal use only)
  55676. */
  55677. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55678. var offset = index * this._vertexBufferSize;
  55679. this._vertexData[offset++] = particle.position.x;
  55680. this._vertexData[offset++] = particle.position.y;
  55681. this._vertexData[offset++] = particle.position.z;
  55682. this._vertexData[offset++] = particle.color.r;
  55683. this._vertexData[offset++] = particle.color.g;
  55684. this._vertexData[offset++] = particle.color.b;
  55685. this._vertexData[offset++] = particle.color.a;
  55686. this._vertexData[offset++] = particle.angle;
  55687. this._vertexData[offset++] = particle.scale.x * particle.size;
  55688. this._vertexData[offset++] = particle.scale.y * particle.size;
  55689. if (this._isAnimationSheetEnabled) {
  55690. this._vertexData[offset++] = particle.cellIndex;
  55691. }
  55692. if (!this._isBillboardBased) {
  55693. if (particle._initialDirection) {
  55694. this._vertexData[offset++] = particle._initialDirection.x;
  55695. this._vertexData[offset++] = particle._initialDirection.y;
  55696. this._vertexData[offset++] = particle._initialDirection.z;
  55697. }
  55698. else {
  55699. this._vertexData[offset++] = particle.direction.x;
  55700. this._vertexData[offset++] = particle.direction.y;
  55701. this._vertexData[offset++] = particle.direction.z;
  55702. }
  55703. }
  55704. if (!this._useInstancing) {
  55705. if (this._isAnimationSheetEnabled) {
  55706. if (offsetX === 0)
  55707. offsetX = this._epsilon;
  55708. else if (offsetX === 1)
  55709. offsetX = 1 - this._epsilon;
  55710. if (offsetY === 0)
  55711. offsetY = this._epsilon;
  55712. else if (offsetY === 1)
  55713. offsetY = 1 - this._epsilon;
  55714. }
  55715. this._vertexData[offset++] = offsetX;
  55716. this._vertexData[offset++] = offsetY;
  55717. }
  55718. };
  55719. ParticleSystem.prototype._stopSubEmitters = function () {
  55720. if (!this.activeSubSystems) {
  55721. return;
  55722. }
  55723. this.activeSubSystems.forEach(function (subSystem) {
  55724. subSystem.stop(true);
  55725. });
  55726. this.activeSubSystems = new Array();
  55727. };
  55728. ParticleSystem.prototype._removeFromRoot = function () {
  55729. if (!this._rootParticleSystem) {
  55730. return;
  55731. }
  55732. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55733. if (index !== -1) {
  55734. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55735. }
  55736. };
  55737. // End of sub system methods
  55738. ParticleSystem.prototype._update = function (newParticles) {
  55739. // Update current
  55740. this._alive = this._particles.length > 0;
  55741. this.updateFunction(this._particles);
  55742. // Add new ones
  55743. var worldMatrix;
  55744. if (this.emitter.position) {
  55745. var emitterMesh = this.emitter;
  55746. worldMatrix = emitterMesh.getWorldMatrix();
  55747. }
  55748. else {
  55749. var emitterPosition = this.emitter;
  55750. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55751. }
  55752. var particle;
  55753. var _loop_1 = function () {
  55754. if (this_1._particles.length === this_1._capacity) {
  55755. return "break";
  55756. }
  55757. particle = this_1._createParticle();
  55758. this_1._particles.push(particle);
  55759. // Emitter
  55760. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55761. if (this_1.startPositionFunction) {
  55762. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55763. }
  55764. else {
  55765. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55766. }
  55767. if (this_1.startDirectionFunction) {
  55768. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55769. }
  55770. else {
  55771. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55772. }
  55773. if (emitPower === 0) {
  55774. if (!particle._initialDirection) {
  55775. particle._initialDirection = particle.direction.clone();
  55776. }
  55777. else {
  55778. particle._initialDirection.copyFrom(particle.direction);
  55779. }
  55780. }
  55781. else {
  55782. particle._initialDirection = null;
  55783. }
  55784. particle.direction.scaleInPlace(emitPower);
  55785. // Life time
  55786. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55787. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55788. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55789. var factorGradient1 = currentGradient;
  55790. var factorGradient2 = nextGradient;
  55791. var lifeTime1 = factorGradient1.getFactor();
  55792. var lifeTime2 = factorGradient2.getFactor();
  55793. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55794. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55795. });
  55796. }
  55797. else {
  55798. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55799. }
  55800. // Size
  55801. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55802. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55803. }
  55804. else {
  55805. particle._currentSizeGradient = this_1._sizeGradients[0];
  55806. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55807. particle.size = particle._currentSize1;
  55808. if (this_1._sizeGradients.length > 1) {
  55809. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55810. }
  55811. else {
  55812. particle._currentSize2 = particle._currentSize1;
  55813. }
  55814. }
  55815. // Size and scale
  55816. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55817. // Angle
  55818. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55819. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55820. // Color
  55821. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55822. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55823. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55824. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55825. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55826. }
  55827. else {
  55828. particle._currentColorGradient = this_1._colorGradients[0];
  55829. particle._currentColorGradient.getColorToRef(particle.color);
  55830. particle._currentColor1.copyFrom(particle.color);
  55831. if (this_1._colorGradients.length > 1) {
  55832. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55833. }
  55834. else {
  55835. particle._currentColor2.copyFrom(particle.color);
  55836. }
  55837. }
  55838. // Sheet
  55839. if (this_1._isAnimationSheetEnabled) {
  55840. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55841. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55842. }
  55843. };
  55844. var this_1 = this, step;
  55845. for (var index = 0; index < newParticles; index++) {
  55846. var state_1 = _loop_1();
  55847. if (state_1 === "break")
  55848. break;
  55849. }
  55850. };
  55851. /** @hidden */
  55852. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55853. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55854. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55855. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55856. if (isAnimationSheetEnabled) {
  55857. attributeNamesOrOptions.push("cellIndex");
  55858. }
  55859. if (!isBillboardBased) {
  55860. attributeNamesOrOptions.push("direction");
  55861. }
  55862. return attributeNamesOrOptions;
  55863. };
  55864. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55865. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55866. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55867. if (isAnimationSheetEnabled) {
  55868. effectCreationOption.push("particlesInfos");
  55869. }
  55870. return effectCreationOption;
  55871. };
  55872. ParticleSystem.prototype._getEffect = function () {
  55873. if (this._customEffect) {
  55874. return this._customEffect;
  55875. }
  55876. ;
  55877. var defines = [];
  55878. if (this._scene.clipPlane) {
  55879. defines.push("#define CLIPPLANE");
  55880. }
  55881. if (this._isAnimationSheetEnabled) {
  55882. defines.push("#define ANIMATESHEET");
  55883. }
  55884. if (this._isBillboardBased) {
  55885. defines.push("#define BILLBOARD");
  55886. }
  55887. // Effect
  55888. var join = defines.join("\n");
  55889. if (this._cachedDefines !== join) {
  55890. this._cachedDefines = join;
  55891. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  55892. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  55893. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55894. }
  55895. return this._effect;
  55896. };
  55897. /**
  55898. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55899. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  55900. */
  55901. ParticleSystem.prototype.animate = function (preWarmOnly) {
  55902. if (preWarmOnly === void 0) { preWarmOnly = false; }
  55903. if (!this._started)
  55904. return;
  55905. if (!preWarmOnly) {
  55906. var effect = this._getEffect();
  55907. // Check
  55908. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55909. return;
  55910. if (this._currentRenderId === this._scene.getRenderId()) {
  55911. return;
  55912. }
  55913. this._currentRenderId = this._scene.getRenderId();
  55914. }
  55915. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  55916. // determine the number of particles we need to create
  55917. var newParticles;
  55918. if (this.manualEmitCount > -1) {
  55919. newParticles = this.manualEmitCount;
  55920. this._newPartsExcess = 0;
  55921. this.manualEmitCount = 0;
  55922. }
  55923. else {
  55924. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55925. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55926. }
  55927. if (this._newPartsExcess > 1.0) {
  55928. newParticles += this._newPartsExcess >> 0;
  55929. this._newPartsExcess -= this._newPartsExcess >> 0;
  55930. }
  55931. this._alive = false;
  55932. if (!this._stopped) {
  55933. this._actualFrame += this._scaledUpdateSpeed;
  55934. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55935. this.stop();
  55936. }
  55937. else {
  55938. newParticles = 0;
  55939. }
  55940. this._update(newParticles);
  55941. // Stopped?
  55942. if (this._stopped) {
  55943. if (!this._alive) {
  55944. this._started = false;
  55945. if (this.onAnimationEnd) {
  55946. this.onAnimationEnd();
  55947. }
  55948. if (this.disposeOnStop) {
  55949. this._scene._toBeDisposed.push(this);
  55950. }
  55951. }
  55952. }
  55953. if (!preWarmOnly) {
  55954. // Update VBO
  55955. var offset = 0;
  55956. for (var index = 0; index < this._particles.length; index++) {
  55957. var particle = this._particles[index];
  55958. this._appendParticleVertices(offset, particle);
  55959. offset += this._useInstancing ? 1 : 4;
  55960. }
  55961. if (this._vertexBuffer) {
  55962. this._vertexBuffer.update(this._vertexData);
  55963. }
  55964. }
  55965. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55966. this.stop();
  55967. }
  55968. };
  55969. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  55970. this._appendParticleVertex(offset++, particle, 0, 0);
  55971. if (!this._useInstancing) {
  55972. this._appendParticleVertex(offset++, particle, 1, 0);
  55973. this._appendParticleVertex(offset++, particle, 1, 1);
  55974. this._appendParticleVertex(offset++, particle, 0, 1);
  55975. }
  55976. };
  55977. /**
  55978. * Rebuilds the particle system.
  55979. */
  55980. ParticleSystem.prototype.rebuild = function () {
  55981. this._createIndexBuffer();
  55982. if (this._vertexBuffer) {
  55983. this._vertexBuffer._rebuild();
  55984. }
  55985. };
  55986. /**
  55987. * Is this system ready to be used/rendered
  55988. * @return true if the system is ready
  55989. */
  55990. ParticleSystem.prototype.isReady = function () {
  55991. var effect = this._getEffect();
  55992. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55993. return false;
  55994. }
  55995. return true;
  55996. };
  55997. /**
  55998. * Renders the particle system in its current state.
  55999. * @returns the current number of particles
  56000. */
  56001. ParticleSystem.prototype.render = function () {
  56002. var effect = this._getEffect();
  56003. // Check
  56004. if (!this.isReady() || !this._particles.length) {
  56005. return 0;
  56006. }
  56007. var engine = this._scene.getEngine();
  56008. // Render
  56009. engine.enableEffect(effect);
  56010. engine.setState(false);
  56011. var viewMatrix = this._scene.getViewMatrix();
  56012. effect.setTexture("diffuseSampler", this.particleTexture);
  56013. effect.setMatrix("view", viewMatrix);
  56014. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56015. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56016. var baseSize = this.particleTexture.getBaseSize();
  56017. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56018. }
  56019. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56020. if (this._scene.clipPlane) {
  56021. var clipPlane = this._scene.clipPlane;
  56022. var invView = viewMatrix.clone();
  56023. invView.invert();
  56024. effect.setMatrix("invView", invView);
  56025. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56026. }
  56027. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56028. // Draw order
  56029. switch (this.blendMode) {
  56030. case ParticleSystem.BLENDMODE_ADD:
  56031. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56032. break;
  56033. case ParticleSystem.BLENDMODE_ONEONE:
  56034. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56035. break;
  56036. case ParticleSystem.BLENDMODE_STANDARD:
  56037. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56038. break;
  56039. }
  56040. if (this.forceDepthWrite) {
  56041. engine.setDepthWrite(true);
  56042. }
  56043. if (this._useInstancing) {
  56044. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56045. engine.unbindInstanceAttributes();
  56046. }
  56047. else {
  56048. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56049. }
  56050. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56051. return this._particles.length;
  56052. };
  56053. /**
  56054. * Disposes the particle system and free the associated resources
  56055. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56056. */
  56057. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56058. if (disposeTexture === void 0) { disposeTexture = true; }
  56059. if (this._vertexBuffer) {
  56060. this._vertexBuffer.dispose();
  56061. this._vertexBuffer = null;
  56062. }
  56063. if (this._spriteBuffer) {
  56064. this._spriteBuffer.dispose();
  56065. this._spriteBuffer = null;
  56066. }
  56067. if (this._indexBuffer) {
  56068. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56069. this._indexBuffer = null;
  56070. }
  56071. if (disposeTexture && this.particleTexture) {
  56072. this.particleTexture.dispose();
  56073. this.particleTexture = null;
  56074. }
  56075. this._removeFromRoot();
  56076. // Remove from scene
  56077. var index = this._scene.particleSystems.indexOf(this);
  56078. if (index > -1) {
  56079. this._scene.particleSystems.splice(index, 1);
  56080. }
  56081. // Callback
  56082. this.onDisposeObservable.notifyObservers(this);
  56083. this.onDisposeObservable.clear();
  56084. };
  56085. /**
  56086. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56087. * @param radius The radius of the sphere to emit from
  56088. * @returns the emitter
  56089. */
  56090. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56091. if (radius === void 0) { radius = 1; }
  56092. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56093. this.particleEmitterType = particleEmitter;
  56094. return particleEmitter;
  56095. };
  56096. /**
  56097. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56098. * @param radius The radius of the sphere to emit from
  56099. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56100. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56101. * @returns the emitter
  56102. */
  56103. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56104. if (radius === void 0) { radius = 1; }
  56105. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56106. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56107. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56108. this.particleEmitterType = particleEmitter;
  56109. return particleEmitter;
  56110. };
  56111. /**
  56112. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56113. * @param radius The radius of the cone to emit from
  56114. * @param angle The base angle of the cone
  56115. * @returns the emitter
  56116. */
  56117. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56118. if (radius === void 0) { radius = 1; }
  56119. if (angle === void 0) { angle = Math.PI / 4; }
  56120. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56121. this.particleEmitterType = particleEmitter;
  56122. return particleEmitter;
  56123. };
  56124. // 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.
  56125. /**
  56126. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56127. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56128. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56129. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56130. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56131. * @returns the emitter
  56132. */
  56133. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56134. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56135. this.particleEmitterType = particleEmitter;
  56136. this.direction1 = direction1;
  56137. this.direction2 = direction2;
  56138. this.minEmitBox = minEmitBox;
  56139. this.maxEmitBox = maxEmitBox;
  56140. return particleEmitter;
  56141. };
  56142. // Clone
  56143. /**
  56144. * Clones the particle system.
  56145. * @param name The name of the cloned object
  56146. * @param newEmitter The new emitter to use
  56147. * @returns the cloned particle system
  56148. */
  56149. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56150. var custom = null;
  56151. var program = null;
  56152. if (this.customShader != null) {
  56153. program = this.customShader;
  56154. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56155. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56156. }
  56157. else if (this._customEffect) {
  56158. custom = this._customEffect;
  56159. }
  56160. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56161. result.customShader = program;
  56162. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56163. if (newEmitter === undefined) {
  56164. newEmitter = this.emitter;
  56165. }
  56166. result.emitter = newEmitter;
  56167. if (this.particleTexture) {
  56168. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56169. }
  56170. if (!this.preventAutoStart) {
  56171. result.start();
  56172. }
  56173. return result;
  56174. };
  56175. /**
  56176. * Serializes the particle system to a JSON object.
  56177. * @returns the JSON object
  56178. */
  56179. ParticleSystem.prototype.serialize = function () {
  56180. var serializationObject = {};
  56181. ParticleSystem._Serialize(serializationObject, this);
  56182. serializationObject.textureMask = this.textureMask.asArray();
  56183. serializationObject.customShader = this.customShader;
  56184. serializationObject.preventAutoStart = this.preventAutoStart;
  56185. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56186. return serializationObject;
  56187. };
  56188. /** @hidden */
  56189. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56190. serializationObject.name = particleSystem.name;
  56191. serializationObject.id = particleSystem.id;
  56192. serializationObject.capacity = particleSystem.getCapacity();
  56193. // Emitter
  56194. if (particleSystem.emitter.position) {
  56195. var emitterMesh = particleSystem.emitter;
  56196. serializationObject.emitterId = emitterMesh.id;
  56197. }
  56198. else {
  56199. var emitterPosition = particleSystem.emitter;
  56200. serializationObject.emitter = emitterPosition.asArray();
  56201. }
  56202. // Emitter
  56203. if (particleSystem.particleEmitterType) {
  56204. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56205. }
  56206. if (particleSystem.particleTexture) {
  56207. serializationObject.textureName = particleSystem.particleTexture.name;
  56208. }
  56209. // Animations
  56210. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56211. // Particle system
  56212. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56213. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56214. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56215. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56216. serializationObject.minSize = particleSystem.minSize;
  56217. serializationObject.maxSize = particleSystem.maxSize;
  56218. serializationObject.minScaleX = particleSystem.minScaleX;
  56219. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56220. serializationObject.minScaleY = particleSystem.minScaleY;
  56221. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56222. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56223. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56224. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56225. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56226. serializationObject.emitRate = particleSystem.emitRate;
  56227. serializationObject.gravity = particleSystem.gravity.asArray();
  56228. serializationObject.color1 = particleSystem.color1.asArray();
  56229. serializationObject.color2 = particleSystem.color2.asArray();
  56230. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56231. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56232. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56233. serializationObject.blendMode = particleSystem.blendMode;
  56234. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56235. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56236. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56237. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56238. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56239. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56240. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56241. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56242. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56243. var colorGradients = particleSystem.getColorGradients();
  56244. if (colorGradients) {
  56245. serializationObject.colorGradients = [];
  56246. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56247. var colorGradient = colorGradients_1[_i];
  56248. var serializedGradient = {
  56249. gradient: colorGradient.gradient,
  56250. color1: colorGradient.color1.asArray()
  56251. };
  56252. if (colorGradient.color2) {
  56253. serializedGradient.color2 = colorGradient.color2.asArray();
  56254. }
  56255. serializationObject.colorGradients.push(serializedGradient);
  56256. }
  56257. }
  56258. var sizeGradients = particleSystem.getSizeGradients();
  56259. if (sizeGradients) {
  56260. serializationObject.sizeGradients = [];
  56261. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56262. var sizeGradient = sizeGradients_1[_a];
  56263. var serializedGradient = {
  56264. gradient: sizeGradient.gradient,
  56265. factor1: sizeGradient.factor1
  56266. };
  56267. if (sizeGradient.factor2 !== undefined) {
  56268. serializedGradient.factor2 = sizeGradient.factor2;
  56269. }
  56270. serializationObject.sizeGradients.push(serializedGradient);
  56271. }
  56272. }
  56273. };
  56274. /** @hidden */
  56275. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56276. // Texture
  56277. if (parsedParticleSystem.textureName) {
  56278. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56279. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56280. }
  56281. // Emitter
  56282. if (parsedParticleSystem.emitterId === undefined) {
  56283. particleSystem.emitter = BABYLON.Vector3.Zero();
  56284. }
  56285. else if (parsedParticleSystem.emitterId) {
  56286. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56287. }
  56288. else {
  56289. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56290. }
  56291. // Misc.
  56292. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56293. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56294. }
  56295. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56296. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56297. }
  56298. // Animations
  56299. if (parsedParticleSystem.animations) {
  56300. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56301. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56302. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56303. }
  56304. }
  56305. if (parsedParticleSystem.autoAnimate) {
  56306. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56307. }
  56308. // Particle system
  56309. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56310. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56311. particleSystem.minSize = parsedParticleSystem.minSize;
  56312. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56313. if (parsedParticleSystem.minScaleX) {
  56314. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56315. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56316. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56317. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56318. }
  56319. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56320. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56321. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56322. }
  56323. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56324. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56325. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56326. }
  56327. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56328. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56329. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56330. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56331. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56332. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56333. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56334. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56335. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56336. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56337. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56338. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56339. if (parsedParticleSystem.colorGradients) {
  56340. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56341. var colorGradient = _a[_i];
  56342. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56343. }
  56344. }
  56345. if (parsedParticleSystem.sizeGradients) {
  56346. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56347. var sizeGradient = _c[_b];
  56348. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56349. }
  56350. }
  56351. // Emitter
  56352. var emitterType;
  56353. if (parsedParticleSystem.particleEmitterType) {
  56354. switch (parsedParticleSystem.particleEmitterType.type) {
  56355. case "SphereParticleEmitter":
  56356. emitterType = new BABYLON.SphereParticleEmitter();
  56357. break;
  56358. case "SphereDirectedParticleEmitter":
  56359. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56360. break;
  56361. case "ConeEmitter":
  56362. case "ConeParticleEmitter":
  56363. emitterType = new BABYLON.ConeParticleEmitter();
  56364. break;
  56365. case "BoxEmitter":
  56366. case "BoxParticleEmitter":
  56367. default:
  56368. emitterType = new BABYLON.BoxParticleEmitter();
  56369. break;
  56370. }
  56371. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56372. }
  56373. else {
  56374. emitterType = new BABYLON.BoxParticleEmitter();
  56375. emitterType.parse(parsedParticleSystem);
  56376. }
  56377. particleSystem.particleEmitterType = emitterType;
  56378. // Animation sheet
  56379. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56380. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56381. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56382. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56383. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56384. };
  56385. /**
  56386. * Parses a JSON object to create a particle system.
  56387. * @param parsedParticleSystem The JSON object to parse
  56388. * @param scene The scene to create the particle system in
  56389. * @param rootUrl The root url to use to load external dependencies like texture
  56390. * @returns the Parsed particle system
  56391. */
  56392. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56393. var name = parsedParticleSystem.name;
  56394. var custom = null;
  56395. var program = null;
  56396. if (parsedParticleSystem.customShader) {
  56397. program = parsedParticleSystem.customShader;
  56398. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56399. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56400. }
  56401. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56402. particleSystem.customShader = program;
  56403. if (parsedParticleSystem.id) {
  56404. particleSystem.id = parsedParticleSystem.id;
  56405. }
  56406. // Auto start
  56407. if (parsedParticleSystem.preventAutoStart) {
  56408. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56409. }
  56410. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56411. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56412. if (!particleSystem.preventAutoStart) {
  56413. particleSystem.start();
  56414. }
  56415. return particleSystem;
  56416. };
  56417. /**
  56418. * Source color is added to the destination color without alpha affecting the result.
  56419. */
  56420. ParticleSystem.BLENDMODE_ONEONE = 0;
  56421. /**
  56422. * Blend current color and particle color using particle’s alpha.
  56423. */
  56424. ParticleSystem.BLENDMODE_STANDARD = 1;
  56425. /**
  56426. * Add current color and particle color multiplied by particle’s alpha.
  56427. */
  56428. ParticleSystem.BLENDMODE_ADD = 2;
  56429. return ParticleSystem;
  56430. }());
  56431. BABYLON.ParticleSystem = ParticleSystem;
  56432. })(BABYLON || (BABYLON = {}));
  56433. //# sourceMappingURL=babylon.particleSystem.js.map
  56434. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56435. var BABYLON;
  56436. (function (BABYLON) {
  56437. /**
  56438. * Particle emitter emitting particles from the inside of a box.
  56439. * It emits the particles randomly between 2 given directions.
  56440. */
  56441. var BoxParticleEmitter = /** @class */ (function () {
  56442. /**
  56443. * Creates a new instance BoxParticleEmitter
  56444. */
  56445. function BoxParticleEmitter() {
  56446. /**
  56447. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56448. */
  56449. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56450. /**
  56451. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56452. */
  56453. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56454. /**
  56455. * 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.
  56456. */
  56457. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56458. /**
  56459. * 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.
  56460. */
  56461. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56462. }
  56463. /**
  56464. * Called by the particle System when the direction is computed for the created particle.
  56465. * @param worldMatrix is the world matrix of the particle system
  56466. * @param directionToUpdate is the direction vector to update with the result
  56467. * @param particle is the particle we are computed the direction for
  56468. */
  56469. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56470. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56471. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56472. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56473. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56474. };
  56475. /**
  56476. * Called by the particle System when the position is computed for the created particle.
  56477. * @param worldMatrix is the world matrix of the particle system
  56478. * @param positionToUpdate is the position vector to update with the result
  56479. * @param particle is the particle we are computed the position for
  56480. */
  56481. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56482. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56483. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56484. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56485. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56486. };
  56487. /**
  56488. * Clones the current emitter and returns a copy of it
  56489. * @returns the new emitter
  56490. */
  56491. BoxParticleEmitter.prototype.clone = function () {
  56492. var newOne = new BoxParticleEmitter();
  56493. BABYLON.Tools.DeepCopy(this, newOne);
  56494. return newOne;
  56495. };
  56496. /**
  56497. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56498. * @param effect defines the update shader
  56499. */
  56500. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56501. effect.setVector3("direction1", this.direction1);
  56502. effect.setVector3("direction2", this.direction2);
  56503. effect.setVector3("minEmitBox", this.minEmitBox);
  56504. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56505. };
  56506. /**
  56507. * Returns a string to use to update the GPU particles update shader
  56508. * @returns a string containng the defines string
  56509. */
  56510. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56511. return "#define BOXEMITTER";
  56512. };
  56513. /**
  56514. * Returns the string "BoxParticleEmitter"
  56515. * @returns a string containing the class name
  56516. */
  56517. BoxParticleEmitter.prototype.getClassName = function () {
  56518. return "BoxParticleEmitter";
  56519. };
  56520. /**
  56521. * Serializes the particle system to a JSON object.
  56522. * @returns the JSON object
  56523. */
  56524. BoxParticleEmitter.prototype.serialize = function () {
  56525. var serializationObject = {};
  56526. serializationObject.type = this.getClassName();
  56527. serializationObject.direction1 = this.direction1.asArray();
  56528. serializationObject.direction2 = this.direction2.asArray();
  56529. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56530. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56531. return serializationObject;
  56532. };
  56533. /**
  56534. * Parse properties from a JSON object
  56535. * @param serializationObject defines the JSON object
  56536. */
  56537. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56538. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56539. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56540. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56541. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56542. };
  56543. return BoxParticleEmitter;
  56544. }());
  56545. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56546. })(BABYLON || (BABYLON = {}));
  56547. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56548. var BABYLON;
  56549. (function (BABYLON) {
  56550. /**
  56551. * Particle emitter emitting particles from the inside of a cone.
  56552. * It emits the particles alongside the cone volume from the base to the particle.
  56553. * The emission direction might be randomized.
  56554. */
  56555. var ConeParticleEmitter = /** @class */ (function () {
  56556. /**
  56557. * Creates a new instance ConeParticleEmitter
  56558. * @param radius the radius of the emission cone (1 by default)
  56559. * @param angles the cone base angle (PI by default)
  56560. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56561. */
  56562. function ConeParticleEmitter(radius, angle,
  56563. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56564. directionRandomizer) {
  56565. if (radius === void 0) { radius = 1; }
  56566. if (angle === void 0) { angle = Math.PI; }
  56567. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56568. this.directionRandomizer = directionRandomizer;
  56569. this.angle = angle;
  56570. this.radius = radius;
  56571. }
  56572. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56573. /**
  56574. * Gets or sets the radius of the emission cone
  56575. */
  56576. get: function () {
  56577. return this._radius;
  56578. },
  56579. set: function (value) {
  56580. this._radius = value;
  56581. this._buildHeight();
  56582. },
  56583. enumerable: true,
  56584. configurable: true
  56585. });
  56586. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56587. /**
  56588. * Gets or sets the angle of the emission cone
  56589. */
  56590. get: function () {
  56591. return this._angle;
  56592. },
  56593. set: function (value) {
  56594. this._angle = value;
  56595. this._buildHeight();
  56596. },
  56597. enumerable: true,
  56598. configurable: true
  56599. });
  56600. ConeParticleEmitter.prototype._buildHeight = function () {
  56601. if (this._angle !== 0) {
  56602. this._height = this._radius / Math.tan(this._angle / 2);
  56603. }
  56604. else {
  56605. this._height = 1;
  56606. }
  56607. };
  56608. /**
  56609. * Called by the particle System when the direction is computed for the created particle.
  56610. * @param worldMatrix is the world matrix of the particle system
  56611. * @param directionToUpdate is the direction vector to update with the result
  56612. * @param particle is the particle we are computed the direction for
  56613. */
  56614. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56615. if (this._angle === 0) {
  56616. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56617. }
  56618. else {
  56619. // measure the direction Vector from the emitter to the particle.
  56620. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56621. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56622. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56623. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56624. direction.x += randX;
  56625. direction.y += randY;
  56626. direction.z += randZ;
  56627. direction.normalize();
  56628. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56629. }
  56630. };
  56631. /**
  56632. * Called by the particle System when the position is computed for the created particle.
  56633. * @param worldMatrix is the world matrix of the particle system
  56634. * @param positionToUpdate is the position vector to update with the result
  56635. * @param particle is the particle we are computed the position for
  56636. */
  56637. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56638. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56639. var h = BABYLON.Scalar.RandomRange(0, 1);
  56640. // Better distribution in a cone at normal angles.
  56641. h = 1 - h * h;
  56642. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56643. radius = radius * h;
  56644. var randX = radius * Math.sin(s);
  56645. var randZ = radius * Math.cos(s);
  56646. var randY = h * this._height;
  56647. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56648. };
  56649. /**
  56650. * Clones the current emitter and returns a copy of it
  56651. * @returns the new emitter
  56652. */
  56653. ConeParticleEmitter.prototype.clone = function () {
  56654. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56655. BABYLON.Tools.DeepCopy(this, newOne);
  56656. return newOne;
  56657. };
  56658. /**
  56659. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56660. * @param effect defines the update shader
  56661. */
  56662. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56663. effect.setFloat("radius", this._radius);
  56664. effect.setFloat("coneAngle", this._angle);
  56665. effect.setFloat("height", this._height);
  56666. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56667. };
  56668. /**
  56669. * Returns a string to use to update the GPU particles update shader
  56670. * @returns a string containng the defines string
  56671. */
  56672. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56673. return "#define CONEEMITTER";
  56674. };
  56675. /**
  56676. * Returns the string "ConeParticleEmitter"
  56677. * @returns a string containing the class name
  56678. */
  56679. ConeParticleEmitter.prototype.getClassName = function () {
  56680. return "ConeParticleEmitter";
  56681. };
  56682. /**
  56683. * Serializes the particle system to a JSON object.
  56684. * @returns the JSON object
  56685. */
  56686. ConeParticleEmitter.prototype.serialize = function () {
  56687. var serializationObject = {};
  56688. serializationObject.type = this.getClassName();
  56689. serializationObject.radius = this._radius;
  56690. serializationObject.angle = this._angle;
  56691. serializationObject.directionRandomizer = this.directionRandomizer;
  56692. return serializationObject;
  56693. };
  56694. /**
  56695. * Parse properties from a JSON object
  56696. * @param serializationObject defines the JSON object
  56697. */
  56698. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56699. this.radius = serializationObject.radius;
  56700. this.angle = serializationObject.angle;
  56701. this.directionRandomizer = serializationObject.directionRandomizer;
  56702. };
  56703. return ConeParticleEmitter;
  56704. }());
  56705. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56706. })(BABYLON || (BABYLON = {}));
  56707. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56708. var BABYLON;
  56709. (function (BABYLON) {
  56710. /**
  56711. * Particle emitter emitting particles from the inside of a sphere.
  56712. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56713. */
  56714. var SphereParticleEmitter = /** @class */ (function () {
  56715. /**
  56716. * Creates a new instance SphereParticleEmitter
  56717. * @param radius the radius of the emission sphere (1 by default)
  56718. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56719. */
  56720. function SphereParticleEmitter(
  56721. /**
  56722. * The radius of the emission sphere.
  56723. */
  56724. radius,
  56725. /**
  56726. * How much to randomize the particle direction [0-1].
  56727. */
  56728. directionRandomizer) {
  56729. if (radius === void 0) { radius = 1; }
  56730. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56731. this.radius = radius;
  56732. this.directionRandomizer = directionRandomizer;
  56733. /**
  56734. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56735. */
  56736. this.radiusRange = 1;
  56737. }
  56738. /**
  56739. * Called by the particle System when the direction is computed for the created particle.
  56740. * @param worldMatrix is the world matrix of the particle system
  56741. * @param directionToUpdate is the direction vector to update with the result
  56742. * @param particle is the particle we are computed the direction for
  56743. */
  56744. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56745. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56746. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56747. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56748. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56749. direction.x += randX;
  56750. direction.y += randY;
  56751. direction.z += randZ;
  56752. direction.normalize();
  56753. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56754. };
  56755. /**
  56756. * Called by the particle System when the position is computed for the created particle.
  56757. * @param worldMatrix is the world matrix of the particle system
  56758. * @param positionToUpdate is the position vector to update with the result
  56759. * @param particle is the particle we are computed the position for
  56760. */
  56761. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56762. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56763. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56764. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56765. var theta = Math.acos(2 * v - 1);
  56766. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56767. var randY = randRadius * Math.cos(theta);
  56768. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56769. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56770. };
  56771. /**
  56772. * Clones the current emitter and returns a copy of it
  56773. * @returns the new emitter
  56774. */
  56775. SphereParticleEmitter.prototype.clone = function () {
  56776. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56777. BABYLON.Tools.DeepCopy(this, newOne);
  56778. return newOne;
  56779. };
  56780. /**
  56781. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56782. * @param effect defines the update shader
  56783. */
  56784. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56785. effect.setFloat("radius", this.radius);
  56786. effect.setFloat("radiusRange", this.radiusRange);
  56787. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56788. };
  56789. /**
  56790. * Returns a string to use to update the GPU particles update shader
  56791. * @returns a string containng the defines string
  56792. */
  56793. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56794. return "#define SPHEREEMITTER";
  56795. };
  56796. /**
  56797. * Returns the string "SphereParticleEmitter"
  56798. * @returns a string containing the class name
  56799. */
  56800. SphereParticleEmitter.prototype.getClassName = function () {
  56801. return "SphereParticleEmitter";
  56802. };
  56803. /**
  56804. * Serializes the particle system to a JSON object.
  56805. * @returns the JSON object
  56806. */
  56807. SphereParticleEmitter.prototype.serialize = function () {
  56808. var serializationObject = {};
  56809. serializationObject.type = this.getClassName();
  56810. serializationObject.radius = this.radius;
  56811. serializationObject.radiusRange = this.radiusRange;
  56812. serializationObject.directionRandomizer = this.directionRandomizer;
  56813. return serializationObject;
  56814. };
  56815. /**
  56816. * Parse properties from a JSON object
  56817. * @param serializationObject defines the JSON object
  56818. */
  56819. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56820. this.radius = serializationObject.radius;
  56821. this.radiusRange = serializationObject.radiusRange;
  56822. this.directionRandomizer = serializationObject.directionRandomizer;
  56823. };
  56824. return SphereParticleEmitter;
  56825. }());
  56826. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56827. /**
  56828. * Particle emitter emitting particles from the inside of a sphere.
  56829. * It emits the particles randomly between two vectors.
  56830. */
  56831. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56832. __extends(SphereDirectedParticleEmitter, _super);
  56833. /**
  56834. * Creates a new instance SphereDirectedParticleEmitter
  56835. * @param radius the radius of the emission sphere (1 by default)
  56836. * @param direction1 the min limit of the emission direction (up vector by default)
  56837. * @param direction2 the max limit of the emission direction (up vector by default)
  56838. */
  56839. function SphereDirectedParticleEmitter(radius,
  56840. /**
  56841. * The min limit of the emission direction.
  56842. */
  56843. direction1,
  56844. /**
  56845. * The max limit of the emission direction.
  56846. */
  56847. direction2) {
  56848. if (radius === void 0) { radius = 1; }
  56849. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56850. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56851. var _this = _super.call(this, radius) || this;
  56852. _this.direction1 = direction1;
  56853. _this.direction2 = direction2;
  56854. return _this;
  56855. }
  56856. /**
  56857. * Called by the particle System when the direction is computed for the created particle.
  56858. * @param worldMatrix is the world matrix of the particle system
  56859. * @param directionToUpdate is the direction vector to update with the result
  56860. * @param particle is the particle we are computed the direction for
  56861. */
  56862. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56863. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56864. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56865. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56866. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56867. };
  56868. /**
  56869. * Clones the current emitter and returns a copy of it
  56870. * @returns the new emitter
  56871. */
  56872. SphereDirectedParticleEmitter.prototype.clone = function () {
  56873. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56874. BABYLON.Tools.DeepCopy(this, newOne);
  56875. return newOne;
  56876. };
  56877. /**
  56878. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56879. * @param effect defines the update shader
  56880. */
  56881. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56882. effect.setFloat("radius", this.radius);
  56883. effect.setFloat("radiusRange", this.radiusRange);
  56884. effect.setVector3("direction1", this.direction1);
  56885. effect.setVector3("direction2", this.direction2);
  56886. };
  56887. /**
  56888. * Returns a string to use to update the GPU particles update shader
  56889. * @returns a string containng the defines string
  56890. */
  56891. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56892. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56893. };
  56894. /**
  56895. * Returns the string "SphereDirectedParticleEmitter"
  56896. * @returns a string containing the class name
  56897. */
  56898. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56899. return "SphereDirectedParticleEmitter";
  56900. };
  56901. /**
  56902. * Serializes the particle system to a JSON object.
  56903. * @returns the JSON object
  56904. */
  56905. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56906. var serializationObject = _super.prototype.serialize.call(this);
  56907. serializationObject.direction1 = this.direction1.asArray();
  56908. serializationObject.direction2 = this.direction2.asArray();
  56909. return serializationObject;
  56910. };
  56911. /**
  56912. * Parse properties from a JSON object
  56913. * @param serializationObject defines the JSON object
  56914. */
  56915. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56916. _super.prototype.parse.call(this, serializationObject);
  56917. this.direction1.copyFrom(serializationObject.direction1);
  56918. this.direction2.copyFrom(serializationObject.direction2);
  56919. };
  56920. return SphereDirectedParticleEmitter;
  56921. }(SphereParticleEmitter));
  56922. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56923. })(BABYLON || (BABYLON = {}));
  56924. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56925. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56926. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56927. s = arguments[i];
  56928. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56929. t[p] = s[p];
  56930. }
  56931. return t;
  56932. };
  56933. var BABYLON;
  56934. (function (BABYLON) {
  56935. /**
  56936. * This represents a GPU particle system in Babylon
  56937. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56938. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56939. */
  56940. var GPUParticleSystem = /** @class */ (function () {
  56941. /**
  56942. * Instantiates a GPU particle system.
  56943. * 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.
  56944. * @param name The name of the particle system
  56945. * @param options The options used to create the system
  56946. * @param scene The scene the particle system belongs to
  56947. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  56948. */
  56949. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  56950. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  56951. /**
  56952. * The emitter represents the Mesh or position we are attaching the particle system to.
  56953. */
  56954. this.emitter = null;
  56955. /**
  56956. * The rendering group used by the Particle system to chose when to render.
  56957. */
  56958. this.renderingGroupId = 0;
  56959. /**
  56960. * The layer mask we are rendering the particles through.
  56961. */
  56962. this.layerMask = 0x0FFFFFFF;
  56963. this._accumulatedCount = 0;
  56964. this._targetIndex = 0;
  56965. this._currentRenderId = -1;
  56966. this._started = false;
  56967. this._stopped = false;
  56968. this._timeDelta = 0;
  56969. this._attributesStrideSize = 21;
  56970. this._actualFrame = 0;
  56971. /**
  56972. * List of animations used by the particle system.
  56973. */
  56974. this.animations = [];
  56975. /**
  56976. * An event triggered when the system is disposed.
  56977. */
  56978. this.onDisposeObservable = new BABYLON.Observable();
  56979. /**
  56980. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56981. */
  56982. this.updateSpeed = 0.01;
  56983. /**
  56984. * The amount of time the particle system is running (depends of the overall update speed).
  56985. */
  56986. this.targetStopDuration = 0;
  56987. /**
  56988. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56989. */
  56990. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56991. /**
  56992. * Minimum life time of emitting particles.
  56993. */
  56994. this.minLifeTime = 1;
  56995. /**
  56996. * Maximum life time of emitting particles.
  56997. */
  56998. this.maxLifeTime = 1;
  56999. /**
  57000. * Minimum Size of emitting particles.
  57001. */
  57002. this.minSize = 1;
  57003. /**
  57004. * Maximum Size of emitting particles.
  57005. */
  57006. this.maxSize = 1;
  57007. /**
  57008. * Minimum scale of emitting particles on X axis.
  57009. */
  57010. this.minScaleX = 1;
  57011. /**
  57012. * Maximum scale of emitting particles on X axis.
  57013. */
  57014. this.maxScaleX = 1;
  57015. /**
  57016. * Minimum scale of emitting particles on Y axis.
  57017. */
  57018. this.minScaleY = 1;
  57019. /**
  57020. * Maximum scale of emitting particles on Y axis.
  57021. */
  57022. this.maxScaleY = 1;
  57023. /**
  57024. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57025. */
  57026. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57027. /**
  57028. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57029. */
  57030. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57031. /**
  57032. * Color the particle will have at the end of its lifetime.
  57033. */
  57034. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57035. /**
  57036. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57037. */
  57038. this.emitRate = 100;
  57039. /**
  57040. * You can use gravity if you want to give an orientation to your particles.
  57041. */
  57042. this.gravity = BABYLON.Vector3.Zero();
  57043. /**
  57044. * Minimum power of emitting particles.
  57045. */
  57046. this.minEmitPower = 1;
  57047. /**
  57048. * Maximum power of emitting particles.
  57049. */
  57050. this.maxEmitPower = 1;
  57051. /**
  57052. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57053. */
  57054. this.minAngularSpeed = 0;
  57055. /**
  57056. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57057. */
  57058. this.maxAngularSpeed = 0;
  57059. /**
  57060. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57061. * to override the particles.
  57062. */
  57063. this.forceDepthWrite = false;
  57064. this._preWarmDone = false;
  57065. /** 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 */
  57066. this.preWarmCycles = 0;
  57067. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57068. this.preWarmStepOffset = 1;
  57069. /**
  57070. * Gets or sets the minimal initial rotation in radians.
  57071. */
  57072. this.minInitialRotation = 0;
  57073. /**
  57074. * Gets or sets the maximal initial rotation in radians.
  57075. */
  57076. this.maxInitialRotation = 0;
  57077. /**
  57078. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  57079. */
  57080. this.spriteCellChangeSpeed = 1;
  57081. /**
  57082. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57083. */
  57084. this.startSpriteCellID = 0;
  57085. /**
  57086. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57087. */
  57088. this.endSpriteCellID = 0;
  57089. /**
  57090. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57091. */
  57092. this.spriteCellWidth = 0;
  57093. /**
  57094. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57095. */
  57096. this.spriteCellHeight = 0;
  57097. this._isBillboardBased = true;
  57098. this._colorGradients = null;
  57099. this._sizeGradients = null;
  57100. this.id = name;
  57101. this.name = name;
  57102. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57103. this._engine = this._scene.getEngine();
  57104. if (!options.randomTextureSize) {
  57105. delete options.randomTextureSize;
  57106. }
  57107. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57108. var optionsAsNumber = options;
  57109. if (isFinite(optionsAsNumber)) {
  57110. fullOptions.capacity = optionsAsNumber;
  57111. }
  57112. this._capacity = fullOptions.capacity;
  57113. this._activeCount = fullOptions.capacity;
  57114. this._currentActiveCount = 0;
  57115. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57116. this._scene.particleSystems.push(this);
  57117. this._updateEffectOptions = {
  57118. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57119. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57120. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57121. "angleRange", "radiusRange", "cellInfos"],
  57122. uniformBuffersNames: [],
  57123. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  57124. defines: "",
  57125. fallbacks: null,
  57126. onCompiled: null,
  57127. onError: null,
  57128. indexParameters: null,
  57129. maxSimultaneousLights: 0,
  57130. transformFeedbackVaryings: []
  57131. };
  57132. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57133. // Random data
  57134. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57135. var d = [];
  57136. for (var i = 0; i < maxTextureSize; ++i) {
  57137. d.push(Math.random());
  57138. d.push(Math.random());
  57139. d.push(Math.random());
  57140. d.push(Math.random());
  57141. }
  57142. 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);
  57143. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57144. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57145. d = [];
  57146. for (var i = 0; i < maxTextureSize; ++i) {
  57147. d.push(Math.random());
  57148. d.push(Math.random());
  57149. d.push(Math.random());
  57150. d.push(Math.random());
  57151. }
  57152. 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);
  57153. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57154. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57155. this._randomTextureSize = maxTextureSize;
  57156. }
  57157. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57158. /**
  57159. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57160. */
  57161. get: function () {
  57162. if (!BABYLON.Engine.LastCreatedEngine) {
  57163. return false;
  57164. }
  57165. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57166. },
  57167. enumerable: true,
  57168. configurable: true
  57169. });
  57170. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57171. /**
  57172. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57173. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57174. */
  57175. get: function () {
  57176. if (this.particleEmitterType.direction1) {
  57177. return this.particleEmitterType.direction1;
  57178. }
  57179. return BABYLON.Vector3.Zero();
  57180. },
  57181. set: function (value) {
  57182. if (this.particleEmitterType.direction1) {
  57183. this.particleEmitterType.direction1 = value;
  57184. }
  57185. },
  57186. enumerable: true,
  57187. configurable: true
  57188. });
  57189. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57190. /**
  57191. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57192. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57193. */
  57194. get: function () {
  57195. if (this.particleEmitterType.direction2) {
  57196. return this.particleEmitterType.direction2;
  57197. }
  57198. return BABYLON.Vector3.Zero();
  57199. },
  57200. set: function (value) {
  57201. if (this.particleEmitterType.direction2) {
  57202. this.particleEmitterType.direction2 = value;
  57203. }
  57204. },
  57205. enumerable: true,
  57206. configurable: true
  57207. });
  57208. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57209. /**
  57210. * 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.
  57211. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57212. */
  57213. get: function () {
  57214. if (this.particleEmitterType.minEmitBox) {
  57215. return this.particleEmitterType.minEmitBox;
  57216. }
  57217. return BABYLON.Vector3.Zero();
  57218. },
  57219. set: function (value) {
  57220. if (this.particleEmitterType.minEmitBox) {
  57221. this.particleEmitterType.minEmitBox = value;
  57222. }
  57223. },
  57224. enumerable: true,
  57225. configurable: true
  57226. });
  57227. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57228. /**
  57229. * 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.
  57230. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57231. */
  57232. get: function () {
  57233. if (this.particleEmitterType.maxEmitBox) {
  57234. return this.particleEmitterType.maxEmitBox;
  57235. }
  57236. return BABYLON.Vector3.Zero();
  57237. },
  57238. set: function (value) {
  57239. if (this.particleEmitterType.maxEmitBox) {
  57240. this.particleEmitterType.maxEmitBox = value;
  57241. }
  57242. },
  57243. enumerable: true,
  57244. configurable: true
  57245. });
  57246. /**
  57247. * Gets the maximum number of particles active at the same time.
  57248. * @returns The max number of active particles.
  57249. */
  57250. GPUParticleSystem.prototype.getCapacity = function () {
  57251. return this._capacity;
  57252. };
  57253. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57254. /**
  57255. * Gets or set the number of active particles
  57256. */
  57257. get: function () {
  57258. return this._activeCount;
  57259. },
  57260. set: function (value) {
  57261. this._activeCount = Math.min(value, this._capacity);
  57262. },
  57263. enumerable: true,
  57264. configurable: true
  57265. });
  57266. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57267. /**
  57268. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57269. */
  57270. get: function () {
  57271. return this._isAnimationSheetEnabled;
  57272. },
  57273. enumerable: true,
  57274. configurable: true
  57275. });
  57276. /**
  57277. * Is this system ready to be used/rendered
  57278. * @return true if the system is ready
  57279. */
  57280. GPUParticleSystem.prototype.isReady = function () {
  57281. if (!this._updateEffect) {
  57282. this._recreateUpdateEffect();
  57283. this._recreateRenderEffect();
  57284. return false;
  57285. }
  57286. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57287. return false;
  57288. }
  57289. return true;
  57290. };
  57291. /**
  57292. * Gets Wether the system has been started.
  57293. * @returns True if it has been started, otherwise false.
  57294. */
  57295. GPUParticleSystem.prototype.isStarted = function () {
  57296. return this._started;
  57297. };
  57298. /**
  57299. * Starts the particle system and begins to emit.
  57300. */
  57301. GPUParticleSystem.prototype.start = function () {
  57302. this._started = true;
  57303. this._stopped = false;
  57304. this._preWarmDone = false;
  57305. };
  57306. /**
  57307. * Stops the particle system.
  57308. */
  57309. GPUParticleSystem.prototype.stop = function () {
  57310. this._stopped = true;
  57311. };
  57312. /**
  57313. * Remove all active particles
  57314. */
  57315. GPUParticleSystem.prototype.reset = function () {
  57316. this._releaseBuffers();
  57317. this._releaseVAOs();
  57318. this._currentActiveCount = 0;
  57319. this._targetIndex = 0;
  57320. };
  57321. /**
  57322. * Returns the string "GPUParticleSystem"
  57323. * @returns a string containing the class name
  57324. */
  57325. GPUParticleSystem.prototype.getClassName = function () {
  57326. return "GPUParticleSystem";
  57327. };
  57328. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57329. /**
  57330. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57331. */
  57332. get: function () {
  57333. return this._isBillboardBased;
  57334. },
  57335. set: function (value) {
  57336. if (this._isBillboardBased === value) {
  57337. return;
  57338. }
  57339. this._isBillboardBased = value;
  57340. this._releaseBuffers();
  57341. },
  57342. enumerable: true,
  57343. configurable: true
  57344. });
  57345. /**
  57346. * Gets the current list of color gradients.
  57347. * You must use addColorGradient and removeColorGradient to udpate this list
  57348. * @returns the list of color gradients
  57349. */
  57350. GPUParticleSystem.prototype.getColorGradients = function () {
  57351. return this._colorGradients;
  57352. };
  57353. /**
  57354. * Gets the current list of size gradients.
  57355. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57356. * @returns the list of size gradients
  57357. */
  57358. GPUParticleSystem.prototype.getSizeGradients = function () {
  57359. return this._sizeGradients;
  57360. };
  57361. /**
  57362. * Adds a new color gradient
  57363. * @param gradient defines the gradient to use (between 0 and 1)
  57364. * @param color defines the color to affect to the specified gradient
  57365. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57366. */
  57367. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57368. if (!this._colorGradients) {
  57369. this._colorGradients = [];
  57370. }
  57371. var colorGradient = new BABYLON.ColorGradient();
  57372. colorGradient.gradient = gradient;
  57373. colorGradient.color1 = color1;
  57374. this._colorGradients.push(colorGradient);
  57375. this._colorGradients.sort(function (a, b) {
  57376. if (a.gradient < b.gradient) {
  57377. return -1;
  57378. }
  57379. else if (a.gradient > b.gradient) {
  57380. return 1;
  57381. }
  57382. return 0;
  57383. });
  57384. if (this._colorGradientsTexture) {
  57385. this._colorGradientsTexture.dispose();
  57386. this._colorGradientsTexture = null;
  57387. }
  57388. this._releaseBuffers();
  57389. return this;
  57390. };
  57391. /**
  57392. * Remove a specific color gradient
  57393. * @param gradient defines the gradient to remove
  57394. */
  57395. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57396. if (!this._colorGradients) {
  57397. return this;
  57398. }
  57399. var index = 0;
  57400. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57401. var colorGradient = _a[_i];
  57402. if (colorGradient.gradient === gradient) {
  57403. this._colorGradients.splice(index, 1);
  57404. break;
  57405. }
  57406. index++;
  57407. }
  57408. if (this._colorGradientsTexture) {
  57409. this._colorGradientsTexture.dispose();
  57410. this._colorGradientsTexture = null;
  57411. }
  57412. this._releaseBuffers();
  57413. return this;
  57414. };
  57415. /**
  57416. * Adds a new size gradient
  57417. * @param gradient defines the gradient to use (between 0 and 1)
  57418. * @param factor defines the size factor to affect to the specified gradient
  57419. */
  57420. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57421. if (!this._sizeGradients) {
  57422. this._sizeGradients = [];
  57423. }
  57424. var sizeGradient = new BABYLON.FactorGradient();
  57425. sizeGradient.gradient = gradient;
  57426. sizeGradient.factor1 = factor;
  57427. this._sizeGradients.push(sizeGradient);
  57428. this._sizeGradients.sort(function (a, b) {
  57429. if (a.gradient < b.gradient) {
  57430. return -1;
  57431. }
  57432. else if (a.gradient > b.gradient) {
  57433. return 1;
  57434. }
  57435. return 0;
  57436. });
  57437. if (this._sizeGradientsTexture) {
  57438. this._sizeGradientsTexture.dispose();
  57439. this._sizeGradientsTexture = null;
  57440. }
  57441. this._releaseBuffers();
  57442. return this;
  57443. };
  57444. /**
  57445. * Remove a specific size gradient
  57446. * @param gradient defines the gradient to remove
  57447. */
  57448. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57449. if (!this._sizeGradients) {
  57450. return this;
  57451. }
  57452. var index = 0;
  57453. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57454. var sizeGradient = _a[_i];
  57455. if (sizeGradient.gradient === gradient) {
  57456. this._sizeGradients.splice(index, 1);
  57457. break;
  57458. }
  57459. index++;
  57460. }
  57461. if (this._sizeGradientsTexture) {
  57462. this._sizeGradientsTexture.dispose();
  57463. this._sizeGradientsTexture = null;
  57464. }
  57465. this._releaseBuffers();
  57466. return this;
  57467. };
  57468. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57469. var updateVertexBuffers = {};
  57470. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57471. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57472. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57473. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57474. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57475. var offset = 12;
  57476. if (!this._colorGradientsTexture) {
  57477. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57478. offset += 4;
  57479. }
  57480. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57481. offset += 3;
  57482. if (!this._isBillboardBased) {
  57483. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57484. offset += 3;
  57485. }
  57486. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57487. offset += 2;
  57488. if (this._isAnimationSheetEnabled) {
  57489. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57490. offset += 1;
  57491. }
  57492. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57493. this._engine.bindArrayBuffer(null);
  57494. return vao;
  57495. };
  57496. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57497. var renderVertexBuffers = {};
  57498. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57499. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57500. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57501. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57502. var offset = 12;
  57503. if (!this._colorGradientsTexture) {
  57504. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57505. offset += 4;
  57506. }
  57507. offset += 3; // Direction
  57508. if (!this._isBillboardBased) {
  57509. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57510. offset += 3;
  57511. }
  57512. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57513. offset += 2;
  57514. if (this._isAnimationSheetEnabled) {
  57515. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57516. offset += 1;
  57517. }
  57518. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57519. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57520. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57521. this._engine.bindArrayBuffer(null);
  57522. return vao;
  57523. };
  57524. GPUParticleSystem.prototype._initialize = function (force) {
  57525. if (force === void 0) { force = false; }
  57526. if (this._buffer0 && !force) {
  57527. return;
  57528. }
  57529. var engine = this._scene.getEngine();
  57530. var data = new Array();
  57531. if (!this.isBillboardBased) {
  57532. this._attributesStrideSize += 3;
  57533. }
  57534. if (this._colorGradientsTexture) {
  57535. this._attributesStrideSize -= 4;
  57536. }
  57537. if (this._isAnimationSheetEnabled) {
  57538. this._attributesStrideSize += 1;
  57539. }
  57540. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57541. // position
  57542. data.push(0.0);
  57543. data.push(0.0);
  57544. data.push(0.0);
  57545. // Age and life
  57546. data.push(0.0); // create the particle as a dead one to create a new one at start
  57547. data.push(0.0);
  57548. // Seed
  57549. data.push(Math.random());
  57550. data.push(Math.random());
  57551. data.push(Math.random());
  57552. data.push(Math.random());
  57553. // Size
  57554. data.push(0.0);
  57555. data.push(0.0);
  57556. data.push(0.0);
  57557. if (!this._colorGradientsTexture) {
  57558. // color
  57559. data.push(0.0);
  57560. data.push(0.0);
  57561. data.push(0.0);
  57562. data.push(0.0);
  57563. }
  57564. // direction
  57565. data.push(0.0);
  57566. data.push(0.0);
  57567. data.push(0.0);
  57568. if (!this.isBillboardBased) {
  57569. // initialDirection
  57570. data.push(0.0);
  57571. data.push(0.0);
  57572. data.push(0.0);
  57573. }
  57574. // angle
  57575. data.push(0.0);
  57576. data.push(0.0);
  57577. if (this._isAnimationSheetEnabled) {
  57578. data.push(0.0);
  57579. }
  57580. }
  57581. // Sprite data
  57582. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57583. -0.5, 0.5, 0, 1,
  57584. -0.5, -0.5, 0, 0,
  57585. 0.5, -0.5, 1, 0]);
  57586. // Buffers
  57587. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57588. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57589. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57590. // Update VAO
  57591. this._updateVAO = [];
  57592. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57593. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57594. // Render VAO
  57595. this._renderVAO = [];
  57596. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57597. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57598. // Links
  57599. this._sourceBuffer = this._buffer0;
  57600. this._targetBuffer = this._buffer1;
  57601. };
  57602. /** @hidden */
  57603. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57604. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57605. if (this._isBillboardBased) {
  57606. defines += "\n#define BILLBOARD";
  57607. }
  57608. if (this._colorGradientsTexture) {
  57609. defines += "\n#define COLORGRADIENTS";
  57610. }
  57611. if (this._sizeGradientsTexture) {
  57612. defines += "\n#define SIZEGRADIENTS";
  57613. }
  57614. if (this.isAnimationSheetEnabled) {
  57615. defines += "\n#define ANIMATESHEET";
  57616. }
  57617. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57618. return;
  57619. }
  57620. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57621. if (!this._colorGradientsTexture) {
  57622. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57623. }
  57624. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57625. if (!this._isBillboardBased) {
  57626. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57627. }
  57628. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57629. if (this.isAnimationSheetEnabled) {
  57630. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57631. }
  57632. this._updateEffectOptions.defines = defines;
  57633. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57634. };
  57635. /** @hidden */
  57636. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57637. var defines = "";
  57638. if (this._scene.clipPlane) {
  57639. defines = "\n#define CLIPPLANE";
  57640. }
  57641. if (this._isBillboardBased) {
  57642. defines += "\n#define BILLBOARD";
  57643. }
  57644. if (this._colorGradientsTexture) {
  57645. defines += "\n#define COLORGRADIENTS";
  57646. }
  57647. if (this.isAnimationSheetEnabled) {
  57648. defines += "\n#define ANIMATESHEET";
  57649. }
  57650. if (this._renderEffect && this._renderEffect.defines === defines) {
  57651. return;
  57652. }
  57653. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57654. };
  57655. /**
  57656. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57657. * @param preWarm defines if we are in the pre-warmimg phase
  57658. */
  57659. GPUParticleSystem.prototype.animate = function (preWarm) {
  57660. if (preWarm === void 0) { preWarm = false; }
  57661. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57662. this._actualFrame += this._timeDelta;
  57663. if (!this._stopped) {
  57664. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57665. this.stop();
  57666. }
  57667. }
  57668. };
  57669. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57670. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57671. return;
  57672. }
  57673. var textureWidth = 256;
  57674. var data = new Float32Array(textureWidth);
  57675. for (var x = 0; x < textureWidth; x++) {
  57676. var ratio = x / textureWidth;
  57677. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57678. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57679. });
  57680. }
  57681. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57682. };
  57683. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57684. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57685. return;
  57686. }
  57687. var textureWidth = 256;
  57688. var data = new Uint8Array(textureWidth * 4);
  57689. var tmpColor = BABYLON.Tmp.Color4[0];
  57690. for (var x = 0; x < textureWidth; x++) {
  57691. var ratio = x / textureWidth;
  57692. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57693. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57694. data[x * 4] = tmpColor.r * 255;
  57695. data[x * 4 + 1] = tmpColor.g * 255;
  57696. data[x * 4 + 2] = tmpColor.b * 255;
  57697. data[x * 4 + 3] = tmpColor.a * 255;
  57698. });
  57699. }
  57700. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57701. };
  57702. /**
  57703. * Renders the particle system in its current state
  57704. * @param preWarm defines if the system should only update the particles but not render them
  57705. * @returns the current number of particles
  57706. */
  57707. GPUParticleSystem.prototype.render = function (preWarm) {
  57708. if (preWarm === void 0) { preWarm = false; }
  57709. if (!this._started) {
  57710. return 0;
  57711. }
  57712. this._createColorGradientTexture();
  57713. this._createSizeGradientTexture();
  57714. this._recreateUpdateEffect();
  57715. this._recreateRenderEffect();
  57716. if (!this.isReady()) {
  57717. return 0;
  57718. }
  57719. if (!preWarm) {
  57720. if (!this._preWarmDone && this.preWarmCycles) {
  57721. for (var index = 0; index < this.preWarmCycles; index++) {
  57722. this.animate(true);
  57723. this.render(true);
  57724. }
  57725. this._preWarmDone = true;
  57726. }
  57727. if (this._currentRenderId === this._scene.getRenderId()) {
  57728. return 0;
  57729. }
  57730. this._currentRenderId = this._scene.getRenderId();
  57731. }
  57732. // Get everything ready to render
  57733. this._initialize();
  57734. this._accumulatedCount += this.emitRate * this._timeDelta;
  57735. if (this._accumulatedCount > 1) {
  57736. var intPart = this._accumulatedCount | 0;
  57737. this._accumulatedCount -= intPart;
  57738. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57739. }
  57740. if (!this._currentActiveCount) {
  57741. return 0;
  57742. }
  57743. // Enable update effect
  57744. this._engine.enableEffect(this._updateEffect);
  57745. this._engine.setState(false);
  57746. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57747. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57748. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57749. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57750. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57751. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57752. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57753. if (!this._colorGradientsTexture) {
  57754. this._updateEffect.setDirectColor4("color1", this.color1);
  57755. this._updateEffect.setDirectColor4("color2", this.color2);
  57756. }
  57757. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57758. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57759. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57760. this._updateEffect.setVector3("gravity", this.gravity);
  57761. if (this._sizeGradientsTexture) {
  57762. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57763. }
  57764. if (this.particleEmitterType) {
  57765. this.particleEmitterType.applyToShader(this._updateEffect);
  57766. }
  57767. if (this._isAnimationSheetEnabled) {
  57768. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  57769. }
  57770. var emitterWM;
  57771. if (this.emitter.position) {
  57772. var emitterMesh = this.emitter;
  57773. emitterWM = emitterMesh.getWorldMatrix();
  57774. }
  57775. else {
  57776. var emitterPosition = this.emitter;
  57777. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57778. }
  57779. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57780. // Bind source VAO
  57781. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57782. // Update
  57783. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57784. this._engine.setRasterizerState(false);
  57785. this._engine.beginTransformFeedback();
  57786. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57787. this._engine.endTransformFeedback();
  57788. this._engine.setRasterizerState(true);
  57789. this._engine.bindTransformFeedbackBuffer(null);
  57790. if (!preWarm) {
  57791. // Enable render effect
  57792. this._engine.enableEffect(this._renderEffect);
  57793. var viewMatrix = this._scene.getViewMatrix();
  57794. this._renderEffect.setMatrix("view", viewMatrix);
  57795. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57796. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57797. if (this._colorGradientsTexture) {
  57798. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57799. }
  57800. else {
  57801. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57802. }
  57803. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57804. var baseSize = this.particleTexture.getBaseSize();
  57805. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57806. }
  57807. if (this._scene.clipPlane) {
  57808. var clipPlane = this._scene.clipPlane;
  57809. var invView = viewMatrix.clone();
  57810. invView.invert();
  57811. this._renderEffect.setMatrix("invView", invView);
  57812. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57813. }
  57814. // Draw order
  57815. switch (this.blendMode) {
  57816. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57817. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57818. break;
  57819. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57820. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57821. break;
  57822. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57823. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57824. break;
  57825. }
  57826. if (this.forceDepthWrite) {
  57827. this._engine.setDepthWrite(true);
  57828. }
  57829. // Bind source VAO
  57830. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57831. // Render
  57832. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57833. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57834. }
  57835. // Switch VAOs
  57836. this._targetIndex++;
  57837. if (this._targetIndex === 2) {
  57838. this._targetIndex = 0;
  57839. }
  57840. // Switch buffers
  57841. var tmpBuffer = this._sourceBuffer;
  57842. this._sourceBuffer = this._targetBuffer;
  57843. this._targetBuffer = tmpBuffer;
  57844. return this._currentActiveCount;
  57845. };
  57846. /**
  57847. * Rebuilds the particle system
  57848. */
  57849. GPUParticleSystem.prototype.rebuild = function () {
  57850. this._initialize(true);
  57851. };
  57852. GPUParticleSystem.prototype._releaseBuffers = function () {
  57853. if (this._buffer0) {
  57854. this._buffer0.dispose();
  57855. this._buffer0 = null;
  57856. }
  57857. if (this._buffer1) {
  57858. this._buffer1.dispose();
  57859. this._buffer1 = null;
  57860. }
  57861. if (this._spriteBuffer) {
  57862. this._spriteBuffer.dispose();
  57863. this._spriteBuffer = null;
  57864. }
  57865. };
  57866. GPUParticleSystem.prototype._releaseVAOs = function () {
  57867. if (!this._updateVAO) {
  57868. return;
  57869. }
  57870. for (var index = 0; index < this._updateVAO.length; index++) {
  57871. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57872. }
  57873. this._updateVAO = [];
  57874. for (var index = 0; index < this._renderVAO.length; index++) {
  57875. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57876. }
  57877. this._renderVAO = [];
  57878. };
  57879. /**
  57880. * Disposes the particle system and free the associated resources
  57881. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57882. */
  57883. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57884. if (disposeTexture === void 0) { disposeTexture = true; }
  57885. var index = this._scene.particleSystems.indexOf(this);
  57886. if (index > -1) {
  57887. this._scene.particleSystems.splice(index, 1);
  57888. }
  57889. this._releaseBuffers();
  57890. this._releaseVAOs();
  57891. if (this._colorGradientsTexture) {
  57892. this._colorGradientsTexture.dispose();
  57893. this._colorGradientsTexture = null;
  57894. }
  57895. if (this._sizeGradientsTexture) {
  57896. this._sizeGradientsTexture.dispose();
  57897. this._sizeGradientsTexture = null;
  57898. }
  57899. if (this._randomTexture) {
  57900. this._randomTexture.dispose();
  57901. this._randomTexture = null;
  57902. }
  57903. if (this._randomTexture2) {
  57904. this._randomTexture2.dispose();
  57905. this._randomTexture2 = null;
  57906. }
  57907. if (disposeTexture && this.particleTexture) {
  57908. this.particleTexture.dispose();
  57909. this.particleTexture = null;
  57910. }
  57911. // Callback
  57912. this.onDisposeObservable.notifyObservers(this);
  57913. this.onDisposeObservable.clear();
  57914. };
  57915. /**
  57916. * Clones the particle system.
  57917. * @param name The name of the cloned object
  57918. * @param newEmitter The new emitter to use
  57919. * @returns the cloned particle system
  57920. */
  57921. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57922. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57923. BABYLON.Tools.DeepCopy(this, result);
  57924. if (newEmitter === undefined) {
  57925. newEmitter = this.emitter;
  57926. }
  57927. result.emitter = newEmitter;
  57928. if (this.particleTexture) {
  57929. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57930. }
  57931. return result;
  57932. };
  57933. /**
  57934. * Serializes the particle system to a JSON object.
  57935. * @returns the JSON object
  57936. */
  57937. GPUParticleSystem.prototype.serialize = function () {
  57938. var serializationObject = {};
  57939. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  57940. serializationObject.activeParticleCount = this.activeParticleCount;
  57941. return serializationObject;
  57942. };
  57943. /**
  57944. * Parses a JSON object to create a GPU particle system.
  57945. * @param parsedParticleSystem The JSON object to parse
  57946. * @param scene The scene to create the particle system in
  57947. * @param rootUrl The root url to use to load external dependencies like texture
  57948. * @returns the parsed GPU particle system
  57949. */
  57950. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57951. var name = parsedParticleSystem.name;
  57952. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57953. if (parsedParticleSystem.activeParticleCount) {
  57954. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57955. }
  57956. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  57957. return particleSystem;
  57958. };
  57959. return GPUParticleSystem;
  57960. }());
  57961. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57962. })(BABYLON || (BABYLON = {}));
  57963. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57964. var BABYLON;
  57965. (function (BABYLON) {
  57966. /**
  57967. * Represents one particle of a solid particle system.
  57968. */
  57969. var SolidParticle = /** @class */ (function () {
  57970. /**
  57971. * Creates a Solid Particle object.
  57972. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57973. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57974. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57975. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57976. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57977. * @param shapeId (integer) is the model shape identifier in the SPS.
  57978. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57979. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57980. */
  57981. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57982. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57983. /**
  57984. * particle global index
  57985. */
  57986. this.idx = 0;
  57987. /**
  57988. * The color of the particle
  57989. */
  57990. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57991. /**
  57992. * The world space position of the particle.
  57993. */
  57994. this.position = BABYLON.Vector3.Zero();
  57995. /**
  57996. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57997. */
  57998. this.rotation = BABYLON.Vector3.Zero();
  57999. /**
  58000. * The scaling of the particle.
  58001. */
  58002. this.scaling = BABYLON.Vector3.One();
  58003. /**
  58004. * The uvs of the particle.
  58005. */
  58006. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58007. /**
  58008. * The current speed of the particle.
  58009. */
  58010. this.velocity = BABYLON.Vector3.Zero();
  58011. /**
  58012. * The pivot point in the particle local space.
  58013. */
  58014. this.pivot = BABYLON.Vector3.Zero();
  58015. /**
  58016. * Must the particle be translated from its pivot point in its local space ?
  58017. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58018. * Default : false
  58019. */
  58020. this.translateFromPivot = false;
  58021. /**
  58022. * Is the particle active or not ?
  58023. */
  58024. this.alive = true;
  58025. /**
  58026. * Is the particle visible or not ?
  58027. */
  58028. this.isVisible = true;
  58029. /**
  58030. * Index of this particle in the global "positions" array (Internal use)
  58031. */
  58032. this._pos = 0;
  58033. /**
  58034. * Index of this particle in the global "indices" array (Internal use)
  58035. */
  58036. this._ind = 0;
  58037. /**
  58038. * ModelShape id of this particle
  58039. */
  58040. this.shapeId = 0;
  58041. /**
  58042. * Index of the particle in its shape id (Internal use)
  58043. */
  58044. this.idxInShape = 0;
  58045. /**
  58046. * Still set as invisible in order to skip useless computations (Internal use)
  58047. */
  58048. this._stillInvisible = false;
  58049. /**
  58050. * Last computed particle rotation matrix
  58051. */
  58052. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58053. /**
  58054. * Parent particle Id, if any.
  58055. * Default null.
  58056. */
  58057. this.parentId = null;
  58058. /**
  58059. * Internal global position in the SPS.
  58060. */
  58061. this._globalPosition = BABYLON.Vector3.Zero();
  58062. this.idx = particleIndex;
  58063. this._pos = positionIndex;
  58064. this._ind = indiceIndex;
  58065. this._model = model;
  58066. this.shapeId = shapeId;
  58067. this.idxInShape = idxInShape;
  58068. this._sps = sps;
  58069. if (modelBoundingInfo) {
  58070. this._modelBoundingInfo = modelBoundingInfo;
  58071. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58072. }
  58073. }
  58074. Object.defineProperty(SolidParticle.prototype, "scale", {
  58075. /**
  58076. * Legacy support, changed scale to scaling
  58077. */
  58078. get: function () {
  58079. return this.scaling;
  58080. },
  58081. /**
  58082. * Legacy support, changed scale to scaling
  58083. */
  58084. set: function (scale) {
  58085. this.scaling = scale;
  58086. },
  58087. enumerable: true,
  58088. configurable: true
  58089. });
  58090. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58091. /**
  58092. * Legacy support, changed quaternion to rotationQuaternion
  58093. */
  58094. get: function () {
  58095. return this.rotationQuaternion;
  58096. },
  58097. /**
  58098. * Legacy support, changed quaternion to rotationQuaternion
  58099. */
  58100. set: function (q) {
  58101. this.rotationQuaternion = q;
  58102. },
  58103. enumerable: true,
  58104. configurable: true
  58105. });
  58106. /**
  58107. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58108. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58109. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58110. * @returns true if it intersects
  58111. */
  58112. SolidParticle.prototype.intersectsMesh = function (target) {
  58113. if (!this._boundingInfo || !target._boundingInfo) {
  58114. return false;
  58115. }
  58116. if (this._sps._bSphereOnly) {
  58117. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58118. }
  58119. return this._boundingInfo.intersects(target._boundingInfo, false);
  58120. };
  58121. return SolidParticle;
  58122. }());
  58123. BABYLON.SolidParticle = SolidParticle;
  58124. /**
  58125. * Represents the shape of the model used by one particle of a solid particle system.
  58126. * SPS internal tool, don't use it manually.
  58127. */
  58128. var ModelShape = /** @class */ (function () {
  58129. /**
  58130. * 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.
  58131. * SPS internal tool, don't use it manually.
  58132. * @hidden
  58133. */
  58134. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58135. /**
  58136. * length of the shape in the model indices array (internal use)
  58137. */
  58138. this._indicesLength = 0;
  58139. this.shapeID = id;
  58140. this._shape = shape;
  58141. this._indicesLength = indicesLength;
  58142. this._shapeUV = shapeUV;
  58143. this._positionFunction = posFunction;
  58144. this._vertexFunction = vtxFunction;
  58145. }
  58146. return ModelShape;
  58147. }());
  58148. BABYLON.ModelShape = ModelShape;
  58149. /**
  58150. * Represents a Depth Sorted Particle in the solid particle system.
  58151. */
  58152. var DepthSortedParticle = /** @class */ (function () {
  58153. function DepthSortedParticle() {
  58154. /**
  58155. * Index of the particle in the "indices" array
  58156. */
  58157. this.ind = 0;
  58158. /**
  58159. * Length of the particle shape in the "indices" array
  58160. */
  58161. this.indicesLength = 0;
  58162. /**
  58163. * Squared distance from the particle to the camera
  58164. */
  58165. this.sqDistance = 0.0;
  58166. }
  58167. return DepthSortedParticle;
  58168. }());
  58169. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58170. })(BABYLON || (BABYLON = {}));
  58171. //# sourceMappingURL=babylon.solidParticle.js.map
  58172. var BABYLON;
  58173. (function (BABYLON) {
  58174. /**
  58175. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58176. *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.
  58177. * The SPS is also a particle system. It provides some methods to manage the particles.
  58178. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58179. *
  58180. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58181. */
  58182. var SolidParticleSystem = /** @class */ (function () {
  58183. /**
  58184. * Creates a SPS (Solid Particle System) object.
  58185. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58186. * @param scene (Scene) is the scene in which the SPS is added.
  58187. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58188. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58189. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58190. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58191. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58192. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58193. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58194. */
  58195. function SolidParticleSystem(name, scene, options) {
  58196. /**
  58197. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58198. * Example : var p = SPS.particles[i];
  58199. */
  58200. this.particles = new Array();
  58201. /**
  58202. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58203. */
  58204. this.nbParticles = 0;
  58205. /**
  58206. * If the particles must ever face the camera (default false). Useful for planar particles.
  58207. */
  58208. this.billboard = false;
  58209. /**
  58210. * Recompute normals when adding a shape
  58211. */
  58212. this.recomputeNormals = true;
  58213. /**
  58214. * This a counter ofr your own usage. It's not set by any SPS functions.
  58215. */
  58216. this.counter = 0;
  58217. /**
  58218. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58219. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58220. */
  58221. this.vars = {};
  58222. /**
  58223. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58224. */
  58225. this._bSphereOnly = false;
  58226. /**
  58227. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58228. */
  58229. this._bSphereRadiusFactor = 1.0;
  58230. this._positions = new Array();
  58231. this._indices = new Array();
  58232. this._normals = new Array();
  58233. this._colors = new Array();
  58234. this._uvs = new Array();
  58235. this._index = 0; // indices index
  58236. this._updatable = true;
  58237. this._pickable = false;
  58238. this._isVisibilityBoxLocked = false;
  58239. this._alwaysVisible = false;
  58240. this._depthSort = false;
  58241. this._shapeCounter = 0;
  58242. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58243. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58244. this._computeParticleColor = true;
  58245. this._computeParticleTexture = true;
  58246. this._computeParticleRotation = true;
  58247. this._computeParticleVertex = false;
  58248. this._computeBoundingBox = false;
  58249. this._depthSortParticles = true;
  58250. this._cam_axisZ = BABYLON.Vector3.Zero();
  58251. this._cam_axisY = BABYLON.Vector3.Zero();
  58252. this._cam_axisX = BABYLON.Vector3.Zero();
  58253. this._axisZ = BABYLON.Axis.Z;
  58254. this._camDir = BABYLON.Vector3.Zero();
  58255. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58256. this._rotMatrix = new BABYLON.Matrix();
  58257. this._invertMatrix = new BABYLON.Matrix();
  58258. this._rotated = BABYLON.Vector3.Zero();
  58259. this._quaternion = new BABYLON.Quaternion();
  58260. this._vertex = BABYLON.Vector3.Zero();
  58261. this._normal = BABYLON.Vector3.Zero();
  58262. this._yaw = 0.0;
  58263. this._pitch = 0.0;
  58264. this._roll = 0.0;
  58265. this._halfroll = 0.0;
  58266. this._halfpitch = 0.0;
  58267. this._halfyaw = 0.0;
  58268. this._sinRoll = 0.0;
  58269. this._cosRoll = 0.0;
  58270. this._sinPitch = 0.0;
  58271. this._cosPitch = 0.0;
  58272. this._sinYaw = 0.0;
  58273. this._cosYaw = 0.0;
  58274. this._mustUnrotateFixedNormals = false;
  58275. this._minimum = BABYLON.Vector3.Zero();
  58276. this._maximum = BABYLON.Vector3.Zero();
  58277. this._minBbox = BABYLON.Vector3.Zero();
  58278. this._maxBbox = BABYLON.Vector3.Zero();
  58279. this._particlesIntersect = false;
  58280. this._depthSortFunction = function (p1, p2) {
  58281. return (p2.sqDistance - p1.sqDistance);
  58282. };
  58283. this._needs32Bits = false;
  58284. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58285. this._scaledPivot = BABYLON.Vector3.Zero();
  58286. this._particleHasParent = false;
  58287. this.name = name;
  58288. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58289. this._camera = scene.activeCamera;
  58290. this._pickable = options ? options.isPickable : false;
  58291. this._depthSort = options ? options.enableDepthSort : false;
  58292. this._particlesIntersect = options ? options.particleIntersection : false;
  58293. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58294. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58295. if (options && options.updatable !== undefined) {
  58296. this._updatable = options.updatable;
  58297. }
  58298. else {
  58299. this._updatable = true;
  58300. }
  58301. if (this._pickable) {
  58302. this.pickedParticles = [];
  58303. }
  58304. if (this._depthSort) {
  58305. this.depthSortedParticles = [];
  58306. }
  58307. }
  58308. /**
  58309. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58310. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58311. * @returns the created mesh
  58312. */
  58313. SolidParticleSystem.prototype.buildMesh = function () {
  58314. if (this.nbParticles === 0) {
  58315. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58316. this.addShape(triangle, 1);
  58317. triangle.dispose();
  58318. }
  58319. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58320. this._positions32 = new Float32Array(this._positions);
  58321. this._uvs32 = new Float32Array(this._uvs);
  58322. this._colors32 = new Float32Array(this._colors);
  58323. if (this.recomputeNormals) {
  58324. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58325. }
  58326. this._normals32 = new Float32Array(this._normals);
  58327. this._fixedNormal32 = new Float32Array(this._normals);
  58328. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58329. this._unrotateFixedNormals();
  58330. }
  58331. var vertexData = new BABYLON.VertexData();
  58332. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58333. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58334. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58335. if (this._uvs32.length > 0) {
  58336. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58337. }
  58338. if (this._colors32.length > 0) {
  58339. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58340. }
  58341. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58342. vertexData.applyToMesh(mesh, this._updatable);
  58343. this.mesh = mesh;
  58344. this.mesh.isPickable = this._pickable;
  58345. // free memory
  58346. if (!this._depthSort) {
  58347. this._indices = null;
  58348. }
  58349. this._positions = null;
  58350. this._normals = null;
  58351. this._uvs = null;
  58352. this._colors = null;
  58353. if (!this._updatable) {
  58354. this.particles.length = 0;
  58355. }
  58356. return mesh;
  58357. };
  58358. /**
  58359. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58360. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58361. * Thus the particles generated from `digest()` have their property `position` set yet.
  58362. * @param mesh ( Mesh ) is the mesh to be digested
  58363. * @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
  58364. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58365. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58366. * @returns the current SPS
  58367. */
  58368. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58369. var size = (options && options.facetNb) || 1;
  58370. var number = (options && options.number) || 0;
  58371. var delta = (options && options.delta) || 0;
  58372. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58373. var meshInd = mesh.getIndices();
  58374. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58375. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58376. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58377. var f = 0; // facet counter
  58378. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58379. // compute size from number
  58380. if (number) {
  58381. number = (number > totalFacets) ? totalFacets : number;
  58382. size = Math.round(totalFacets / number);
  58383. delta = 0;
  58384. }
  58385. else {
  58386. size = (size > totalFacets) ? totalFacets : size;
  58387. }
  58388. var facetPos = []; // submesh positions
  58389. var facetInd = []; // submesh indices
  58390. var facetUV = []; // submesh UV
  58391. var facetCol = []; // submesh colors
  58392. var barycenter = BABYLON.Vector3.Zero();
  58393. var sizeO = size;
  58394. while (f < totalFacets) {
  58395. size = sizeO + Math.floor((1 + delta) * Math.random());
  58396. if (f > totalFacets - size) {
  58397. size = totalFacets - f;
  58398. }
  58399. // reset temp arrays
  58400. facetPos.length = 0;
  58401. facetInd.length = 0;
  58402. facetUV.length = 0;
  58403. facetCol.length = 0;
  58404. // iterate over "size" facets
  58405. var fi = 0;
  58406. for (var j = f * 3; j < (f + size) * 3; j++) {
  58407. facetInd.push(fi);
  58408. var i = meshInd[j];
  58409. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58410. if (meshUV) {
  58411. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58412. }
  58413. if (meshCol) {
  58414. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58415. }
  58416. fi++;
  58417. }
  58418. // create a model shape for each single particle
  58419. var idx = this.nbParticles;
  58420. var shape = this._posToShape(facetPos);
  58421. var shapeUV = this._uvsToShapeUV(facetUV);
  58422. // compute the barycenter of the shape
  58423. var v;
  58424. for (v = 0; v < shape.length; v++) {
  58425. barycenter.addInPlace(shape[v]);
  58426. }
  58427. barycenter.scaleInPlace(1 / shape.length);
  58428. // shift the shape from its barycenter to the origin
  58429. for (v = 0; v < shape.length; v++) {
  58430. shape[v].subtractInPlace(barycenter);
  58431. }
  58432. var bInfo;
  58433. if (this._particlesIntersect) {
  58434. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58435. }
  58436. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58437. // add the particle in the SPS
  58438. var currentPos = this._positions.length;
  58439. var currentInd = this._indices.length;
  58440. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58441. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58442. // initialize the particle position
  58443. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58444. this._index += shape.length;
  58445. idx++;
  58446. this.nbParticles++;
  58447. this._shapeCounter++;
  58448. f += size;
  58449. }
  58450. return this;
  58451. };
  58452. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58453. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58454. var index = 0;
  58455. var idx = 0;
  58456. for (var p = 0; p < this.particles.length; p++) {
  58457. this._particle = this.particles[p];
  58458. this._shape = this._particle._model._shape;
  58459. if (this._particle.rotationQuaternion) {
  58460. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58461. }
  58462. else {
  58463. this._yaw = this._particle.rotation.y;
  58464. this._pitch = this._particle.rotation.x;
  58465. this._roll = this._particle.rotation.z;
  58466. this._quaternionRotationYPR();
  58467. }
  58468. this._quaternionToRotationMatrix();
  58469. this._rotMatrix.invertToRef(this._invertMatrix);
  58470. for (var pt = 0; pt < this._shape.length; pt++) {
  58471. idx = index + pt * 3;
  58472. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58473. this._fixedNormal32[idx] = this._normal.x;
  58474. this._fixedNormal32[idx + 1] = this._normal.y;
  58475. this._fixedNormal32[idx + 2] = this._normal.z;
  58476. }
  58477. index = idx + 3;
  58478. }
  58479. };
  58480. //reset copy
  58481. SolidParticleSystem.prototype._resetCopy = function () {
  58482. this._copy.position.x = 0;
  58483. this._copy.position.y = 0;
  58484. this._copy.position.z = 0;
  58485. this._copy.rotation.x = 0;
  58486. this._copy.rotation.y = 0;
  58487. this._copy.rotation.z = 0;
  58488. this._copy.rotationQuaternion = null;
  58489. this._copy.scaling.x = 1.0;
  58490. this._copy.scaling.y = 1.0;
  58491. this._copy.scaling.z = 1.0;
  58492. this._copy.uvs.x = 0;
  58493. this._copy.uvs.y = 0;
  58494. this._copy.uvs.z = 1.0;
  58495. this._copy.uvs.w = 1.0;
  58496. this._copy.color = null;
  58497. this._copy.translateFromPivot = false;
  58498. };
  58499. // _meshBuilder : inserts the shape model in the global SPS mesh
  58500. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58501. var i;
  58502. var u = 0;
  58503. var c = 0;
  58504. var n = 0;
  58505. this._resetCopy();
  58506. if (options && options.positionFunction) { // call to custom positionFunction
  58507. options.positionFunction(this._copy, idx, idxInShape);
  58508. this._mustUnrotateFixedNormals = true;
  58509. }
  58510. if (this._copy.rotationQuaternion) {
  58511. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58512. }
  58513. else {
  58514. this._yaw = this._copy.rotation.y;
  58515. this._pitch = this._copy.rotation.x;
  58516. this._roll = this._copy.rotation.z;
  58517. this._quaternionRotationYPR();
  58518. }
  58519. this._quaternionToRotationMatrix();
  58520. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58521. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58522. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58523. if (this._copy.translateFromPivot) {
  58524. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58525. }
  58526. else {
  58527. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58528. }
  58529. for (i = 0; i < shape.length; i++) {
  58530. this._vertex.x = shape[i].x;
  58531. this._vertex.y = shape[i].y;
  58532. this._vertex.z = shape[i].z;
  58533. if (options && options.vertexFunction) {
  58534. options.vertexFunction(this._copy, this._vertex, i);
  58535. }
  58536. this._vertex.x *= this._copy.scaling.x;
  58537. this._vertex.y *= this._copy.scaling.y;
  58538. this._vertex.z *= this._copy.scaling.z;
  58539. this._vertex.x -= this._scaledPivot.x;
  58540. this._vertex.y -= this._scaledPivot.y;
  58541. this._vertex.z -= this._scaledPivot.z;
  58542. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58543. this._rotated.addInPlace(this._pivotBackTranslation);
  58544. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58545. if (meshUV) {
  58546. 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);
  58547. u += 2;
  58548. }
  58549. if (this._copy.color) {
  58550. this._color = this._copy.color;
  58551. }
  58552. else if (meshCol && meshCol[c] !== undefined) {
  58553. this._color.r = meshCol[c];
  58554. this._color.g = meshCol[c + 1];
  58555. this._color.b = meshCol[c + 2];
  58556. this._color.a = meshCol[c + 3];
  58557. }
  58558. else {
  58559. this._color.r = 1.0;
  58560. this._color.g = 1.0;
  58561. this._color.b = 1.0;
  58562. this._color.a = 1.0;
  58563. }
  58564. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58565. c += 4;
  58566. if (!this.recomputeNormals && meshNor) {
  58567. this._normal.x = meshNor[n];
  58568. this._normal.y = meshNor[n + 1];
  58569. this._normal.z = meshNor[n + 2];
  58570. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58571. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58572. n += 3;
  58573. }
  58574. }
  58575. for (i = 0; i < meshInd.length; i++) {
  58576. var current_ind = p + meshInd[i];
  58577. indices.push(current_ind);
  58578. if (current_ind > 65535) {
  58579. this._needs32Bits = true;
  58580. }
  58581. }
  58582. if (this._pickable) {
  58583. var nbfaces = meshInd.length / 3;
  58584. for (i = 0; i < nbfaces; i++) {
  58585. this.pickedParticles.push({ idx: idx, faceId: i });
  58586. }
  58587. }
  58588. if (this._depthSort) {
  58589. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58590. }
  58591. return this._copy;
  58592. };
  58593. // returns a shape array from positions array
  58594. SolidParticleSystem.prototype._posToShape = function (positions) {
  58595. var shape = [];
  58596. for (var i = 0; i < positions.length; i += 3) {
  58597. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58598. }
  58599. return shape;
  58600. };
  58601. // returns a shapeUV array from a Vector4 uvs
  58602. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58603. var shapeUV = [];
  58604. if (uvs) {
  58605. for (var i = 0; i < uvs.length; i++)
  58606. shapeUV.push(uvs[i]);
  58607. }
  58608. return shapeUV;
  58609. };
  58610. // adds a new particle object in the particles array
  58611. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58612. if (bInfo === void 0) { bInfo = null; }
  58613. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58614. this.particles.push(sp);
  58615. return sp;
  58616. };
  58617. /**
  58618. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58619. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58620. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58621. * @param nb (positive integer) the number of particles to be created from this model
  58622. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58623. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58624. * @returns the number of shapes in the system
  58625. */
  58626. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58627. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58628. var meshInd = mesh.getIndices();
  58629. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58630. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58631. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58632. var bbInfo;
  58633. if (this._particlesIntersect) {
  58634. bbInfo = mesh.getBoundingInfo();
  58635. }
  58636. var shape = this._posToShape(meshPos);
  58637. var shapeUV = this._uvsToShapeUV(meshUV);
  58638. var posfunc = options ? options.positionFunction : null;
  58639. var vtxfunc = options ? options.vertexFunction : null;
  58640. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58641. // particles
  58642. var sp;
  58643. var currentCopy;
  58644. var idx = this.nbParticles;
  58645. for (var i = 0; i < nb; i++) {
  58646. var currentPos = this._positions.length;
  58647. var currentInd = this._indices.length;
  58648. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58649. if (this._updatable) {
  58650. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58651. sp.position.copyFrom(currentCopy.position);
  58652. sp.rotation.copyFrom(currentCopy.rotation);
  58653. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58654. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58655. }
  58656. if (currentCopy.color && sp.color) {
  58657. sp.color.copyFrom(currentCopy.color);
  58658. }
  58659. sp.scaling.copyFrom(currentCopy.scaling);
  58660. sp.uvs.copyFrom(currentCopy.uvs);
  58661. }
  58662. this._index += shape.length;
  58663. idx++;
  58664. }
  58665. this.nbParticles += nb;
  58666. this._shapeCounter++;
  58667. return this._shapeCounter - 1;
  58668. };
  58669. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58670. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58671. this._resetCopy();
  58672. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58673. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58674. }
  58675. if (this._copy.rotationQuaternion) {
  58676. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58677. }
  58678. else {
  58679. this._yaw = this._copy.rotation.y;
  58680. this._pitch = this._copy.rotation.x;
  58681. this._roll = this._copy.rotation.z;
  58682. this._quaternionRotationYPR();
  58683. }
  58684. this._quaternionToRotationMatrix();
  58685. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58686. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58687. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58688. if (this._copy.translateFromPivot) {
  58689. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58690. }
  58691. else {
  58692. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58693. }
  58694. this._shape = particle._model._shape;
  58695. for (var pt = 0; pt < this._shape.length; pt++) {
  58696. this._vertex.x = this._shape[pt].x;
  58697. this._vertex.y = this._shape[pt].y;
  58698. this._vertex.z = this._shape[pt].z;
  58699. if (particle._model._vertexFunction) {
  58700. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58701. }
  58702. this._vertex.x *= this._copy.scaling.x;
  58703. this._vertex.y *= this._copy.scaling.y;
  58704. this._vertex.z *= this._copy.scaling.z;
  58705. this._vertex.x -= this._scaledPivot.x;
  58706. this._vertex.y -= this._scaledPivot.y;
  58707. this._vertex.z -= this._scaledPivot.z;
  58708. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58709. this._rotated.addInPlace(this._pivotBackTranslation);
  58710. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58711. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58712. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58713. }
  58714. particle.position.x = 0.0;
  58715. particle.position.y = 0.0;
  58716. particle.position.z = 0.0;
  58717. particle.rotation.x = 0.0;
  58718. particle.rotation.y = 0.0;
  58719. particle.rotation.z = 0.0;
  58720. particle.rotationQuaternion = null;
  58721. particle.scaling.x = 1.0;
  58722. particle.scaling.y = 1.0;
  58723. particle.scaling.z = 1.0;
  58724. particle.uvs.x = 0.0;
  58725. particle.uvs.y = 0.0;
  58726. particle.uvs.z = 1.0;
  58727. particle.uvs.w = 1.0;
  58728. particle.pivot.x = 0.0;
  58729. particle.pivot.y = 0.0;
  58730. particle.pivot.z = 0.0;
  58731. particle.translateFromPivot = false;
  58732. particle.parentId = null;
  58733. };
  58734. /**
  58735. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58736. * @returns the SPS.
  58737. */
  58738. SolidParticleSystem.prototype.rebuildMesh = function () {
  58739. for (var p = 0; p < this.particles.length; p++) {
  58740. this._rebuildParticle(this.particles[p]);
  58741. }
  58742. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58743. return this;
  58744. };
  58745. /**
  58746. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58747. * This method calls `updateParticle()` for each particle of the SPS.
  58748. * For an animated SPS, it is usually called within the render loop.
  58749. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58750. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58751. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58752. * @returns the SPS.
  58753. */
  58754. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58755. if (start === void 0) { start = 0; }
  58756. if (end === void 0) { end = this.nbParticles - 1; }
  58757. if (update === void 0) { update = true; }
  58758. if (!this._updatable) {
  58759. return this;
  58760. }
  58761. // custom beforeUpdate
  58762. this.beforeUpdateParticles(start, end, update);
  58763. this._cam_axisX.x = 1.0;
  58764. this._cam_axisX.y = 0.0;
  58765. this._cam_axisX.z = 0.0;
  58766. this._cam_axisY.x = 0.0;
  58767. this._cam_axisY.y = 1.0;
  58768. this._cam_axisY.z = 0.0;
  58769. this._cam_axisZ.x = 0.0;
  58770. this._cam_axisZ.y = 0.0;
  58771. this._cam_axisZ.z = 1.0;
  58772. // cases when the World Matrix is to be computed first
  58773. if (this.billboard || this._depthSort) {
  58774. this.mesh.computeWorldMatrix(true);
  58775. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58776. }
  58777. // if the particles will always face the camera
  58778. if (this.billboard) {
  58779. // compute the camera position and un-rotate it by the current mesh rotation
  58780. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58781. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58782. this._cam_axisZ.normalize();
  58783. // same for camera up vector extracted from the cam view matrix
  58784. var view = this._camera.getViewMatrix(true);
  58785. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58786. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58787. this._cam_axisY.normalize();
  58788. this._cam_axisX.normalize();
  58789. }
  58790. // if depthSort, compute the camera global position in the mesh local system
  58791. if (this._depthSort) {
  58792. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58793. }
  58794. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58795. var idx = 0; // current position index in the global array positions32
  58796. var index = 0; // position start index in the global array positions32 of the current particle
  58797. var colidx = 0; // current color index in the global array colors32
  58798. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58799. var uvidx = 0; // current uv index in the global array uvs32
  58800. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58801. var pt = 0; // current index in the particle model shape
  58802. if (this.mesh.isFacetDataEnabled) {
  58803. this._computeBoundingBox = true;
  58804. }
  58805. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58806. if (this._computeBoundingBox) {
  58807. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58808. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58809. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58810. }
  58811. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58812. if (this.mesh._boundingInfo) {
  58813. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58814. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58815. }
  58816. }
  58817. }
  58818. // particle loop
  58819. index = this.particles[start]._pos;
  58820. var vpos = (index / 3) | 0;
  58821. colorIndex = vpos * 4;
  58822. uvIndex = vpos * 2;
  58823. for (var p = start; p <= end; p++) {
  58824. this._particle = this.particles[p];
  58825. this._shape = this._particle._model._shape;
  58826. this._shapeUV = this._particle._model._shapeUV;
  58827. // call to custom user function to update the particle properties
  58828. this.updateParticle(this._particle);
  58829. // camera-particle distance for depth sorting
  58830. if (this._depthSort && this._depthSortParticles) {
  58831. var dsp = this.depthSortedParticles[p];
  58832. dsp.ind = this._particle._ind;
  58833. dsp.indicesLength = this._particle._model._indicesLength;
  58834. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58835. }
  58836. // skip the computations for inactive or already invisible particles
  58837. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58838. // increment indexes for the next particle
  58839. pt = this._shape.length;
  58840. index += pt * 3;
  58841. colorIndex += pt * 4;
  58842. uvIndex += pt * 2;
  58843. continue;
  58844. }
  58845. if (this._particle.isVisible) {
  58846. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58847. this._particleHasParent = (this._particle.parentId !== null);
  58848. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58849. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58850. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58851. // particle rotation matrix
  58852. if (this.billboard) {
  58853. this._particle.rotation.x = 0.0;
  58854. this._particle.rotation.y = 0.0;
  58855. }
  58856. if (this._computeParticleRotation || this.billboard) {
  58857. if (this._particle.rotationQuaternion) {
  58858. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58859. }
  58860. else {
  58861. this._yaw = this._particle.rotation.y;
  58862. this._pitch = this._particle.rotation.x;
  58863. this._roll = this._particle.rotation.z;
  58864. this._quaternionRotationYPR();
  58865. }
  58866. this._quaternionToRotationMatrix();
  58867. }
  58868. if (this._particleHasParent) {
  58869. this._parent = this.particles[this._particle.parentId];
  58870. 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];
  58871. 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];
  58872. 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];
  58873. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58874. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58875. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58876. if (this._computeParticleRotation || this.billboard) {
  58877. 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];
  58878. 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];
  58879. 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];
  58880. 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];
  58881. 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];
  58882. 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];
  58883. 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];
  58884. 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];
  58885. 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];
  58886. }
  58887. }
  58888. else {
  58889. this._particle._globalPosition.x = this._particle.position.x;
  58890. this._particle._globalPosition.y = this._particle.position.y;
  58891. this._particle._globalPosition.z = this._particle.position.z;
  58892. if (this._computeParticleRotation || this.billboard) {
  58893. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58894. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58895. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58896. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58897. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58898. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58899. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58900. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58901. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58902. }
  58903. }
  58904. if (this._particle.translateFromPivot) {
  58905. this._pivotBackTranslation.x = 0.0;
  58906. this._pivotBackTranslation.y = 0.0;
  58907. this._pivotBackTranslation.z = 0.0;
  58908. }
  58909. else {
  58910. this._pivotBackTranslation.x = this._scaledPivot.x;
  58911. this._pivotBackTranslation.y = this._scaledPivot.y;
  58912. this._pivotBackTranslation.z = this._scaledPivot.z;
  58913. }
  58914. // particle vertex loop
  58915. for (pt = 0; pt < this._shape.length; pt++) {
  58916. idx = index + pt * 3;
  58917. colidx = colorIndex + pt * 4;
  58918. uvidx = uvIndex + pt * 2;
  58919. this._vertex.x = this._shape[pt].x;
  58920. this._vertex.y = this._shape[pt].y;
  58921. this._vertex.z = this._shape[pt].z;
  58922. if (this._computeParticleVertex) {
  58923. this.updateParticleVertex(this._particle, this._vertex, pt);
  58924. }
  58925. // positions
  58926. this._vertex.x *= this._particle.scaling.x;
  58927. this._vertex.y *= this._particle.scaling.y;
  58928. this._vertex.z *= this._particle.scaling.z;
  58929. this._vertex.x -= this._scaledPivot.x;
  58930. this._vertex.y -= this._scaledPivot.y;
  58931. this._vertex.z -= this._scaledPivot.z;
  58932. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58933. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58934. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58935. this._rotated.x += this._pivotBackTranslation.x;
  58936. this._rotated.y += this._pivotBackTranslation.y;
  58937. this._rotated.z += this._pivotBackTranslation.z;
  58938. 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;
  58939. 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;
  58940. 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;
  58941. if (this._computeBoundingBox) {
  58942. if (this._positions32[idx] < this._minimum.x) {
  58943. this._minimum.x = this._positions32[idx];
  58944. }
  58945. if (this._positions32[idx] > this._maximum.x) {
  58946. this._maximum.x = this._positions32[idx];
  58947. }
  58948. if (this._positions32[idx + 1] < this._minimum.y) {
  58949. this._minimum.y = this._positions32[idx + 1];
  58950. }
  58951. if (this._positions32[idx + 1] > this._maximum.y) {
  58952. this._maximum.y = this._positions32[idx + 1];
  58953. }
  58954. if (this._positions32[idx + 2] < this._minimum.z) {
  58955. this._minimum.z = this._positions32[idx + 2];
  58956. }
  58957. if (this._positions32[idx + 2] > this._maximum.z) {
  58958. this._maximum.z = this._positions32[idx + 2];
  58959. }
  58960. }
  58961. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58962. if (!this._computeParticleVertex) {
  58963. this._normal.x = this._fixedNormal32[idx];
  58964. this._normal.y = this._fixedNormal32[idx + 1];
  58965. this._normal.z = this._fixedNormal32[idx + 2];
  58966. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58967. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58968. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58969. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58970. 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;
  58971. 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;
  58972. }
  58973. if (this._computeParticleColor && this._particle.color) {
  58974. this._colors32[colidx] = this._particle.color.r;
  58975. this._colors32[colidx + 1] = this._particle.color.g;
  58976. this._colors32[colidx + 2] = this._particle.color.b;
  58977. this._colors32[colidx + 3] = this._particle.color.a;
  58978. }
  58979. if (this._computeParticleTexture) {
  58980. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58981. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58982. }
  58983. }
  58984. }
  58985. // particle just set invisible : scaled to zero and positioned at the origin
  58986. else {
  58987. this._particle._stillInvisible = true; // mark the particle as invisible
  58988. for (pt = 0; pt < this._shape.length; pt++) {
  58989. idx = index + pt * 3;
  58990. colidx = colorIndex + pt * 4;
  58991. uvidx = uvIndex + pt * 2;
  58992. this._positions32[idx] = 0.0;
  58993. this._positions32[idx + 1] = 0.0;
  58994. this._positions32[idx + 2] = 0.0;
  58995. this._normals32[idx] = 0.0;
  58996. this._normals32[idx + 1] = 0.0;
  58997. this._normals32[idx + 2] = 0.0;
  58998. if (this._computeParticleColor && this._particle.color) {
  58999. this._colors32[colidx] = this._particle.color.r;
  59000. this._colors32[colidx + 1] = this._particle.color.g;
  59001. this._colors32[colidx + 2] = this._particle.color.b;
  59002. this._colors32[colidx + 3] = this._particle.color.a;
  59003. }
  59004. if (this._computeParticleTexture) {
  59005. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59006. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59007. }
  59008. }
  59009. }
  59010. // if the particle intersections must be computed : update the bbInfo
  59011. if (this._particlesIntersect) {
  59012. var bInfo = this._particle._boundingInfo;
  59013. var bBox = bInfo.boundingBox;
  59014. var bSphere = bInfo.boundingSphere;
  59015. if (!this._bSphereOnly) {
  59016. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59017. for (var b = 0; b < bBox.vectors.length; b++) {
  59018. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59019. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59020. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59021. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59022. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59023. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59024. 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;
  59025. 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;
  59026. 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;
  59027. }
  59028. bBox._update(this.mesh._worldMatrix);
  59029. }
  59030. // place and scale the particle bouding sphere in the SPS local system, then update it
  59031. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59032. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59033. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59034. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59035. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59036. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59037. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59038. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59039. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59040. 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));
  59041. bSphere._update(this.mesh._worldMatrix);
  59042. }
  59043. // increment indexes for the next particle
  59044. index = idx + 3;
  59045. colorIndex = colidx + 4;
  59046. uvIndex = uvidx + 2;
  59047. }
  59048. // if the VBO must be updated
  59049. if (update) {
  59050. if (this._computeParticleColor) {
  59051. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59052. }
  59053. if (this._computeParticleTexture) {
  59054. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59055. }
  59056. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59057. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59058. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59059. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59060. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59061. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59062. for (var i = 0; i < this._normals32.length; i++) {
  59063. this._fixedNormal32[i] = this._normals32[i];
  59064. }
  59065. }
  59066. if (!this.mesh.areNormalsFrozen) {
  59067. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59068. }
  59069. }
  59070. if (this._depthSort && this._depthSortParticles) {
  59071. this.depthSortedParticles.sort(this._depthSortFunction);
  59072. var dspl = this.depthSortedParticles.length;
  59073. var sorted = 0;
  59074. var lind = 0;
  59075. var sind = 0;
  59076. var sid = 0;
  59077. for (sorted = 0; sorted < dspl; sorted++) {
  59078. lind = this.depthSortedParticles[sorted].indicesLength;
  59079. sind = this.depthSortedParticles[sorted].ind;
  59080. for (var i = 0; i < lind; i++) {
  59081. this._indices32[sid] = this._indices[sind + i];
  59082. sid++;
  59083. }
  59084. }
  59085. this.mesh.updateIndices(this._indices32);
  59086. }
  59087. }
  59088. if (this._computeBoundingBox) {
  59089. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59090. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59091. }
  59092. this.afterUpdateParticles(start, end, update);
  59093. return this;
  59094. };
  59095. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59096. this._halfroll = this._roll * 0.5;
  59097. this._halfpitch = this._pitch * 0.5;
  59098. this._halfyaw = this._yaw * 0.5;
  59099. this._sinRoll = Math.sin(this._halfroll);
  59100. this._cosRoll = Math.cos(this._halfroll);
  59101. this._sinPitch = Math.sin(this._halfpitch);
  59102. this._cosPitch = Math.cos(this._halfpitch);
  59103. this._sinYaw = Math.sin(this._halfyaw);
  59104. this._cosYaw = Math.cos(this._halfyaw);
  59105. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59106. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59107. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59108. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59109. };
  59110. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59111. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59112. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59113. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59114. this._rotMatrix.m[3] = 0;
  59115. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59116. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59117. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59118. this._rotMatrix.m[7] = 0;
  59119. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59120. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59121. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59122. this._rotMatrix.m[11] = 0;
  59123. this._rotMatrix.m[12] = 0;
  59124. this._rotMatrix.m[13] = 0;
  59125. this._rotMatrix.m[14] = 0;
  59126. this._rotMatrix.m[15] = 1.0;
  59127. };
  59128. /**
  59129. * Disposes the SPS.
  59130. */
  59131. SolidParticleSystem.prototype.dispose = function () {
  59132. this.mesh.dispose();
  59133. this.vars = null;
  59134. // drop references to internal big arrays for the GC
  59135. this._positions = null;
  59136. this._indices = null;
  59137. this._normals = null;
  59138. this._uvs = null;
  59139. this._colors = null;
  59140. this._indices32 = null;
  59141. this._positions32 = null;
  59142. this._normals32 = null;
  59143. this._fixedNormal32 = null;
  59144. this._uvs32 = null;
  59145. this._colors32 = null;
  59146. this.pickedParticles = null;
  59147. };
  59148. /**
  59149. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59150. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59151. * @returns the SPS.
  59152. */
  59153. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59154. if (!this._isVisibilityBoxLocked) {
  59155. this.mesh.refreshBoundingInfo();
  59156. }
  59157. return this;
  59158. };
  59159. /**
  59160. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59161. * @param size the size (float) of the visibility box
  59162. * note : this doesn't lock the SPS mesh bounding box.
  59163. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59164. */
  59165. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59166. var vis = size / 2;
  59167. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59168. };
  59169. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59170. /**
  59171. * Gets whether the SPS as always visible or not
  59172. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59173. */
  59174. get: function () {
  59175. return this._alwaysVisible;
  59176. },
  59177. /**
  59178. * Sets the SPS as always visible or not
  59179. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59180. */
  59181. set: function (val) {
  59182. this._alwaysVisible = val;
  59183. this.mesh.alwaysSelectAsActiveMesh = val;
  59184. },
  59185. enumerable: true,
  59186. configurable: true
  59187. });
  59188. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59189. /**
  59190. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59191. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59192. */
  59193. get: function () {
  59194. return this._isVisibilityBoxLocked;
  59195. },
  59196. /**
  59197. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59198. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59199. */
  59200. set: function (val) {
  59201. this._isVisibilityBoxLocked = val;
  59202. var boundingInfo = this.mesh.getBoundingInfo();
  59203. boundingInfo.isLocked = val;
  59204. },
  59205. enumerable: true,
  59206. configurable: true
  59207. });
  59208. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59209. /**
  59210. * Gets if `setParticles()` computes the particle rotations or not.
  59211. * Default value : true. The SPS is faster when it's set to false.
  59212. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59213. */
  59214. get: function () {
  59215. return this._computeParticleRotation;
  59216. },
  59217. /**
  59218. * Tells to `setParticles()` to compute the particle rotations or not.
  59219. * Default value : true. The SPS is faster when it's set to false.
  59220. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59221. */
  59222. set: function (val) {
  59223. this._computeParticleRotation = val;
  59224. },
  59225. enumerable: true,
  59226. configurable: true
  59227. });
  59228. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59229. /**
  59230. * Gets if `setParticles()` computes the particle colors or not.
  59231. * Default value : true. The SPS is faster when it's set to false.
  59232. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59233. */
  59234. get: function () {
  59235. return this._computeParticleColor;
  59236. },
  59237. /**
  59238. * Tells to `setParticles()` to compute the particle colors or not.
  59239. * Default value : true. The SPS is faster when it's set to false.
  59240. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59241. */
  59242. set: function (val) {
  59243. this._computeParticleColor = val;
  59244. },
  59245. enumerable: true,
  59246. configurable: true
  59247. });
  59248. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59249. /**
  59250. * Gets if `setParticles()` computes the particle textures or not.
  59251. * Default value : true. The SPS is faster when it's set to false.
  59252. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59253. */
  59254. get: function () {
  59255. return this._computeParticleTexture;
  59256. },
  59257. set: function (val) {
  59258. this._computeParticleTexture = val;
  59259. },
  59260. enumerable: true,
  59261. configurable: true
  59262. });
  59263. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59264. /**
  59265. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59266. * Default value : false. The SPS is faster when it's set to false.
  59267. * Note : the particle custom vertex positions aren't stored values.
  59268. */
  59269. get: function () {
  59270. return this._computeParticleVertex;
  59271. },
  59272. /**
  59273. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59274. * Default value : false. The SPS is faster when it's set to false.
  59275. * Note : the particle custom vertex positions aren't stored values.
  59276. */
  59277. set: function (val) {
  59278. this._computeParticleVertex = val;
  59279. },
  59280. enumerable: true,
  59281. configurable: true
  59282. });
  59283. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59284. /**
  59285. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59286. */
  59287. get: function () {
  59288. return this._computeBoundingBox;
  59289. },
  59290. /**
  59291. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59292. */
  59293. set: function (val) {
  59294. this._computeBoundingBox = val;
  59295. },
  59296. enumerable: true,
  59297. configurable: true
  59298. });
  59299. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59300. /**
  59301. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59302. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59303. * Default : `true`
  59304. */
  59305. get: function () {
  59306. return this._depthSortParticles;
  59307. },
  59308. /**
  59309. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59310. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59311. * Default : `true`
  59312. */
  59313. set: function (val) {
  59314. this._depthSortParticles = val;
  59315. },
  59316. enumerable: true,
  59317. configurable: true
  59318. });
  59319. // =======================================================================
  59320. // Particle behavior logic
  59321. // these following methods may be overwritten by the user to fit his needs
  59322. /**
  59323. * This function does nothing. It may be overwritten to set all the particle first values.
  59324. * The SPS doesn't call this function, you may have to call it by your own.
  59325. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59326. */
  59327. SolidParticleSystem.prototype.initParticles = function () {
  59328. };
  59329. /**
  59330. * This function does nothing. It may be overwritten to recycle a particle.
  59331. * The SPS doesn't call this function, you may have to call it by your own.
  59332. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59333. * @param particle The particle to recycle
  59334. * @returns the recycled particle
  59335. */
  59336. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59337. return particle;
  59338. };
  59339. /**
  59340. * Updates a particle : this function should be overwritten by the user.
  59341. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59342. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59343. * @example : just set a particle position or velocity and recycle conditions
  59344. * @param particle The particle to update
  59345. * @returns the updated particle
  59346. */
  59347. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59348. return particle;
  59349. };
  59350. /**
  59351. * Updates a vertex of a particle : it can be overwritten by the user.
  59352. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59353. * @param particle the current particle
  59354. * @param vertex the current index of the current particle
  59355. * @param pt the index of the current vertex in the particle shape
  59356. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59357. * @example : just set a vertex particle position
  59358. * @returns the updated vertex
  59359. */
  59360. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59361. return vertex;
  59362. };
  59363. /**
  59364. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59365. * This does nothing and may be overwritten by the user.
  59366. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59367. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59368. * @param update the boolean update value actually passed to setParticles()
  59369. */
  59370. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59371. };
  59372. /**
  59373. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59374. * This will be passed three parameters.
  59375. * This does nothing and may be overwritten by the user.
  59376. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59377. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59378. * @param update the boolean update value actually passed to setParticles()
  59379. */
  59380. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59381. };
  59382. return SolidParticleSystem;
  59383. }());
  59384. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59385. })(BABYLON || (BABYLON = {}));
  59386. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59387. var BABYLON;
  59388. (function (BABYLON) {
  59389. var ShaderMaterial = /** @class */ (function (_super) {
  59390. __extends(ShaderMaterial, _super);
  59391. function ShaderMaterial(name, scene, shaderPath, options) {
  59392. var _this = _super.call(this, name, scene) || this;
  59393. _this._textures = {};
  59394. _this._textureArrays = {};
  59395. _this._floats = {};
  59396. _this._ints = {};
  59397. _this._floatsArrays = {};
  59398. _this._colors3 = {};
  59399. _this._colors3Arrays = {};
  59400. _this._colors4 = {};
  59401. _this._vectors2 = {};
  59402. _this._vectors3 = {};
  59403. _this._vectors4 = {};
  59404. _this._matrices = {};
  59405. _this._matrices3x3 = {};
  59406. _this._matrices2x2 = {};
  59407. _this._vectors2Arrays = {};
  59408. _this._vectors3Arrays = {};
  59409. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59410. _this._shaderPath = shaderPath;
  59411. options.needAlphaBlending = options.needAlphaBlending || false;
  59412. options.needAlphaTesting = options.needAlphaTesting || false;
  59413. options.attributes = options.attributes || ["position", "normal", "uv"];
  59414. options.uniforms = options.uniforms || ["worldViewProjection"];
  59415. options.uniformBuffers = options.uniformBuffers || [];
  59416. options.samplers = options.samplers || [];
  59417. options.defines = options.defines || [];
  59418. _this._options = options;
  59419. return _this;
  59420. }
  59421. ShaderMaterial.prototype.getClassName = function () {
  59422. return "ShaderMaterial";
  59423. };
  59424. ShaderMaterial.prototype.needAlphaBlending = function () {
  59425. return this._options.needAlphaBlending;
  59426. };
  59427. ShaderMaterial.prototype.needAlphaTesting = function () {
  59428. return this._options.needAlphaTesting;
  59429. };
  59430. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59431. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59432. this._options.uniforms.push(uniformName);
  59433. }
  59434. };
  59435. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59436. if (this._options.samplers.indexOf(name) === -1) {
  59437. this._options.samplers.push(name);
  59438. }
  59439. this._textures[name] = texture;
  59440. return this;
  59441. };
  59442. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59443. if (this._options.samplers.indexOf(name) === -1) {
  59444. this._options.samplers.push(name);
  59445. }
  59446. this._checkUniform(name);
  59447. this._textureArrays[name] = textures;
  59448. return this;
  59449. };
  59450. ShaderMaterial.prototype.setFloat = function (name, value) {
  59451. this._checkUniform(name);
  59452. this._floats[name] = value;
  59453. return this;
  59454. };
  59455. ShaderMaterial.prototype.setInt = function (name, value) {
  59456. this._checkUniform(name);
  59457. this._ints[name] = value;
  59458. return this;
  59459. };
  59460. ShaderMaterial.prototype.setFloats = function (name, value) {
  59461. this._checkUniform(name);
  59462. this._floatsArrays[name] = value;
  59463. return this;
  59464. };
  59465. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59466. this._checkUniform(name);
  59467. this._colors3[name] = value;
  59468. return this;
  59469. };
  59470. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59471. this._checkUniform(name);
  59472. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59473. color.toArray(arr, arr.length);
  59474. return arr;
  59475. }, []);
  59476. return this;
  59477. };
  59478. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59479. this._checkUniform(name);
  59480. this._colors4[name] = value;
  59481. return this;
  59482. };
  59483. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59484. this._checkUniform(name);
  59485. this._vectors2[name] = value;
  59486. return this;
  59487. };
  59488. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59489. this._checkUniform(name);
  59490. this._vectors3[name] = value;
  59491. return this;
  59492. };
  59493. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59494. this._checkUniform(name);
  59495. this._vectors4[name] = value;
  59496. return this;
  59497. };
  59498. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59499. this._checkUniform(name);
  59500. this._matrices[name] = value;
  59501. return this;
  59502. };
  59503. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59504. this._checkUniform(name);
  59505. this._matrices3x3[name] = value;
  59506. return this;
  59507. };
  59508. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59509. this._checkUniform(name);
  59510. this._matrices2x2[name] = value;
  59511. return this;
  59512. };
  59513. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59514. this._checkUniform(name);
  59515. this._vectors2Arrays[name] = value;
  59516. return this;
  59517. };
  59518. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59519. this._checkUniform(name);
  59520. this._vectors3Arrays[name] = value;
  59521. return this;
  59522. };
  59523. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59524. if (!mesh) {
  59525. return true;
  59526. }
  59527. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59528. return false;
  59529. }
  59530. return false;
  59531. };
  59532. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59533. var scene = this.getScene();
  59534. var engine = scene.getEngine();
  59535. if (!this.checkReadyOnEveryCall) {
  59536. if (this._renderId === scene.getRenderId()) {
  59537. if (this._checkCache(scene, mesh, useInstances)) {
  59538. return true;
  59539. }
  59540. }
  59541. }
  59542. // Instances
  59543. var defines = [];
  59544. var attribs = [];
  59545. var fallbacks = new BABYLON.EffectFallbacks();
  59546. if (useInstances) {
  59547. defines.push("#define INSTANCES");
  59548. }
  59549. for (var index = 0; index < this._options.defines.length; index++) {
  59550. defines.push(this._options.defines[index]);
  59551. }
  59552. for (var index = 0; index < this._options.attributes.length; index++) {
  59553. attribs.push(this._options.attributes[index]);
  59554. }
  59555. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59556. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59557. defines.push("#define VERTEXCOLOR");
  59558. }
  59559. // Bones
  59560. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59563. if (mesh.numBoneInfluencers > 4) {
  59564. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59565. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59566. }
  59567. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59568. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59569. fallbacks.addCPUSkinningFallback(0, mesh);
  59570. if (this._options.uniforms.indexOf("mBones") === -1) {
  59571. this._options.uniforms.push("mBones");
  59572. }
  59573. }
  59574. else {
  59575. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59576. }
  59577. // Textures
  59578. for (var name in this._textures) {
  59579. if (!this._textures[name].isReady()) {
  59580. return false;
  59581. }
  59582. }
  59583. // Alpha test
  59584. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59585. defines.push("#define ALPHATEST");
  59586. }
  59587. var previousEffect = this._effect;
  59588. var join = defines.join("\n");
  59589. this._effect = engine.createEffect(this._shaderPath, {
  59590. attributes: attribs,
  59591. uniformsNames: this._options.uniforms,
  59592. uniformBuffersNames: this._options.uniformBuffers,
  59593. samplers: this._options.samplers,
  59594. defines: join,
  59595. fallbacks: fallbacks,
  59596. onCompiled: this.onCompiled,
  59597. onError: this.onError
  59598. }, engine);
  59599. if (!this._effect.isReady()) {
  59600. return false;
  59601. }
  59602. if (previousEffect !== this._effect) {
  59603. scene.resetCachedMaterial();
  59604. }
  59605. this._renderId = scene.getRenderId();
  59606. return true;
  59607. };
  59608. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59609. var scene = this.getScene();
  59610. if (!this._effect) {
  59611. return;
  59612. }
  59613. if (this._options.uniforms.indexOf("world") !== -1) {
  59614. this._effect.setMatrix("world", world);
  59615. }
  59616. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59617. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59618. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59619. }
  59620. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59621. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59622. }
  59623. };
  59624. ShaderMaterial.prototype.bind = function (world, mesh) {
  59625. // Std values
  59626. this.bindOnlyWorldMatrix(world);
  59627. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59628. if (this._options.uniforms.indexOf("view") !== -1) {
  59629. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59630. }
  59631. if (this._options.uniforms.indexOf("projection") !== -1) {
  59632. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59633. }
  59634. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59635. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59636. }
  59637. // Bones
  59638. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59639. var name;
  59640. // Texture
  59641. for (name in this._textures) {
  59642. this._effect.setTexture(name, this._textures[name]);
  59643. }
  59644. // Texture arrays
  59645. for (name in this._textureArrays) {
  59646. this._effect.setTextureArray(name, this._textureArrays[name]);
  59647. }
  59648. // Int
  59649. for (name in this._ints) {
  59650. this._effect.setInt(name, this._ints[name]);
  59651. }
  59652. // Float
  59653. for (name in this._floats) {
  59654. this._effect.setFloat(name, this._floats[name]);
  59655. }
  59656. // Floats
  59657. for (name in this._floatsArrays) {
  59658. this._effect.setArray(name, this._floatsArrays[name]);
  59659. }
  59660. // Color3
  59661. for (name in this._colors3) {
  59662. this._effect.setColor3(name, this._colors3[name]);
  59663. }
  59664. for (name in this._colors3Arrays) {
  59665. this._effect.setArray3(name, this._colors3Arrays[name]);
  59666. }
  59667. // Color4
  59668. for (name in this._colors4) {
  59669. var color = this._colors4[name];
  59670. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59671. }
  59672. // Vector2
  59673. for (name in this._vectors2) {
  59674. this._effect.setVector2(name, this._vectors2[name]);
  59675. }
  59676. // Vector3
  59677. for (name in this._vectors3) {
  59678. this._effect.setVector3(name, this._vectors3[name]);
  59679. }
  59680. // Vector4
  59681. for (name in this._vectors4) {
  59682. this._effect.setVector4(name, this._vectors4[name]);
  59683. }
  59684. // Matrix
  59685. for (name in this._matrices) {
  59686. this._effect.setMatrix(name, this._matrices[name]);
  59687. }
  59688. // Matrix 3x3
  59689. for (name in this._matrices3x3) {
  59690. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59691. }
  59692. // Matrix 2x2
  59693. for (name in this._matrices2x2) {
  59694. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59695. }
  59696. // Vector2Array
  59697. for (name in this._vectors2Arrays) {
  59698. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59699. }
  59700. // Vector3Array
  59701. for (name in this._vectors3Arrays) {
  59702. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59703. }
  59704. }
  59705. this._afterBind(mesh);
  59706. };
  59707. ShaderMaterial.prototype.getActiveTextures = function () {
  59708. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59709. for (var name in this._textures) {
  59710. activeTextures.push(this._textures[name]);
  59711. }
  59712. for (var name in this._textureArrays) {
  59713. var array = this._textureArrays[name];
  59714. for (var index = 0; index < array.length; index++) {
  59715. activeTextures.push(array[index]);
  59716. }
  59717. }
  59718. return activeTextures;
  59719. };
  59720. ShaderMaterial.prototype.hasTexture = function (texture) {
  59721. if (_super.prototype.hasTexture.call(this, texture)) {
  59722. return true;
  59723. }
  59724. for (var name in this._textures) {
  59725. if (this._textures[name] === texture) {
  59726. return true;
  59727. }
  59728. }
  59729. for (var name in this._textureArrays) {
  59730. var array = this._textureArrays[name];
  59731. for (var index = 0; index < array.length; index++) {
  59732. if (array[index] === texture) {
  59733. return true;
  59734. }
  59735. }
  59736. }
  59737. return false;
  59738. };
  59739. ShaderMaterial.prototype.clone = function (name) {
  59740. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59741. return newShaderMaterial;
  59742. };
  59743. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59744. if (forceDisposeTextures) {
  59745. var name;
  59746. for (name in this._textures) {
  59747. this._textures[name].dispose();
  59748. }
  59749. for (name in this._textureArrays) {
  59750. var array = this._textureArrays[name];
  59751. for (var index = 0; index < array.length; index++) {
  59752. array[index].dispose();
  59753. }
  59754. }
  59755. }
  59756. this._textures = {};
  59757. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59758. };
  59759. ShaderMaterial.prototype.serialize = function () {
  59760. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59761. serializationObject.customType = "BABYLON.ShaderMaterial";
  59762. serializationObject.options = this._options;
  59763. serializationObject.shaderPath = this._shaderPath;
  59764. var name;
  59765. // Texture
  59766. serializationObject.textures = {};
  59767. for (name in this._textures) {
  59768. serializationObject.textures[name] = this._textures[name].serialize();
  59769. }
  59770. // Texture arrays
  59771. serializationObject.textureArrays = {};
  59772. for (name in this._textureArrays) {
  59773. serializationObject.textureArrays[name] = [];
  59774. var array = this._textureArrays[name];
  59775. for (var index = 0; index < array.length; index++) {
  59776. serializationObject.textureArrays[name].push(array[index].serialize());
  59777. }
  59778. }
  59779. // Float
  59780. serializationObject.floats = {};
  59781. for (name in this._floats) {
  59782. serializationObject.floats[name] = this._floats[name];
  59783. }
  59784. // Float s
  59785. serializationObject.FloatArrays = {};
  59786. for (name in this._floatsArrays) {
  59787. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59788. }
  59789. // Color3
  59790. serializationObject.colors3 = {};
  59791. for (name in this._colors3) {
  59792. serializationObject.colors3[name] = this._colors3[name].asArray();
  59793. }
  59794. // Color3 array
  59795. serializationObject.colors3Arrays = {};
  59796. for (name in this._colors3Arrays) {
  59797. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59798. }
  59799. // Color4
  59800. serializationObject.colors4 = {};
  59801. for (name in this._colors4) {
  59802. serializationObject.colors4[name] = this._colors4[name].asArray();
  59803. }
  59804. // Vector2
  59805. serializationObject.vectors2 = {};
  59806. for (name in this._vectors2) {
  59807. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59808. }
  59809. // Vector3
  59810. serializationObject.vectors3 = {};
  59811. for (name in this._vectors3) {
  59812. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59813. }
  59814. // Vector4
  59815. serializationObject.vectors4 = {};
  59816. for (name in this._vectors4) {
  59817. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59818. }
  59819. // Matrix
  59820. serializationObject.matrices = {};
  59821. for (name in this._matrices) {
  59822. serializationObject.matrices[name] = this._matrices[name].asArray();
  59823. }
  59824. // Matrix 3x3
  59825. serializationObject.matrices3x3 = {};
  59826. for (name in this._matrices3x3) {
  59827. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59828. }
  59829. // Matrix 2x2
  59830. serializationObject.matrices2x2 = {};
  59831. for (name in this._matrices2x2) {
  59832. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59833. }
  59834. // Vector2Array
  59835. serializationObject.vectors2Arrays = {};
  59836. for (name in this._vectors2Arrays) {
  59837. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59838. }
  59839. // Vector3Array
  59840. serializationObject.vectors3Arrays = {};
  59841. for (name in this._vectors3Arrays) {
  59842. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59843. }
  59844. return serializationObject;
  59845. };
  59846. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59847. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59848. var name;
  59849. // Texture
  59850. for (name in source.textures) {
  59851. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59852. }
  59853. // Texture arrays
  59854. for (name in source.textureArrays) {
  59855. var array = source.textureArrays[name];
  59856. var textureArray = new Array();
  59857. for (var index = 0; index < array.length; index++) {
  59858. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59859. }
  59860. material.setTextureArray(name, textureArray);
  59861. }
  59862. // Float
  59863. for (name in source.floats) {
  59864. material.setFloat(name, source.floats[name]);
  59865. }
  59866. // Float s
  59867. for (name in source.floatsArrays) {
  59868. material.setFloats(name, source.floatsArrays[name]);
  59869. }
  59870. // Color3
  59871. for (name in source.colors3) {
  59872. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59873. }
  59874. // Color3 arrays
  59875. for (name in source.colors3Arrays) {
  59876. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59877. if (i % 3 === 0) {
  59878. arr.push([num]);
  59879. }
  59880. else {
  59881. arr[arr.length - 1].push(num);
  59882. }
  59883. return arr;
  59884. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59885. material.setColor3Array(name, colors);
  59886. }
  59887. // Color4
  59888. for (name in source.colors4) {
  59889. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59890. }
  59891. // Vector2
  59892. for (name in source.vectors2) {
  59893. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59894. }
  59895. // Vector3
  59896. for (name in source.vectors3) {
  59897. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59898. }
  59899. // Vector4
  59900. for (name in source.vectors4) {
  59901. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59902. }
  59903. // Matrix
  59904. for (name in source.matrices) {
  59905. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59906. }
  59907. // Matrix 3x3
  59908. for (name in source.matrices3x3) {
  59909. material.setMatrix3x3(name, source.matrices3x3[name]);
  59910. }
  59911. // Matrix 2x2
  59912. for (name in source.matrices2x2) {
  59913. material.setMatrix2x2(name, source.matrices2x2[name]);
  59914. }
  59915. // Vector2Array
  59916. for (name in source.vectors2Arrays) {
  59917. material.setArray2(name, source.vectors2Arrays[name]);
  59918. }
  59919. // Vector3Array
  59920. for (name in source.vectors3Arrays) {
  59921. material.setArray3(name, source.vectors3Arrays[name]);
  59922. }
  59923. return material;
  59924. };
  59925. return ShaderMaterial;
  59926. }(BABYLON.Material));
  59927. BABYLON.ShaderMaterial = ShaderMaterial;
  59928. })(BABYLON || (BABYLON = {}));
  59929. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59930. var BABYLON;
  59931. (function (BABYLON) {
  59932. var GroundMesh = /** @class */ (function (_super) {
  59933. __extends(GroundMesh, _super);
  59934. function GroundMesh(name, scene) {
  59935. var _this = _super.call(this, name, scene) || this;
  59936. _this.generateOctree = false;
  59937. return _this;
  59938. }
  59939. GroundMesh.prototype.getClassName = function () {
  59940. return "GroundMesh";
  59941. };
  59942. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59943. get: function () {
  59944. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59945. },
  59946. enumerable: true,
  59947. configurable: true
  59948. });
  59949. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59950. get: function () {
  59951. return this._subdivisionsX;
  59952. },
  59953. enumerable: true,
  59954. configurable: true
  59955. });
  59956. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59957. get: function () {
  59958. return this._subdivisionsY;
  59959. },
  59960. enumerable: true,
  59961. configurable: true
  59962. });
  59963. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59964. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59965. this._subdivisionsX = chunksCount;
  59966. this._subdivisionsY = chunksCount;
  59967. this.subdivide(chunksCount);
  59968. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59969. };
  59970. /**
  59971. * Returns a height (y) value in the Worl system :
  59972. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59973. * Returns the ground y position if (x, z) are outside the ground surface.
  59974. */
  59975. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59976. var world = this.getWorldMatrix();
  59977. var invMat = BABYLON.Tmp.Matrix[5];
  59978. world.invertToRef(invMat);
  59979. var tmpVect = BABYLON.Tmp.Vector3[8];
  59980. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59981. x = tmpVect.x;
  59982. z = tmpVect.z;
  59983. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59984. return this.position.y;
  59985. }
  59986. if (!this._heightQuads || this._heightQuads.length == 0) {
  59987. this._initHeightQuads();
  59988. this._computeHeightQuads();
  59989. }
  59990. var facet = this._getFacetAt(x, z);
  59991. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59992. // return y in the World system
  59993. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59994. return tmpVect.y;
  59995. };
  59996. /**
  59997. * Returns a normalized vector (Vector3) orthogonal to the ground
  59998. * at the ground coordinates (x, z) expressed in the World system.
  59999. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60000. */
  60001. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60002. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60003. this.getNormalAtCoordinatesToRef(x, z, normal);
  60004. return normal;
  60005. };
  60006. /**
  60007. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60008. * at the ground coordinates (x, z) expressed in the World system.
  60009. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60010. * Returns the GroundMesh.
  60011. */
  60012. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60013. var world = this.getWorldMatrix();
  60014. var tmpMat = BABYLON.Tmp.Matrix[5];
  60015. world.invertToRef(tmpMat);
  60016. var tmpVect = BABYLON.Tmp.Vector3[8];
  60017. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60018. x = tmpVect.x;
  60019. z = tmpVect.z;
  60020. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60021. return this;
  60022. }
  60023. if (!this._heightQuads || this._heightQuads.length == 0) {
  60024. this._initHeightQuads();
  60025. this._computeHeightQuads();
  60026. }
  60027. var facet = this._getFacetAt(x, z);
  60028. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60029. return this;
  60030. };
  60031. /**
  60032. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60033. * if the ground has been updated.
  60034. * This can be used in the render loop.
  60035. * Returns the GroundMesh.
  60036. */
  60037. GroundMesh.prototype.updateCoordinateHeights = function () {
  60038. if (!this._heightQuads || this._heightQuads.length == 0) {
  60039. this._initHeightQuads();
  60040. }
  60041. this._computeHeightQuads();
  60042. return this;
  60043. };
  60044. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60045. GroundMesh.prototype._getFacetAt = function (x, z) {
  60046. // retrieve col and row from x, z coordinates in the ground local system
  60047. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60048. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60049. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60050. var facet;
  60051. if (z < quad.slope.x * x + quad.slope.y) {
  60052. facet = quad.facet1;
  60053. }
  60054. else {
  60055. facet = quad.facet2;
  60056. }
  60057. return facet;
  60058. };
  60059. // Creates and populates the heightMap array with "facet" elements :
  60060. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60061. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60062. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60063. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60064. // Returns the GroundMesh.
  60065. GroundMesh.prototype._initHeightQuads = function () {
  60066. var subdivisionsX = this._subdivisionsX;
  60067. var subdivisionsY = this._subdivisionsY;
  60068. this._heightQuads = new Array();
  60069. for (var row = 0; row < subdivisionsY; row++) {
  60070. for (var col = 0; col < subdivisionsX; col++) {
  60071. 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) };
  60072. this._heightQuads[row * subdivisionsX + col] = quad;
  60073. }
  60074. }
  60075. return this;
  60076. };
  60077. // Compute each quad element values and update the the heightMap array :
  60078. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60079. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60080. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60081. // Returns the GroundMesh.
  60082. GroundMesh.prototype._computeHeightQuads = function () {
  60083. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60084. if (!positions) {
  60085. return this;
  60086. }
  60087. var v1 = BABYLON.Tmp.Vector3[3];
  60088. var v2 = BABYLON.Tmp.Vector3[2];
  60089. var v3 = BABYLON.Tmp.Vector3[1];
  60090. var v4 = BABYLON.Tmp.Vector3[0];
  60091. var v1v2 = BABYLON.Tmp.Vector3[4];
  60092. var v1v3 = BABYLON.Tmp.Vector3[5];
  60093. var v1v4 = BABYLON.Tmp.Vector3[6];
  60094. var norm1 = BABYLON.Tmp.Vector3[7];
  60095. var norm2 = BABYLON.Tmp.Vector3[8];
  60096. var i = 0;
  60097. var j = 0;
  60098. var k = 0;
  60099. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60100. var h = 0;
  60101. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60102. var d2 = 0;
  60103. var subdivisionsX = this._subdivisionsX;
  60104. var subdivisionsY = this._subdivisionsY;
  60105. for (var row = 0; row < subdivisionsY; row++) {
  60106. for (var col = 0; col < subdivisionsX; col++) {
  60107. i = col * 3;
  60108. j = row * (subdivisionsX + 1) * 3;
  60109. k = (row + 1) * (subdivisionsX + 1) * 3;
  60110. v1.x = positions[j + i];
  60111. v1.y = positions[j + i + 1];
  60112. v1.z = positions[j + i + 2];
  60113. v2.x = positions[j + i + 3];
  60114. v2.y = positions[j + i + 4];
  60115. v2.z = positions[j + i + 5];
  60116. v3.x = positions[k + i];
  60117. v3.y = positions[k + i + 1];
  60118. v3.z = positions[k + i + 2];
  60119. v4.x = positions[k + i + 3];
  60120. v4.y = positions[k + i + 4];
  60121. v4.z = positions[k + i + 5];
  60122. // 2D slope V1V4
  60123. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60124. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60125. // facet equations :
  60126. // we compute each facet normal vector
  60127. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60128. // we compute the value d by applying the equation to v1 which belongs to the plane
  60129. // then we store the facet equation in a Vector4
  60130. v2.subtractToRef(v1, v1v2);
  60131. v3.subtractToRef(v1, v1v3);
  60132. v4.subtractToRef(v1, v1v4);
  60133. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60134. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60135. norm1.normalize();
  60136. norm2.normalize();
  60137. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60138. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60139. var quad = this._heightQuads[row * subdivisionsX + col];
  60140. quad.slope.copyFromFloats(cd, h);
  60141. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60142. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60143. }
  60144. }
  60145. return this;
  60146. };
  60147. GroundMesh.prototype.serialize = function (serializationObject) {
  60148. _super.prototype.serialize.call(this, serializationObject);
  60149. serializationObject.subdivisionsX = this._subdivisionsX;
  60150. serializationObject.subdivisionsY = this._subdivisionsY;
  60151. serializationObject.minX = this._minX;
  60152. serializationObject.maxX = this._maxX;
  60153. serializationObject.minZ = this._minZ;
  60154. serializationObject.maxZ = this._maxZ;
  60155. serializationObject.width = this._width;
  60156. serializationObject.height = this._height;
  60157. };
  60158. GroundMesh.Parse = function (parsedMesh, scene) {
  60159. var result = new GroundMesh(parsedMesh.name, scene);
  60160. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60161. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60162. result._minX = parsedMesh.minX;
  60163. result._maxX = parsedMesh.maxX;
  60164. result._minZ = parsedMesh.minZ;
  60165. result._maxZ = parsedMesh.maxZ;
  60166. result._width = parsedMesh.width;
  60167. result._height = parsedMesh.height;
  60168. return result;
  60169. };
  60170. return GroundMesh;
  60171. }(BABYLON.Mesh));
  60172. BABYLON.GroundMesh = GroundMesh;
  60173. })(BABYLON || (BABYLON = {}));
  60174. //# sourceMappingURL=babylon.groundMesh.js.map
  60175. var BABYLON;
  60176. (function (BABYLON) {
  60177. /**
  60178. * Creates an instance based on a source mesh.
  60179. */
  60180. var InstancedMesh = /** @class */ (function (_super) {
  60181. __extends(InstancedMesh, _super);
  60182. function InstancedMesh(name, source) {
  60183. var _this = _super.call(this, name, source.getScene()) || this;
  60184. source.instances.push(_this);
  60185. _this._sourceMesh = source;
  60186. _this.position.copyFrom(source.position);
  60187. _this.rotation.copyFrom(source.rotation);
  60188. _this.scaling.copyFrom(source.scaling);
  60189. if (source.rotationQuaternion) {
  60190. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60191. }
  60192. _this.infiniteDistance = source.infiniteDistance;
  60193. _this.setPivotMatrix(source.getPivotMatrix());
  60194. _this.refreshBoundingInfo();
  60195. _this._syncSubMeshes();
  60196. return _this;
  60197. }
  60198. /**
  60199. * Returns the string "InstancedMesh".
  60200. */
  60201. InstancedMesh.prototype.getClassName = function () {
  60202. return "InstancedMesh";
  60203. };
  60204. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60205. // Methods
  60206. get: function () {
  60207. return this._sourceMesh.receiveShadows;
  60208. },
  60209. enumerable: true,
  60210. configurable: true
  60211. });
  60212. Object.defineProperty(InstancedMesh.prototype, "material", {
  60213. get: function () {
  60214. return this._sourceMesh.material;
  60215. },
  60216. enumerable: true,
  60217. configurable: true
  60218. });
  60219. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60220. get: function () {
  60221. return this._sourceMesh.visibility;
  60222. },
  60223. enumerable: true,
  60224. configurable: true
  60225. });
  60226. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60227. get: function () {
  60228. return this._sourceMesh.skeleton;
  60229. },
  60230. enumerable: true,
  60231. configurable: true
  60232. });
  60233. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60234. get: function () {
  60235. return this._sourceMesh.renderingGroupId;
  60236. },
  60237. set: function (value) {
  60238. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60239. return;
  60240. }
  60241. //no-op with warning
  60242. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60243. },
  60244. enumerable: true,
  60245. configurable: true
  60246. });
  60247. /**
  60248. * Returns the total number of vertices (integer).
  60249. */
  60250. InstancedMesh.prototype.getTotalVertices = function () {
  60251. return this._sourceMesh.getTotalVertices();
  60252. };
  60253. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60254. get: function () {
  60255. return this._sourceMesh;
  60256. },
  60257. enumerable: true,
  60258. configurable: true
  60259. });
  60260. /**
  60261. * Is this node ready to be used/rendered
  60262. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60263. * @return {boolean} is it ready
  60264. */
  60265. InstancedMesh.prototype.isReady = function (completeCheck) {
  60266. if (completeCheck === void 0) { completeCheck = false; }
  60267. return this._sourceMesh.isReady(completeCheck, true);
  60268. };
  60269. /**
  60270. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60271. */
  60272. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60273. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60274. };
  60275. /**
  60276. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60277. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60278. * The `data` are either a numeric array either a Float32Array.
  60279. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60280. * 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).
  60281. * Note that a new underlying VertexBuffer object is created each call.
  60282. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60283. *
  60284. * Possible `kind` values :
  60285. * - BABYLON.VertexBuffer.PositionKind
  60286. * - BABYLON.VertexBuffer.UVKind
  60287. * - BABYLON.VertexBuffer.UV2Kind
  60288. * - BABYLON.VertexBuffer.UV3Kind
  60289. * - BABYLON.VertexBuffer.UV4Kind
  60290. * - BABYLON.VertexBuffer.UV5Kind
  60291. * - BABYLON.VertexBuffer.UV6Kind
  60292. * - BABYLON.VertexBuffer.ColorKind
  60293. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60294. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60295. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60296. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60297. *
  60298. * Returns the Mesh.
  60299. */
  60300. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60301. if (this.sourceMesh) {
  60302. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60303. }
  60304. return this.sourceMesh;
  60305. };
  60306. /**
  60307. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60308. * If the mesh has no geometry, it is simply returned as it is.
  60309. * The `data` are either a numeric array either a Float32Array.
  60310. * No new underlying VertexBuffer object is created.
  60311. * 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.
  60312. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60313. *
  60314. * Possible `kind` values :
  60315. * - BABYLON.VertexBuffer.PositionKind
  60316. * - BABYLON.VertexBuffer.UVKind
  60317. * - BABYLON.VertexBuffer.UV2Kind
  60318. * - BABYLON.VertexBuffer.UV3Kind
  60319. * - BABYLON.VertexBuffer.UV4Kind
  60320. * - BABYLON.VertexBuffer.UV5Kind
  60321. * - BABYLON.VertexBuffer.UV6Kind
  60322. * - BABYLON.VertexBuffer.ColorKind
  60323. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60324. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60325. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60326. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60327. *
  60328. * Returns the Mesh.
  60329. */
  60330. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60331. if (this.sourceMesh) {
  60332. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60333. }
  60334. return this.sourceMesh;
  60335. };
  60336. /**
  60337. * Sets the mesh indices.
  60338. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60339. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60340. * This method creates a new index buffer each call.
  60341. * Returns the Mesh.
  60342. */
  60343. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60344. if (totalVertices === void 0) { totalVertices = null; }
  60345. if (this.sourceMesh) {
  60346. this.sourceMesh.setIndices(indices, totalVertices);
  60347. }
  60348. return this.sourceMesh;
  60349. };
  60350. /**
  60351. * Boolean : True if the mesh owns the requested kind of data.
  60352. */
  60353. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60354. return this._sourceMesh.isVerticesDataPresent(kind);
  60355. };
  60356. /**
  60357. * Returns an array of indices (IndicesArray).
  60358. */
  60359. InstancedMesh.prototype.getIndices = function () {
  60360. return this._sourceMesh.getIndices();
  60361. };
  60362. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60363. get: function () {
  60364. return this._sourceMesh._positions;
  60365. },
  60366. enumerable: true,
  60367. configurable: true
  60368. });
  60369. /**
  60370. * Sets a new updated BoundingInfo to the mesh.
  60371. * Returns the mesh.
  60372. */
  60373. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60374. var meshBB = this._sourceMesh.getBoundingInfo();
  60375. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60376. this._updateBoundingInfo();
  60377. return this;
  60378. };
  60379. InstancedMesh.prototype._preActivate = function () {
  60380. if (this._currentLOD) {
  60381. this._currentLOD._preActivate();
  60382. }
  60383. return this;
  60384. };
  60385. InstancedMesh.prototype._activate = function (renderId) {
  60386. if (this._currentLOD) {
  60387. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60388. }
  60389. return this;
  60390. };
  60391. /**
  60392. * Returns the current associated LOD AbstractMesh.
  60393. */
  60394. InstancedMesh.prototype.getLOD = function (camera) {
  60395. if (!camera) {
  60396. return this;
  60397. }
  60398. var boundingInfo = this.getBoundingInfo();
  60399. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60400. if (this._currentLOD === this.sourceMesh) {
  60401. return this;
  60402. }
  60403. return this._currentLOD;
  60404. };
  60405. InstancedMesh.prototype._syncSubMeshes = function () {
  60406. this.releaseSubMeshes();
  60407. if (this._sourceMesh.subMeshes) {
  60408. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60409. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60410. }
  60411. }
  60412. return this;
  60413. };
  60414. InstancedMesh.prototype._generatePointsArray = function () {
  60415. return this._sourceMesh._generatePointsArray();
  60416. };
  60417. /**
  60418. * Creates a new InstancedMesh from the current mesh.
  60419. * - name (string) : the cloned mesh name
  60420. * - newParent (optional Node) : the optional Node to parent the clone to.
  60421. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60422. *
  60423. * Returns the clone.
  60424. */
  60425. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60426. var result = this._sourceMesh.createInstance(name);
  60427. // Deep copy
  60428. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60429. // Bounding info
  60430. this.refreshBoundingInfo();
  60431. // Parent
  60432. if (newParent) {
  60433. result.parent = newParent;
  60434. }
  60435. if (!doNotCloneChildren) {
  60436. // Children
  60437. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60438. var mesh = this.getScene().meshes[index];
  60439. if (mesh.parent === this) {
  60440. mesh.clone(mesh.name, result);
  60441. }
  60442. }
  60443. }
  60444. result.computeWorldMatrix(true);
  60445. return result;
  60446. };
  60447. /**
  60448. * Disposes the InstancedMesh.
  60449. * Returns nothing.
  60450. */
  60451. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60452. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60453. // Remove from mesh
  60454. var index = this._sourceMesh.instances.indexOf(this);
  60455. this._sourceMesh.instances.splice(index, 1);
  60456. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60457. };
  60458. return InstancedMesh;
  60459. }(BABYLON.AbstractMesh));
  60460. BABYLON.InstancedMesh = InstancedMesh;
  60461. })(BABYLON || (BABYLON = {}));
  60462. //# sourceMappingURL=babylon.instancedMesh.js.map
  60463. var BABYLON;
  60464. (function (BABYLON) {
  60465. var LinesMesh = /** @class */ (function (_super) {
  60466. __extends(LinesMesh, _super);
  60467. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60468. if (scene === void 0) { scene = null; }
  60469. if (parent === void 0) { parent = null; }
  60470. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60471. _this.useVertexColor = useVertexColor;
  60472. _this.useVertexAlpha = useVertexAlpha;
  60473. _this.color = new BABYLON.Color3(1, 1, 1);
  60474. _this.alpha = 1;
  60475. if (source) {
  60476. _this.color = source.color.clone();
  60477. _this.alpha = source.alpha;
  60478. _this.useVertexColor = source.useVertexColor;
  60479. _this.useVertexAlpha = source.useVertexAlpha;
  60480. }
  60481. _this._intersectionThreshold = 0.1;
  60482. var defines = [];
  60483. var options = {
  60484. attributes: [BABYLON.VertexBuffer.PositionKind],
  60485. uniforms: ["world", "viewProjection"],
  60486. needAlphaBlending: true,
  60487. defines: defines
  60488. };
  60489. if (useVertexAlpha === false) {
  60490. options.needAlphaBlending = false;
  60491. }
  60492. if (!useVertexColor) {
  60493. options.uniforms.push("color");
  60494. }
  60495. else {
  60496. options.defines.push("#define VERTEXCOLOR");
  60497. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60498. }
  60499. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60500. return _this;
  60501. }
  60502. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60503. /**
  60504. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60505. * This margin is expressed in world space coordinates, so its value may vary.
  60506. * Default value is 0.1
  60507. * @returns the intersection Threshold value.
  60508. */
  60509. get: function () {
  60510. return this._intersectionThreshold;
  60511. },
  60512. /**
  60513. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60514. * This margin is expressed in world space coordinates, so its value may vary.
  60515. * @param value the new threshold to apply
  60516. */
  60517. set: function (value) {
  60518. if (this._intersectionThreshold === value) {
  60519. return;
  60520. }
  60521. this._intersectionThreshold = value;
  60522. if (this.geometry) {
  60523. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60524. }
  60525. },
  60526. enumerable: true,
  60527. configurable: true
  60528. });
  60529. /**
  60530. * Returns the string "LineMesh"
  60531. */
  60532. LinesMesh.prototype.getClassName = function () {
  60533. return "LinesMesh";
  60534. };
  60535. Object.defineProperty(LinesMesh.prototype, "material", {
  60536. get: function () {
  60537. return this._colorShader;
  60538. },
  60539. set: function (value) {
  60540. // Do nothing
  60541. },
  60542. enumerable: true,
  60543. configurable: true
  60544. });
  60545. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60546. get: function () {
  60547. return false;
  60548. },
  60549. enumerable: true,
  60550. configurable: true
  60551. });
  60552. LinesMesh.prototype.createInstance = function (name) {
  60553. throw new Error("LinesMeshes do not support createInstance.");
  60554. };
  60555. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60556. if (!this._geometry) {
  60557. return this;
  60558. }
  60559. // VBOs
  60560. this._geometry._bind(this._colorShader.getEffect());
  60561. // Color
  60562. if (!this.useVertexColor) {
  60563. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60564. }
  60565. return this;
  60566. };
  60567. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60568. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60569. return this;
  60570. }
  60571. var engine = this.getScene().getEngine();
  60572. // Draw order
  60573. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60574. return this;
  60575. };
  60576. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60577. this._colorShader.dispose();
  60578. _super.prototype.dispose.call(this, doNotRecurse);
  60579. };
  60580. /**
  60581. * Returns a new LineMesh object cloned from the current one.
  60582. */
  60583. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60584. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60585. };
  60586. return LinesMesh;
  60587. }(BABYLON.Mesh));
  60588. BABYLON.LinesMesh = LinesMesh;
  60589. })(BABYLON || (BABYLON = {}));
  60590. //# sourceMappingURL=babylon.linesMesh.js.map
  60591. var BABYLON;
  60592. (function (BABYLON) {
  60593. /**
  60594. * Class containing static functions to help procedurally build meshes
  60595. */
  60596. var MeshBuilder = /** @class */ (function () {
  60597. function MeshBuilder() {
  60598. }
  60599. MeshBuilder.updateSideOrientation = function (orientation) {
  60600. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60601. return BABYLON.Mesh.DOUBLESIDE;
  60602. }
  60603. if (orientation === undefined || orientation === null) {
  60604. return BABYLON.Mesh.FRONTSIDE;
  60605. }
  60606. return orientation;
  60607. };
  60608. /**
  60609. * Creates a box mesh
  60610. * * The parameter `size` sets the size (float) of each box side (default 1)
  60611. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60612. * * 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)
  60613. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60614. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60615. * * 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
  60616. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60617. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60618. * @param name defines the name of the mesh
  60619. * @param options defines the options used to create the mesh
  60620. * @param scene defines the hosting scene
  60621. * @returns the box mesh
  60622. */
  60623. MeshBuilder.CreateBox = function (name, options, scene) {
  60624. if (scene === void 0) { scene = null; }
  60625. var box = new BABYLON.Mesh(name, scene);
  60626. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60627. box._originalBuilderSideOrientation = options.sideOrientation;
  60628. var vertexData = BABYLON.VertexData.CreateBox(options);
  60629. vertexData.applyToMesh(box, options.updatable);
  60630. return box;
  60631. };
  60632. /**
  60633. * Creates a sphere mesh
  60634. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60635. * * 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`)
  60636. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60637. * * 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
  60638. * * 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)
  60639. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60640. * * 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
  60641. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60642. * @param name defines the name of the mesh
  60643. * @param options defines the options used to create the mesh
  60644. * @param scene defines the hosting scene
  60645. * @returns the sphere mesh
  60646. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60647. */
  60648. MeshBuilder.CreateSphere = function (name, options, scene) {
  60649. var sphere = new BABYLON.Mesh(name, scene);
  60650. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60651. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60652. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60653. vertexData.applyToMesh(sphere, options.updatable);
  60654. return sphere;
  60655. };
  60656. /**
  60657. * Creates a plane polygonal mesh. By default, this is a disc
  60658. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60659. * * 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
  60660. * * 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
  60661. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60662. * * 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
  60663. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60664. * @param name defines the name of the mesh
  60665. * @param options defines the options used to create the mesh
  60666. * @param scene defines the hosting scene
  60667. * @returns the plane polygonal mesh
  60668. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60669. */
  60670. MeshBuilder.CreateDisc = function (name, options, scene) {
  60671. if (scene === void 0) { scene = null; }
  60672. var disc = new BABYLON.Mesh(name, scene);
  60673. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60674. disc._originalBuilderSideOrientation = options.sideOrientation;
  60675. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60676. vertexData.applyToMesh(disc, options.updatable);
  60677. return disc;
  60678. };
  60679. /**
  60680. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60681. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60682. * * 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`)
  60683. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60684. * * 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
  60685. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60686. * * 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
  60687. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60688. * @param name defines the name of the mesh
  60689. * @param options defines the options used to create the mesh
  60690. * @param scene defines the hosting scene
  60691. * @returns the icosahedron mesh
  60692. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60693. */
  60694. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60695. var sphere = new BABYLON.Mesh(name, scene);
  60696. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60697. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60698. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60699. vertexData.applyToMesh(sphere, options.updatable);
  60700. return sphere;
  60701. };
  60702. ;
  60703. /**
  60704. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60705. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60706. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60707. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60708. * * 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
  60709. * * 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
  60710. * * 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
  60711. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60712. * * 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
  60713. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60714. * * 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
  60715. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60716. * * 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
  60717. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  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. * @param name defines the name of the mesh
  60720. * @param options defines the options used to create the mesh
  60721. * @param scene defines the hosting scene
  60722. * @returns the ribbon mesh
  60723. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60724. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60725. */
  60726. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60727. if (scene === void 0) { scene = null; }
  60728. var pathArray = options.pathArray;
  60729. var closeArray = options.closeArray;
  60730. var closePath = options.closePath;
  60731. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60732. var instance = options.instance;
  60733. var updatable = options.updatable;
  60734. if (instance) { // existing ribbon instance update
  60735. // positionFunction : ribbon case
  60736. // only pathArray and sideOrientation parameters are taken into account for positions update
  60737. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60738. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60739. var positionFunction = function (positions) {
  60740. var minlg = pathArray[0].length;
  60741. var i = 0;
  60742. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60743. for (var si = 1; si <= ns; si++) {
  60744. for (var p = 0; p < pathArray.length; p++) {
  60745. var path = pathArray[p];
  60746. var l = path.length;
  60747. minlg = (minlg < l) ? minlg : l;
  60748. var j = 0;
  60749. while (j < minlg) {
  60750. positions[i] = path[j].x;
  60751. positions[i + 1] = path[j].y;
  60752. positions[i + 2] = path[j].z;
  60753. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60754. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60755. }
  60756. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60757. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60758. }
  60759. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60760. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60761. }
  60762. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60763. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60764. }
  60765. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60766. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60767. }
  60768. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60769. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60770. }
  60771. j++;
  60772. i += 3;
  60773. }
  60774. if (instance._closePath) {
  60775. positions[i] = path[0].x;
  60776. positions[i + 1] = path[0].y;
  60777. positions[i + 2] = path[0].z;
  60778. i += 3;
  60779. }
  60780. }
  60781. }
  60782. };
  60783. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60784. positionFunction(positions);
  60785. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60786. instance._boundingInfo.update(instance._worldMatrix);
  60787. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60788. if (options.colors) {
  60789. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60790. for (var c = 0; c < options.colors.length; c++) {
  60791. colors[c * 4] = options.colors[c].r;
  60792. colors[c * 4 + 1] = options.colors[c].g;
  60793. colors[c * 4 + 2] = options.colors[c].b;
  60794. colors[c * 4 + 3] = options.colors[c].a;
  60795. }
  60796. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60797. }
  60798. if (options.uvs) {
  60799. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60800. for (var i = 0; i < options.uvs.length; i++) {
  60801. uvs[i * 2] = options.uvs[i].x;
  60802. uvs[i * 2 + 1] = options.uvs[i].y;
  60803. }
  60804. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60805. }
  60806. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60807. var indices = instance.getIndices();
  60808. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60809. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60810. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60811. if (instance._closePath) {
  60812. var indexFirst = 0;
  60813. var indexLast = 0;
  60814. for (var p = 0; p < pathArray.length; p++) {
  60815. indexFirst = instance._idx[p] * 3;
  60816. if (p + 1 < pathArray.length) {
  60817. indexLast = (instance._idx[p + 1] - 1) * 3;
  60818. }
  60819. else {
  60820. indexLast = normals.length - 3;
  60821. }
  60822. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60823. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60824. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60825. normals[indexLast] = normals[indexFirst];
  60826. normals[indexLast + 1] = normals[indexFirst + 1];
  60827. normals[indexLast + 2] = normals[indexFirst + 2];
  60828. }
  60829. }
  60830. if (!(instance.areNormalsFrozen)) {
  60831. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60832. }
  60833. }
  60834. return instance;
  60835. }
  60836. else { // new ribbon creation
  60837. var ribbon = new BABYLON.Mesh(name, scene);
  60838. ribbon._originalBuilderSideOrientation = sideOrientation;
  60839. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60840. if (closePath) {
  60841. ribbon._idx = vertexData._idx;
  60842. }
  60843. ribbon._closePath = closePath;
  60844. ribbon._closeArray = closeArray;
  60845. vertexData.applyToMesh(ribbon, updatable);
  60846. return ribbon;
  60847. }
  60848. };
  60849. /**
  60850. * Creates a cylinder or a cone mesh
  60851. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60852. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60853. * * 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.
  60854. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60855. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60856. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60857. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60858. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60859. * * 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).
  60860. * * 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
  60861. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60862. * * 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
  60863. * * 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.
  60864. * * If `enclose` is false, a ring surface is one element.
  60865. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60866. * * 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
  60867. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60868. * * 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
  60869. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60870. * @param name defines the name of the mesh
  60871. * @param options defines the options used to create the mesh
  60872. * @param scene defines the hosting scene
  60873. * @returns the cylinder mesh
  60874. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60875. */
  60876. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60877. var cylinder = new BABYLON.Mesh(name, scene);
  60878. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60879. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60880. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60881. vertexData.applyToMesh(cylinder, options.updatable);
  60882. return cylinder;
  60883. };
  60884. /**
  60885. * Creates a torus mesh
  60886. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60887. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60888. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60889. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60890. * * 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
  60891. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60892. * @param name defines the name of the mesh
  60893. * @param options defines the options used to create the mesh
  60894. * @param scene defines the hosting scene
  60895. * @returns the torus mesh
  60896. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60897. */
  60898. MeshBuilder.CreateTorus = function (name, options, scene) {
  60899. var torus = new BABYLON.Mesh(name, scene);
  60900. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60901. torus._originalBuilderSideOrientation = options.sideOrientation;
  60902. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60903. vertexData.applyToMesh(torus, options.updatable);
  60904. return torus;
  60905. };
  60906. /**
  60907. * Creates a torus knot mesh
  60908. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60909. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60910. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60911. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60912. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60913. * * 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
  60914. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60915. * @param name defines the name of the mesh
  60916. * @param options defines the options used to create the mesh
  60917. * @param scene defines the hosting scene
  60918. * @returns the torus knot mesh
  60919. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60920. */
  60921. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60922. var torusKnot = new BABYLON.Mesh(name, scene);
  60923. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60924. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60925. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60926. vertexData.applyToMesh(torusKnot, options.updatable);
  60927. return torusKnot;
  60928. };
  60929. /**
  60930. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60931. * * 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
  60932. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60933. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60934. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60935. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60936. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60937. * * 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
  60938. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60939. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60940. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60941. * @param name defines the name of the new line system
  60942. * @param options defines the options used to create the line system
  60943. * @param scene defines the hosting scene
  60944. * @returns a new line system mesh
  60945. */
  60946. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60947. var instance = options.instance;
  60948. var lines = options.lines;
  60949. var colors = options.colors;
  60950. if (instance) { // lines update
  60951. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60952. var vertexColor;
  60953. var lineColors;
  60954. if (colors) {
  60955. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60956. }
  60957. var i = 0;
  60958. var c = 0;
  60959. for (var l = 0; l < lines.length; l++) {
  60960. var points = lines[l];
  60961. for (var p = 0; p < points.length; p++) {
  60962. positions[i] = points[p].x;
  60963. positions[i + 1] = points[p].y;
  60964. positions[i + 2] = points[p].z;
  60965. if (colors && vertexColor) {
  60966. lineColors = colors[l];
  60967. vertexColor[c] = lineColors[p].r;
  60968. vertexColor[c + 1] = lineColors[p].g;
  60969. vertexColor[c + 2] = lineColors[p].b;
  60970. vertexColor[c + 3] = lineColors[p].a;
  60971. c += 4;
  60972. }
  60973. i += 3;
  60974. }
  60975. }
  60976. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60977. if (colors && vertexColor) {
  60978. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60979. }
  60980. return instance;
  60981. }
  60982. // line system creation
  60983. var useVertexColor = (colors) ? true : false;
  60984. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60985. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60986. vertexData.applyToMesh(lineSystem, options.updatable);
  60987. return lineSystem;
  60988. };
  60989. /**
  60990. * Creates a line mesh
  60991. * 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
  60992. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60993. * * The parameter `points` is an array successive Vector3
  60994. * * 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
  60995. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60996. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60997. * * When updating an instance, remember that only point positions can change, not the number of points
  60998. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60999. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61000. * @param name defines the name of the new line system
  61001. * @param options defines the options used to create the line system
  61002. * @param scene defines the hosting scene
  61003. * @returns a new line mesh
  61004. */
  61005. MeshBuilder.CreateLines = function (name, options, scene) {
  61006. if (scene === void 0) { scene = null; }
  61007. var colors = (options.colors) ? [options.colors] : null;
  61008. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61009. return lines;
  61010. };
  61011. /**
  61012. * Creates a dashed line mesh
  61013. * * 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
  61014. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61015. * * The parameter `points` is an array successive Vector3
  61016. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61017. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61018. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61019. * * 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
  61020. * * When updating an instance, remember that only point positions can change, not the number of points
  61021. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61022. * @param name defines the name of the mesh
  61023. * @param options defines the options used to create the mesh
  61024. * @param scene defines the hosting scene
  61025. * @returns the dashed line mesh
  61026. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61027. */
  61028. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61029. if (scene === void 0) { scene = null; }
  61030. var points = options.points;
  61031. var instance = options.instance;
  61032. var gapSize = options.gapSize || 1;
  61033. var dashSize = options.dashSize || 3;
  61034. if (instance) { // dashed lines update
  61035. var positionFunction = function (positions) {
  61036. var curvect = BABYLON.Vector3.Zero();
  61037. var nbSeg = positions.length / 6;
  61038. var lg = 0;
  61039. var nb = 0;
  61040. var shft = 0;
  61041. var dashshft = 0;
  61042. var curshft = 0;
  61043. var p = 0;
  61044. var i = 0;
  61045. var j = 0;
  61046. for (i = 0; i < points.length - 1; i++) {
  61047. points[i + 1].subtractToRef(points[i], curvect);
  61048. lg += curvect.length();
  61049. }
  61050. shft = lg / nbSeg;
  61051. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61052. for (i = 0; i < points.length - 1; i++) {
  61053. points[i + 1].subtractToRef(points[i], curvect);
  61054. nb = Math.floor(curvect.length() / shft);
  61055. curvect.normalize();
  61056. j = 0;
  61057. while (j < nb && p < positions.length) {
  61058. curshft = shft * j;
  61059. positions[p] = points[i].x + curshft * curvect.x;
  61060. positions[p + 1] = points[i].y + curshft * curvect.y;
  61061. positions[p + 2] = points[i].z + curshft * curvect.z;
  61062. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61063. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61064. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61065. p += 6;
  61066. j++;
  61067. }
  61068. }
  61069. while (p < positions.length) {
  61070. positions[p] = points[i].x;
  61071. positions[p + 1] = points[i].y;
  61072. positions[p + 2] = points[i].z;
  61073. p += 3;
  61074. }
  61075. };
  61076. instance.updateMeshPositions(positionFunction, false);
  61077. return instance;
  61078. }
  61079. // dashed lines creation
  61080. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61081. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61082. vertexData.applyToMesh(dashedLines, options.updatable);
  61083. dashedLines.dashSize = dashSize;
  61084. dashedLines.gapSize = gapSize;
  61085. return dashedLines;
  61086. };
  61087. /**
  61088. * 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.
  61089. * * 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.
  61090. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61091. * * 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.
  61092. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61093. * * 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
  61094. * * 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
  61095. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61096. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61097. * * 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
  61098. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61099. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61100. * @param name defines the name of the mesh
  61101. * @param options defines the options used to create the mesh
  61102. * @param scene defines the hosting scene
  61103. * @returns the extruded shape mesh
  61104. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61105. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61106. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61107. */
  61108. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61109. if (scene === void 0) { scene = null; }
  61110. var path = options.path;
  61111. var shape = options.shape;
  61112. var scale = options.scale || 1;
  61113. var rotation = options.rotation || 0;
  61114. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61115. var updatable = options.updatable;
  61116. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61117. var instance = options.instance || null;
  61118. var invertUV = options.invertUV || false;
  61119. 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);
  61120. };
  61121. /**
  61122. * Creates an custom extruded shape mesh.
  61123. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61124. * * 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.
  61125. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61126. * * 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
  61127. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61128. * * 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
  61129. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61130. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61131. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61132. * * 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
  61133. * * 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
  61134. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61135. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61136. * * 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
  61137. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61138. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61139. * @param name defines the name of the mesh
  61140. * @param options defines the options used to create the mesh
  61141. * @param scene defines the hosting scene
  61142. * @returns the custom extruded shape mesh
  61143. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61144. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61145. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61146. */
  61147. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61148. var path = options.path;
  61149. var shape = options.shape;
  61150. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61151. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61152. var ribbonCloseArray = options.ribbonCloseArray || false;
  61153. var ribbonClosePath = options.ribbonClosePath || false;
  61154. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61155. var updatable = options.updatable;
  61156. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61157. var instance = options.instance;
  61158. var invertUV = options.invertUV || false;
  61159. 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);
  61160. };
  61161. /**
  61162. * Creates lathe mesh.
  61163. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61164. * * 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
  61165. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61166. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61167. * * 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
  61168. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61169. * * 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
  61170. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61171. * * 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
  61172. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61173. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61174. * @param name defines the name of the mesh
  61175. * @param options defines the options used to create the mesh
  61176. * @param scene defines the hosting scene
  61177. * @returns the lathe mesh
  61178. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61179. */
  61180. MeshBuilder.CreateLathe = function (name, options, scene) {
  61181. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61182. var closed = (options.closed === undefined) ? true : options.closed;
  61183. var shape = options.shape;
  61184. var radius = options.radius || 1;
  61185. var tessellation = options.tessellation || 64;
  61186. var updatable = options.updatable;
  61187. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61188. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61189. var pi2 = Math.PI * 2;
  61190. var paths = new Array();
  61191. var invertUV = options.invertUV || false;
  61192. var i = 0;
  61193. var p = 0;
  61194. var step = pi2 / tessellation * arc;
  61195. var rotated;
  61196. var path = new Array();
  61197. for (i = 0; i <= tessellation; i++) {
  61198. var path = [];
  61199. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61200. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61201. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61202. }
  61203. for (p = 0; p < shape.length; p++) {
  61204. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61205. path.push(rotated);
  61206. }
  61207. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61208. 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));
  61209. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61210. }
  61211. paths.push(path);
  61212. }
  61213. // lathe ribbon
  61214. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61215. return lathe;
  61216. };
  61217. /**
  61218. * Creates a plane mesh
  61219. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61220. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61221. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61222. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61223. * * 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
  61224. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61225. * @param name defines the name of the mesh
  61226. * @param options defines the options used to create the mesh
  61227. * @param scene defines the hosting scene
  61228. * @returns the plane mesh
  61229. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61230. */
  61231. MeshBuilder.CreatePlane = function (name, options, scene) {
  61232. var plane = new BABYLON.Mesh(name, scene);
  61233. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61234. plane._originalBuilderSideOrientation = options.sideOrientation;
  61235. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61236. vertexData.applyToMesh(plane, options.updatable);
  61237. if (options.sourcePlane) {
  61238. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61239. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61240. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61241. plane.rotate(vectorProduct, product);
  61242. }
  61243. return plane;
  61244. };
  61245. /**
  61246. * Creates a ground mesh
  61247. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61248. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61249. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61250. * @param name defines the name of the mesh
  61251. * @param options defines the options used to create the mesh
  61252. * @param scene defines the hosting scene
  61253. * @returns the ground mesh
  61254. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61255. */
  61256. MeshBuilder.CreateGround = function (name, options, scene) {
  61257. var ground = new BABYLON.GroundMesh(name, scene);
  61258. ground._setReady(false);
  61259. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61260. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61261. ground._width = options.width || 1;
  61262. ground._height = options.height || 1;
  61263. ground._maxX = ground._width / 2;
  61264. ground._maxZ = ground._height / 2;
  61265. ground._minX = -ground._maxX;
  61266. ground._minZ = -ground._maxZ;
  61267. var vertexData = BABYLON.VertexData.CreateGround(options);
  61268. vertexData.applyToMesh(ground, options.updatable);
  61269. ground._setReady(true);
  61270. return ground;
  61271. };
  61272. /**
  61273. * Creates a tiled ground mesh
  61274. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61275. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61276. * * 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
  61277. * * 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
  61278. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61279. * @param name defines the name of the mesh
  61280. * @param options defines the options used to create the mesh
  61281. * @param scene defines the hosting scene
  61282. * @returns the tiled ground mesh
  61283. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61284. */
  61285. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61286. var tiledGround = new BABYLON.Mesh(name, scene);
  61287. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61288. vertexData.applyToMesh(tiledGround, options.updatable);
  61289. return tiledGround;
  61290. };
  61291. /**
  61292. * Creates a ground mesh from a height map
  61293. * * The parameter `url` sets the URL of the height map image resource.
  61294. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61295. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61296. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61297. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61298. * * 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.
  61299. * * 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).
  61300. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61301. * @param name defines the name of the mesh
  61302. * @param url defines the url to the height map
  61303. * @param options defines the options used to create the mesh
  61304. * @param scene defines the hosting scene
  61305. * @returns the ground mesh
  61306. * @see http://doc.babylonjs.com/babylon101/height_map
  61307. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61308. */
  61309. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61310. var width = options.width || 10.0;
  61311. var height = options.height || 10.0;
  61312. var subdivisions = options.subdivisions || 1 | 0;
  61313. var minHeight = options.minHeight || 0.0;
  61314. var maxHeight = options.maxHeight || 1.0;
  61315. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61316. var updatable = options.updatable;
  61317. var onReady = options.onReady;
  61318. var ground = new BABYLON.GroundMesh(name, scene);
  61319. ground._subdivisionsX = subdivisions;
  61320. ground._subdivisionsY = subdivisions;
  61321. ground._width = width;
  61322. ground._height = height;
  61323. ground._maxX = ground._width / 2.0;
  61324. ground._maxZ = ground._height / 2.0;
  61325. ground._minX = -ground._maxX;
  61326. ground._minZ = -ground._maxZ;
  61327. ground._setReady(false);
  61328. var onload = function (img) {
  61329. // Getting height map data
  61330. var canvas = document.createElement("canvas");
  61331. var context = canvas.getContext("2d");
  61332. if (!context) {
  61333. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61334. }
  61335. if (scene.isDisposed) {
  61336. return;
  61337. }
  61338. var bufferWidth = img.width;
  61339. var bufferHeight = img.height;
  61340. canvas.width = bufferWidth;
  61341. canvas.height = bufferHeight;
  61342. context.drawImage(img, 0, 0);
  61343. // Create VertexData from map data
  61344. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61345. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61346. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61347. width: width, height: height,
  61348. subdivisions: subdivisions,
  61349. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61350. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61351. });
  61352. vertexData.applyToMesh(ground, updatable);
  61353. //execute ready callback, if set
  61354. if (onReady) {
  61355. onReady(ground);
  61356. }
  61357. ground._setReady(true);
  61358. };
  61359. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61360. return ground;
  61361. };
  61362. /**
  61363. * Creates a polygon mesh
  61364. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61365. * * 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
  61366. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61367. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61368. * * 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)
  61369. * * Remember you can only change the shape positions, not their number when updating a polygon
  61370. * @param name defines the name of the mesh
  61371. * @param options defines the options used to create the mesh
  61372. * @param scene defines the hosting scene
  61373. * @returns the polygon mesh
  61374. */
  61375. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61376. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61377. var shape = options.shape;
  61378. var holes = options.holes || [];
  61379. var depth = options.depth || 0;
  61380. var contours = [];
  61381. var hole = [];
  61382. for (var i = 0; i < shape.length; i++) {
  61383. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61384. }
  61385. var epsilon = 0.00000001;
  61386. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61387. contours.pop();
  61388. }
  61389. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61390. for (var hNb = 0; hNb < holes.length; hNb++) {
  61391. hole = [];
  61392. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61393. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61394. }
  61395. polygonTriangulation.addHole(hole);
  61396. }
  61397. var polygon = polygonTriangulation.build(options.updatable, depth);
  61398. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61399. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61400. vertexData.applyToMesh(polygon, options.updatable);
  61401. return polygon;
  61402. };
  61403. ;
  61404. /**
  61405. * Creates an extruded polygon mesh, with depth in the Y direction.
  61406. * * 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)
  61407. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61408. * @param name defines the name of the mesh
  61409. * @param options defines the options used to create the mesh
  61410. * @param scene defines the hosting scene
  61411. * @returns the polygon mesh
  61412. */
  61413. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61414. return MeshBuilder.CreatePolygon(name, options, scene);
  61415. };
  61416. ;
  61417. /**
  61418. * Creates a tube mesh.
  61419. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61420. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61421. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61422. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61423. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61424. * * 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)
  61425. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61426. * * 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
  61427. * * 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
  61428. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61429. * * 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
  61430. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61431. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61432. * @param name defines the name of the mesh
  61433. * @param options defines the options used to create the mesh
  61434. * @param scene defines the hosting scene
  61435. * @returns the tube mesh
  61436. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61437. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61438. */
  61439. MeshBuilder.CreateTube = function (name, options, scene) {
  61440. var path = options.path;
  61441. var instance = options.instance;
  61442. var radius = 1.0;
  61443. if (instance) {
  61444. radius = instance.radius;
  61445. }
  61446. if (options.radius !== undefined) {
  61447. radius = options.radius;
  61448. }
  61449. ;
  61450. var tessellation = options.tessellation || 64 | 0;
  61451. var radiusFunction = options.radiusFunction || null;
  61452. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61453. var invertUV = options.invertUV || false;
  61454. var updatable = options.updatable;
  61455. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61456. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61457. // tube geometry
  61458. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61459. var tangents = path3D.getTangents();
  61460. var normals = path3D.getNormals();
  61461. var distances = path3D.getDistances();
  61462. var pi2 = Math.PI * 2;
  61463. var step = pi2 / tessellation * arc;
  61464. var returnRadius = function () { return radius; };
  61465. var radiusFunctionFinal = radiusFunction || returnRadius;
  61466. var circlePath;
  61467. var rad;
  61468. var normal;
  61469. var rotated;
  61470. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61471. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61472. for (var i = 0; i < path.length; i++) {
  61473. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61474. circlePath = Array(); // current circle array
  61475. normal = normals[i]; // current normal
  61476. for (var t = 0; t < tessellation; t++) {
  61477. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61478. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61479. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61480. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61481. circlePath[t] = rotated;
  61482. }
  61483. circlePaths[index] = circlePath;
  61484. index++;
  61485. }
  61486. // cap
  61487. var capPath = function (nbPoints, pathIndex) {
  61488. var pointCap = Array();
  61489. for (var i = 0; i < nbPoints; i++) {
  61490. pointCap.push(path[pathIndex]);
  61491. }
  61492. return pointCap;
  61493. };
  61494. switch (cap) {
  61495. case BABYLON.Mesh.NO_CAP:
  61496. break;
  61497. case BABYLON.Mesh.CAP_START:
  61498. circlePaths[0] = capPath(tessellation, 0);
  61499. circlePaths[1] = circlePaths[2].slice(0);
  61500. break;
  61501. case BABYLON.Mesh.CAP_END:
  61502. circlePaths[index] = circlePaths[index - 1].slice(0);
  61503. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61504. break;
  61505. case BABYLON.Mesh.CAP_ALL:
  61506. circlePaths[0] = capPath(tessellation, 0);
  61507. circlePaths[1] = circlePaths[2].slice(0);
  61508. circlePaths[index] = circlePaths[index - 1].slice(0);
  61509. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61510. break;
  61511. default:
  61512. break;
  61513. }
  61514. return circlePaths;
  61515. };
  61516. var path3D;
  61517. var pathArray;
  61518. if (instance) { // tube update
  61519. var arc = options.arc || instance.arc;
  61520. path3D = (instance.path3D).update(path);
  61521. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61522. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61523. instance.path3D = path3D;
  61524. instance.pathArray = pathArray;
  61525. instance.arc = arc;
  61526. instance.radius = radius;
  61527. return instance;
  61528. }
  61529. // tube creation
  61530. path3D = new BABYLON.Path3D(path);
  61531. var newPathArray = new Array();
  61532. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61533. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61534. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61535. tube.pathArray = pathArray;
  61536. tube.path3D = path3D;
  61537. tube.tessellation = tessellation;
  61538. tube.cap = cap;
  61539. tube.arc = options.arc;
  61540. tube.radius = radius;
  61541. return tube;
  61542. };
  61543. /**
  61544. * Creates a polyhedron mesh
  61545. * * 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
  61546. * * The parameter `size` (positive float, default 1) sets the polygon size
  61547. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61548. * * 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`
  61549. * * 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
  61550. * * 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)`)
  61551. * * 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
  61552. * * 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
  61553. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61554. * * 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
  61555. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61556. * @param name defines the name of the mesh
  61557. * @param options defines the options used to create the mesh
  61558. * @param scene defines the hosting scene
  61559. * @returns the polyhedron mesh
  61560. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61561. */
  61562. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61563. var polyhedron = new BABYLON.Mesh(name, scene);
  61564. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61565. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61566. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61567. vertexData.applyToMesh(polyhedron, options.updatable);
  61568. return polyhedron;
  61569. };
  61570. /**
  61571. * Creates a decal mesh.
  61572. * 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
  61573. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61574. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61575. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61576. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61577. * @param name defines the name of the mesh
  61578. * @param sourceMesh defines the mesh where the decal must be applied
  61579. * @param options defines the options used to create the mesh
  61580. * @param scene defines the hosting scene
  61581. * @returns the decal mesh
  61582. * @see http://doc.babylonjs.com/how_to/decals
  61583. */
  61584. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61585. var indices = sourceMesh.getIndices();
  61586. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61587. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61588. var position = options.position || BABYLON.Vector3.Zero();
  61589. var normal = options.normal || BABYLON.Vector3.Up();
  61590. var size = options.size || BABYLON.Vector3.One();
  61591. var angle = options.angle || 0;
  61592. // Getting correct rotation
  61593. if (!normal) {
  61594. var target = new BABYLON.Vector3(0, 0, 1);
  61595. var camera = sourceMesh.getScene().activeCamera;
  61596. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61597. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61598. }
  61599. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61600. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61601. var pitch = Math.atan2(normal.y, len);
  61602. // Matrix
  61603. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61604. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61605. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61606. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61607. var vertexData = new BABYLON.VertexData();
  61608. vertexData.indices = [];
  61609. vertexData.positions = [];
  61610. vertexData.normals = [];
  61611. vertexData.uvs = [];
  61612. var currentVertexDataIndex = 0;
  61613. var extractDecalVector3 = function (indexId) {
  61614. var result = new BABYLON.PositionNormalVertex();
  61615. if (!indices || !positions || !normals) {
  61616. return result;
  61617. }
  61618. var vertexId = indices[indexId];
  61619. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61620. // Send vector to decal local world
  61621. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61622. // Get normal
  61623. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61624. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61625. return result;
  61626. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61627. var clip = function (vertices, axis) {
  61628. if (vertices.length === 0) {
  61629. return vertices;
  61630. }
  61631. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61632. var clipVertices = function (v0, v1) {
  61633. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61634. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61635. };
  61636. var result = new Array();
  61637. for (var index = 0; index < vertices.length; index += 3) {
  61638. var v1Out;
  61639. var v2Out;
  61640. var v3Out;
  61641. var total = 0;
  61642. var nV1 = null;
  61643. var nV2 = null;
  61644. var nV3 = null;
  61645. var nV4 = null;
  61646. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61647. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61648. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61649. v1Out = d1 > 0;
  61650. v2Out = d2 > 0;
  61651. v3Out = d3 > 0;
  61652. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61653. switch (total) {
  61654. case 0:
  61655. result.push(vertices[index]);
  61656. result.push(vertices[index + 1]);
  61657. result.push(vertices[index + 2]);
  61658. break;
  61659. case 1:
  61660. if (v1Out) {
  61661. nV1 = vertices[index + 1];
  61662. nV2 = vertices[index + 2];
  61663. nV3 = clipVertices(vertices[index], nV1);
  61664. nV4 = clipVertices(vertices[index], nV2);
  61665. }
  61666. if (v2Out) {
  61667. nV1 = vertices[index];
  61668. nV2 = vertices[index + 2];
  61669. nV3 = clipVertices(vertices[index + 1], nV1);
  61670. nV4 = clipVertices(vertices[index + 1], nV2);
  61671. result.push(nV3);
  61672. result.push(nV2.clone());
  61673. result.push(nV1.clone());
  61674. result.push(nV2.clone());
  61675. result.push(nV3.clone());
  61676. result.push(nV4);
  61677. break;
  61678. }
  61679. if (v3Out) {
  61680. nV1 = vertices[index];
  61681. nV2 = vertices[index + 1];
  61682. nV3 = clipVertices(vertices[index + 2], nV1);
  61683. nV4 = clipVertices(vertices[index + 2], nV2);
  61684. }
  61685. if (nV1 && nV2 && nV3 && nV4) {
  61686. result.push(nV1.clone());
  61687. result.push(nV2.clone());
  61688. result.push(nV3);
  61689. result.push(nV4);
  61690. result.push(nV3.clone());
  61691. result.push(nV2.clone());
  61692. }
  61693. break;
  61694. case 2:
  61695. if (!v1Out) {
  61696. nV1 = vertices[index].clone();
  61697. nV2 = clipVertices(nV1, vertices[index + 1]);
  61698. nV3 = clipVertices(nV1, vertices[index + 2]);
  61699. result.push(nV1);
  61700. result.push(nV2);
  61701. result.push(nV3);
  61702. }
  61703. if (!v2Out) {
  61704. nV1 = vertices[index + 1].clone();
  61705. nV2 = clipVertices(nV1, vertices[index + 2]);
  61706. nV3 = clipVertices(nV1, vertices[index]);
  61707. result.push(nV1);
  61708. result.push(nV2);
  61709. result.push(nV3);
  61710. }
  61711. if (!v3Out) {
  61712. nV1 = vertices[index + 2].clone();
  61713. nV2 = clipVertices(nV1, vertices[index]);
  61714. nV3 = clipVertices(nV1, vertices[index + 1]);
  61715. result.push(nV1);
  61716. result.push(nV2);
  61717. result.push(nV3);
  61718. }
  61719. break;
  61720. case 3:
  61721. break;
  61722. }
  61723. }
  61724. return result;
  61725. };
  61726. for (var index = 0; index < indices.length; index += 3) {
  61727. var faceVertices = new Array();
  61728. faceVertices.push(extractDecalVector3(index));
  61729. faceVertices.push(extractDecalVector3(index + 1));
  61730. faceVertices.push(extractDecalVector3(index + 2));
  61731. // Clip
  61732. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61733. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61734. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61735. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61736. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61737. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61738. if (faceVertices.length === 0) {
  61739. continue;
  61740. }
  61741. // Add UVs and get back to world
  61742. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61743. var vertex = faceVertices[vIndex];
  61744. //TODO check for Int32Array | Uint32Array | Uint16Array
  61745. vertexData.indices.push(currentVertexDataIndex);
  61746. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61747. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61748. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61749. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61750. currentVertexDataIndex++;
  61751. }
  61752. }
  61753. // Return mesh
  61754. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61755. vertexData.applyToMesh(decal);
  61756. decal.position = position.clone();
  61757. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61758. return decal;
  61759. };
  61760. // Privates
  61761. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61762. // extrusion geometry
  61763. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61764. var tangents = path3D.getTangents();
  61765. var normals = path3D.getNormals();
  61766. var binormals = path3D.getBinormals();
  61767. var distances = path3D.getDistances();
  61768. var angle = 0;
  61769. var returnScale = function () { return scale !== null ? scale : 1; };
  61770. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61771. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61772. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61773. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61774. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61775. for (var i = 0; i < curve.length; i++) {
  61776. var shapePath = new Array();
  61777. var angleStep = rotate(i, distances[i]);
  61778. var scaleRatio = scl(i, distances[i]);
  61779. for (var p = 0; p < shape.length; p++) {
  61780. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61781. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61782. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61783. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61784. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61785. shapePath[p] = rotated;
  61786. }
  61787. shapePaths[index] = shapePath;
  61788. angle += angleStep;
  61789. index++;
  61790. }
  61791. // cap
  61792. var capPath = function (shapePath) {
  61793. var pointCap = Array();
  61794. var barycenter = BABYLON.Vector3.Zero();
  61795. var i;
  61796. for (i = 0; i < shapePath.length; i++) {
  61797. barycenter.addInPlace(shapePath[i]);
  61798. }
  61799. barycenter.scaleInPlace(1.0 / shapePath.length);
  61800. for (i = 0; i < shapePath.length; i++) {
  61801. pointCap.push(barycenter);
  61802. }
  61803. return pointCap;
  61804. };
  61805. switch (cap) {
  61806. case BABYLON.Mesh.NO_CAP:
  61807. break;
  61808. case BABYLON.Mesh.CAP_START:
  61809. shapePaths[0] = capPath(shapePaths[2]);
  61810. shapePaths[1] = shapePaths[2];
  61811. break;
  61812. case BABYLON.Mesh.CAP_END:
  61813. shapePaths[index] = shapePaths[index - 1];
  61814. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61815. break;
  61816. case BABYLON.Mesh.CAP_ALL:
  61817. shapePaths[0] = capPath(shapePaths[2]);
  61818. shapePaths[1] = shapePaths[2];
  61819. shapePaths[index] = shapePaths[index - 1];
  61820. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61821. break;
  61822. default:
  61823. break;
  61824. }
  61825. return shapePaths;
  61826. };
  61827. var path3D;
  61828. var pathArray;
  61829. if (instance) { // instance update
  61830. path3D = (instance.path3D).update(curve);
  61831. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61832. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61833. return instance;
  61834. }
  61835. // extruded shape creation
  61836. path3D = new BABYLON.Path3D(curve);
  61837. var newShapePaths = new Array();
  61838. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61839. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61840. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61841. extrudedGeneric.pathArray = pathArray;
  61842. extrudedGeneric.path3D = path3D;
  61843. extrudedGeneric.cap = cap;
  61844. return extrudedGeneric;
  61845. };
  61846. return MeshBuilder;
  61847. }());
  61848. BABYLON.MeshBuilder = MeshBuilder;
  61849. })(BABYLON || (BABYLON = {}));
  61850. //# sourceMappingURL=babylon.meshBuilder.js.map
  61851. var BABYLON;
  61852. (function (BABYLON) {
  61853. /**
  61854. * Draco compression (https://google.github.io/draco/)
  61855. *
  61856. * This class wraps the Draco module.
  61857. *
  61858. * **Encoder**
  61859. *
  61860. * The encoder is not currently implemented.
  61861. *
  61862. * **Decoder**
  61863. *
  61864. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  61865. *
  61866. * To update the configuration, use the following code:
  61867. * ```javascript
  61868. * BABYLON.DracoCompression.Configuration = {
  61869. * decoder: {
  61870. * wasmUrl: "<url to the WebAssembly library>",
  61871. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  61872. * fallbackUrl: "<url to the fallback JavaScript library>",
  61873. * }
  61874. * };
  61875. * ```
  61876. *
  61877. * 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.
  61878. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  61879. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  61880. *
  61881. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  61882. * ```javascript
  61883. * var dracoCompression = new BABYLON.DracoCompression();
  61884. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  61885. * [BABYLON.VertexBuffer.PositionKind]: 0
  61886. * });
  61887. * ```
  61888. *
  61889. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  61890. */
  61891. var DracoCompression = /** @class */ (function () {
  61892. /**
  61893. * Constructor
  61894. */
  61895. function DracoCompression() {
  61896. }
  61897. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61898. /**
  61899. * Returns true if the decoder is available.
  61900. */
  61901. get: function () {
  61902. if (typeof DracoDecoderModule !== "undefined") {
  61903. return true;
  61904. }
  61905. var decoder = DracoCompression.Configuration.decoder;
  61906. if (decoder) {
  61907. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61908. return true;
  61909. }
  61910. if (decoder.fallbackUrl) {
  61911. return true;
  61912. }
  61913. }
  61914. return false;
  61915. },
  61916. enumerable: true,
  61917. configurable: true
  61918. });
  61919. /**
  61920. * Stop all async operations and release resources.
  61921. */
  61922. DracoCompression.prototype.dispose = function () {
  61923. };
  61924. /**
  61925. * Decode Draco compressed mesh data to vertex data.
  61926. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  61927. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61928. * @returns A promise that resolves with the decoded vertex data
  61929. */
  61930. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61931. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  61932. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61933. var module = wrappedModule.module;
  61934. var vertexData = new BABYLON.VertexData();
  61935. var buffer = new module.DecoderBuffer();
  61936. buffer.Init(dataView, dataView.byteLength);
  61937. var decoder = new module.Decoder();
  61938. var geometry;
  61939. var status;
  61940. try {
  61941. var type = decoder.GetEncodedGeometryType(buffer);
  61942. switch (type) {
  61943. case module.TRIANGULAR_MESH:
  61944. geometry = new module.Mesh();
  61945. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61946. break;
  61947. case module.POINT_CLOUD:
  61948. geometry = new module.PointCloud();
  61949. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61950. break;
  61951. default:
  61952. throw new Error("Invalid geometry type " + type);
  61953. }
  61954. if (!status.ok() || !geometry.ptr) {
  61955. throw new Error(status.error_msg());
  61956. }
  61957. var numPoints = geometry.num_points();
  61958. if (type === module.TRIANGULAR_MESH) {
  61959. var numFaces = geometry.num_faces();
  61960. var faceIndices = new module.DracoInt32Array();
  61961. try {
  61962. var indices = new Uint32Array(numFaces * 3);
  61963. for (var i = 0; i < numFaces; i++) {
  61964. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61965. var offset = i * 3;
  61966. indices[offset + 0] = faceIndices.GetValue(0);
  61967. indices[offset + 1] = faceIndices.GetValue(1);
  61968. indices[offset + 2] = faceIndices.GetValue(2);
  61969. }
  61970. vertexData.indices = indices;
  61971. }
  61972. finally {
  61973. module.destroy(faceIndices);
  61974. }
  61975. }
  61976. for (var kind in attributes) {
  61977. var uniqueId = attributes[kind];
  61978. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61979. var dracoData = new module.DracoFloat32Array();
  61980. try {
  61981. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61982. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61983. for (var i = 0; i < babylonData.length; i++) {
  61984. babylonData[i] = dracoData.GetValue(i);
  61985. }
  61986. vertexData.set(babylonData, kind);
  61987. }
  61988. finally {
  61989. module.destroy(dracoData);
  61990. }
  61991. }
  61992. }
  61993. finally {
  61994. if (geometry) {
  61995. module.destroy(geometry);
  61996. }
  61997. module.destroy(decoder);
  61998. module.destroy(buffer);
  61999. }
  62000. return vertexData;
  62001. });
  62002. };
  62003. DracoCompression._GetDecoderModule = function () {
  62004. if (!DracoCompression._DecoderModulePromise) {
  62005. var promise = null;
  62006. var config_1 = {};
  62007. if (typeof DracoDecoderModule !== "undefined") {
  62008. promise = Promise.resolve();
  62009. }
  62010. else {
  62011. var decoder = DracoCompression.Configuration.decoder;
  62012. if (decoder) {
  62013. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62014. promise = Promise.all([
  62015. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62016. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62017. config_1.wasmBinary = data;
  62018. })
  62019. ]);
  62020. }
  62021. else if (decoder.fallbackUrl) {
  62022. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62023. }
  62024. }
  62025. }
  62026. if (!promise) {
  62027. throw new Error("Draco decoder module is not available");
  62028. }
  62029. DracoCompression._DecoderModulePromise = promise.then(function () {
  62030. return new Promise(function (resolve) {
  62031. config_1.onModuleLoaded = function (decoderModule) {
  62032. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62033. resolve({ module: decoderModule });
  62034. };
  62035. DracoDecoderModule(config_1);
  62036. });
  62037. });
  62038. }
  62039. return DracoCompression._DecoderModulePromise;
  62040. };
  62041. DracoCompression._LoadScriptAsync = function (url) {
  62042. return new Promise(function (resolve, reject) {
  62043. BABYLON.Tools.LoadScript(url, function () {
  62044. resolve();
  62045. }, function (message) {
  62046. reject(new Error(message));
  62047. });
  62048. });
  62049. };
  62050. DracoCompression._LoadFileAsync = function (url) {
  62051. return new Promise(function (resolve, reject) {
  62052. BABYLON.Tools.LoadFile(url, function (data) {
  62053. resolve(data);
  62054. }, undefined, undefined, true, function (request, exception) {
  62055. reject(exception);
  62056. });
  62057. });
  62058. };
  62059. /**
  62060. * The configuration. Defaults to the following urls:
  62061. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62062. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62063. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62064. */
  62065. DracoCompression.Configuration = {
  62066. decoder: {
  62067. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62068. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62069. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62070. }
  62071. };
  62072. return DracoCompression;
  62073. }());
  62074. BABYLON.DracoCompression = DracoCompression;
  62075. })(BABYLON || (BABYLON = {}));
  62076. //# sourceMappingURL=babylon.dracoCompression.js.map
  62077. var BABYLON;
  62078. (function (BABYLON) {
  62079. var AudioEngine = /** @class */ (function () {
  62080. function AudioEngine() {
  62081. this._audioContext = null;
  62082. this._audioContextInitialized = false;
  62083. this.canUseWebAudio = false;
  62084. this.WarnedWebAudioUnsupported = false;
  62085. this.unlocked = false;
  62086. this.isMP3supported = false;
  62087. this.isOGGsupported = false;
  62088. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62089. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62090. this.canUseWebAudio = true;
  62091. }
  62092. var audioElem = document.createElement('audio');
  62093. try {
  62094. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62095. this.isMP3supported = true;
  62096. }
  62097. }
  62098. catch (e) {
  62099. // protect error during capability check.
  62100. }
  62101. try {
  62102. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62103. this.isOGGsupported = true;
  62104. }
  62105. }
  62106. catch (e) {
  62107. // protect error during capability check.
  62108. }
  62109. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62110. this._unlockiOSaudio();
  62111. }
  62112. else {
  62113. this.unlocked = true;
  62114. }
  62115. }
  62116. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62117. get: function () {
  62118. if (!this._audioContextInitialized) {
  62119. this._initializeAudioContext();
  62120. }
  62121. return this._audioContext;
  62122. },
  62123. enumerable: true,
  62124. configurable: true
  62125. });
  62126. AudioEngine.prototype._unlockiOSaudio = function () {
  62127. var _this = this;
  62128. var unlockaudio = function () {
  62129. if (!_this.audioContext) {
  62130. return;
  62131. }
  62132. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62133. var source = _this.audioContext.createBufferSource();
  62134. source.buffer = buffer;
  62135. source.connect(_this.audioContext.destination);
  62136. source.start(0);
  62137. setTimeout(function () {
  62138. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62139. _this.unlocked = true;
  62140. window.removeEventListener('touchend', unlockaudio, false);
  62141. if (_this.onAudioUnlocked) {
  62142. _this.onAudioUnlocked();
  62143. }
  62144. }
  62145. }, 0);
  62146. };
  62147. window.addEventListener('touchend', unlockaudio, false);
  62148. };
  62149. AudioEngine.prototype._initializeAudioContext = function () {
  62150. try {
  62151. if (this.canUseWebAudio) {
  62152. this._audioContext = new AudioContext();
  62153. // create a global volume gain node
  62154. this.masterGain = this._audioContext.createGain();
  62155. this.masterGain.gain.value = 1;
  62156. this.masterGain.connect(this._audioContext.destination);
  62157. this._audioContextInitialized = true;
  62158. }
  62159. }
  62160. catch (e) {
  62161. this.canUseWebAudio = false;
  62162. BABYLON.Tools.Error("Web Audio: " + e.message);
  62163. }
  62164. };
  62165. AudioEngine.prototype.dispose = function () {
  62166. if (this.canUseWebAudio && this._audioContextInitialized) {
  62167. if (this._connectedAnalyser && this._audioContext) {
  62168. this._connectedAnalyser.stopDebugCanvas();
  62169. this._connectedAnalyser.dispose();
  62170. this.masterGain.disconnect();
  62171. this.masterGain.connect(this._audioContext.destination);
  62172. this._connectedAnalyser = null;
  62173. }
  62174. this.masterGain.gain.value = 1;
  62175. }
  62176. this.WarnedWebAudioUnsupported = false;
  62177. };
  62178. AudioEngine.prototype.getGlobalVolume = function () {
  62179. if (this.canUseWebAudio && this._audioContextInitialized) {
  62180. return this.masterGain.gain.value;
  62181. }
  62182. else {
  62183. return -1;
  62184. }
  62185. };
  62186. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62187. if (this.canUseWebAudio && this._audioContextInitialized) {
  62188. this.masterGain.gain.value = newVolume;
  62189. }
  62190. };
  62191. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62192. if (this._connectedAnalyser) {
  62193. this._connectedAnalyser.stopDebugCanvas();
  62194. }
  62195. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62196. this._connectedAnalyser = analyser;
  62197. this.masterGain.disconnect();
  62198. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62199. }
  62200. };
  62201. return AudioEngine;
  62202. }());
  62203. BABYLON.AudioEngine = AudioEngine;
  62204. })(BABYLON || (BABYLON = {}));
  62205. //# sourceMappingURL=babylon.audioEngine.js.map
  62206. var BABYLON;
  62207. (function (BABYLON) {
  62208. var Sound = /** @class */ (function () {
  62209. /**
  62210. * Create a sound and attach it to a scene
  62211. * @param name Name of your sound
  62212. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62213. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62214. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62215. */
  62216. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62217. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62218. var _this = this;
  62219. this.autoplay = false;
  62220. this.loop = false;
  62221. this.useCustomAttenuation = false;
  62222. this.spatialSound = false;
  62223. this.refDistance = 1;
  62224. this.rolloffFactor = 1;
  62225. this.maxDistance = 100;
  62226. this.distanceModel = "linear";
  62227. this._panningModel = "equalpower";
  62228. this._playbackRate = 1;
  62229. this._streaming = false;
  62230. this._startTime = 0;
  62231. this._startOffset = 0;
  62232. this._position = BABYLON.Vector3.Zero();
  62233. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62234. this._volume = 1;
  62235. this._isReadyToPlay = false;
  62236. this.isPlaying = false;
  62237. this.isPaused = false;
  62238. this._isDirectional = false;
  62239. // Used if you'd like to create a directional sound.
  62240. // If not set, the sound will be omnidirectional
  62241. this._coneInnerAngle = 360;
  62242. this._coneOuterAngle = 360;
  62243. this._coneOuterGain = 0;
  62244. this._isOutputConnected = false;
  62245. this._urlType = "Unknown";
  62246. this.name = name;
  62247. this._scene = scene;
  62248. this._readyToPlayCallback = readyToPlayCallback;
  62249. // Default custom attenuation function is a linear attenuation
  62250. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62251. if (currentDistance < maxDistance) {
  62252. return currentVolume * (1 - currentDistance / maxDistance);
  62253. }
  62254. else {
  62255. return 0;
  62256. }
  62257. };
  62258. if (options) {
  62259. this.autoplay = options.autoplay || false;
  62260. this.loop = options.loop || false;
  62261. // if volume === 0, we need another way to check this option
  62262. if (options.volume !== undefined) {
  62263. this._volume = options.volume;
  62264. }
  62265. this.spatialSound = options.spatialSound || false;
  62266. this.maxDistance = options.maxDistance || 100;
  62267. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62268. this.rolloffFactor = options.rolloffFactor || 1;
  62269. this.refDistance = options.refDistance || 1;
  62270. this.distanceModel = options.distanceModel || "linear";
  62271. this._playbackRate = options.playbackRate || 1;
  62272. this._streaming = options.streaming || false;
  62273. }
  62274. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62275. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62276. this._soundGain.gain.value = this._volume;
  62277. this._inputAudioNode = this._soundGain;
  62278. this._ouputAudioNode = this._soundGain;
  62279. if (this.spatialSound) {
  62280. this._createSpatialParameters();
  62281. }
  62282. this._scene.mainSoundTrack.AddSound(this);
  62283. var validParameter = true;
  62284. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62285. if (urlOrArrayBuffer) {
  62286. try {
  62287. if (typeof (urlOrArrayBuffer) === "string") {
  62288. this._urlType = "String";
  62289. }
  62290. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62291. this._urlType = "ArrayBuffer";
  62292. }
  62293. else if (urlOrArrayBuffer instanceof MediaStream) {
  62294. this._urlType = "MediaStream";
  62295. }
  62296. else if (Array.isArray(urlOrArrayBuffer)) {
  62297. this._urlType = "Array";
  62298. }
  62299. var urls = [];
  62300. var codecSupportedFound = false;
  62301. switch (this._urlType) {
  62302. case "MediaStream":
  62303. this._streaming = true;
  62304. this._isReadyToPlay = true;
  62305. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62306. if (this.autoplay) {
  62307. this.play();
  62308. }
  62309. if (this._readyToPlayCallback) {
  62310. this._readyToPlayCallback();
  62311. }
  62312. break;
  62313. case "ArrayBuffer":
  62314. if (urlOrArrayBuffer.byteLength > 0) {
  62315. codecSupportedFound = true;
  62316. this._soundLoaded(urlOrArrayBuffer);
  62317. }
  62318. break;
  62319. case "String":
  62320. urls.push(urlOrArrayBuffer);
  62321. case "Array":
  62322. if (urls.length === 0)
  62323. urls = urlOrArrayBuffer;
  62324. // If we found a supported format, we load it immediately and stop the loop
  62325. for (var i = 0; i < urls.length; i++) {
  62326. var url = urls[i];
  62327. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62328. codecSupportedFound = true;
  62329. }
  62330. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62331. codecSupportedFound = true;
  62332. }
  62333. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62334. codecSupportedFound = true;
  62335. }
  62336. if (url.indexOf("blob:") !== -1) {
  62337. codecSupportedFound = true;
  62338. }
  62339. if (codecSupportedFound) {
  62340. // Loading sound using XHR2
  62341. if (!this._streaming) {
  62342. this._scene._loadFile(url, function (data) {
  62343. _this._soundLoaded(data);
  62344. }, undefined, true, true, function (exception) {
  62345. if (exception) {
  62346. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62347. }
  62348. BABYLON.Tools.Error("Sound creation aborted.");
  62349. _this._scene.mainSoundTrack.RemoveSound(_this);
  62350. });
  62351. }
  62352. // Streaming sound using HTML5 Audio tag
  62353. else {
  62354. this._htmlAudioElement = new Audio(url);
  62355. this._htmlAudioElement.controls = false;
  62356. this._htmlAudioElement.loop = this.loop;
  62357. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62358. this._htmlAudioElement.preload = "auto";
  62359. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62360. _this._isReadyToPlay = true;
  62361. if (_this.autoplay) {
  62362. _this.play();
  62363. }
  62364. if (_this._readyToPlayCallback) {
  62365. _this._readyToPlayCallback();
  62366. }
  62367. });
  62368. document.body.appendChild(this._htmlAudioElement);
  62369. }
  62370. break;
  62371. }
  62372. }
  62373. break;
  62374. default:
  62375. validParameter = false;
  62376. break;
  62377. }
  62378. if (!validParameter) {
  62379. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62380. }
  62381. else {
  62382. if (!codecSupportedFound) {
  62383. this._isReadyToPlay = true;
  62384. // Simulating a ready to play event to avoid breaking code path
  62385. if (this._readyToPlayCallback) {
  62386. window.setTimeout(function () {
  62387. if (_this._readyToPlayCallback) {
  62388. _this._readyToPlayCallback();
  62389. }
  62390. }, 1000);
  62391. }
  62392. }
  62393. }
  62394. }
  62395. catch (ex) {
  62396. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62397. this._scene.mainSoundTrack.RemoveSound(this);
  62398. }
  62399. }
  62400. }
  62401. else {
  62402. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62403. this._scene.mainSoundTrack.AddSound(this);
  62404. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62405. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62406. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62407. }
  62408. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62409. if (this._readyToPlayCallback) {
  62410. window.setTimeout(function () {
  62411. if (_this._readyToPlayCallback) {
  62412. _this._readyToPlayCallback();
  62413. }
  62414. }, 1000);
  62415. }
  62416. }
  62417. }
  62418. Sound.prototype.dispose = function () {
  62419. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62420. if (this.isPlaying) {
  62421. this.stop();
  62422. }
  62423. this._isReadyToPlay = false;
  62424. if (this.soundTrackId === -1) {
  62425. this._scene.mainSoundTrack.RemoveSound(this);
  62426. }
  62427. else {
  62428. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62429. }
  62430. if (this._soundGain) {
  62431. this._soundGain.disconnect();
  62432. this._soundGain = null;
  62433. }
  62434. if (this._soundPanner) {
  62435. this._soundPanner.disconnect();
  62436. this._soundPanner = null;
  62437. }
  62438. if (this._soundSource) {
  62439. this._soundSource.disconnect();
  62440. this._soundSource = null;
  62441. }
  62442. this._audioBuffer = null;
  62443. if (this._htmlAudioElement) {
  62444. this._htmlAudioElement.pause();
  62445. this._htmlAudioElement.src = "";
  62446. document.body.removeChild(this._htmlAudioElement);
  62447. }
  62448. if (this._streamingSource) {
  62449. this._streamingSource.disconnect();
  62450. }
  62451. if (this._connectedMesh && this._registerFunc) {
  62452. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62453. this._connectedMesh = null;
  62454. }
  62455. }
  62456. };
  62457. Sound.prototype.isReady = function () {
  62458. return this._isReadyToPlay;
  62459. };
  62460. Sound.prototype._soundLoaded = function (audioData) {
  62461. var _this = this;
  62462. if (!BABYLON.Engine.audioEngine.audioContext) {
  62463. return;
  62464. }
  62465. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62466. _this._audioBuffer = buffer;
  62467. _this._isReadyToPlay = true;
  62468. if (_this.autoplay) {
  62469. _this.play();
  62470. }
  62471. if (_this._readyToPlayCallback) {
  62472. _this._readyToPlayCallback();
  62473. }
  62474. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62475. };
  62476. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62477. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62478. this._audioBuffer = audioBuffer;
  62479. this._isReadyToPlay = true;
  62480. }
  62481. };
  62482. Sound.prototype.updateOptions = function (options) {
  62483. if (options) {
  62484. this.loop = options.loop || this.loop;
  62485. this.maxDistance = options.maxDistance || this.maxDistance;
  62486. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62487. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62488. this.refDistance = options.refDistance || this.refDistance;
  62489. this.distanceModel = options.distanceModel || this.distanceModel;
  62490. this._playbackRate = options.playbackRate || this._playbackRate;
  62491. this._updateSpatialParameters();
  62492. if (this.isPlaying) {
  62493. if (this._streaming && this._htmlAudioElement) {
  62494. this._htmlAudioElement.playbackRate = this._playbackRate;
  62495. }
  62496. else {
  62497. if (this._soundSource) {
  62498. this._soundSource.playbackRate.value = this._playbackRate;
  62499. }
  62500. }
  62501. }
  62502. }
  62503. };
  62504. Sound.prototype._createSpatialParameters = function () {
  62505. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62506. if (this._scene.headphone) {
  62507. this._panningModel = "HRTF";
  62508. }
  62509. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62510. this._updateSpatialParameters();
  62511. this._soundPanner.connect(this._ouputAudioNode);
  62512. this._inputAudioNode = this._soundPanner;
  62513. }
  62514. };
  62515. Sound.prototype._updateSpatialParameters = function () {
  62516. if (this.spatialSound && this._soundPanner) {
  62517. if (this.useCustomAttenuation) {
  62518. // Tricks to disable in a way embedded Web Audio attenuation
  62519. this._soundPanner.distanceModel = "linear";
  62520. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62521. this._soundPanner.refDistance = 1;
  62522. this._soundPanner.rolloffFactor = 1;
  62523. this._soundPanner.panningModel = this._panningModel;
  62524. }
  62525. else {
  62526. this._soundPanner.distanceModel = this.distanceModel;
  62527. this._soundPanner.maxDistance = this.maxDistance;
  62528. this._soundPanner.refDistance = this.refDistance;
  62529. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62530. this._soundPanner.panningModel = this._panningModel;
  62531. }
  62532. }
  62533. };
  62534. Sound.prototype.switchPanningModelToHRTF = function () {
  62535. this._panningModel = "HRTF";
  62536. this._switchPanningModel();
  62537. };
  62538. Sound.prototype.switchPanningModelToEqualPower = function () {
  62539. this._panningModel = "equalpower";
  62540. this._switchPanningModel();
  62541. };
  62542. Sound.prototype._switchPanningModel = function () {
  62543. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62544. this._soundPanner.panningModel = this._panningModel;
  62545. }
  62546. };
  62547. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62548. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62549. if (this._isOutputConnected) {
  62550. this._ouputAudioNode.disconnect();
  62551. }
  62552. this._ouputAudioNode.connect(soundTrackAudioNode);
  62553. this._isOutputConnected = true;
  62554. }
  62555. };
  62556. /**
  62557. * Transform this sound into a directional source
  62558. * @param coneInnerAngle Size of the inner cone in degree
  62559. * @param coneOuterAngle Size of the outer cone in degree
  62560. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62561. */
  62562. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62563. if (coneOuterAngle < coneInnerAngle) {
  62564. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62565. return;
  62566. }
  62567. this._coneInnerAngle = coneInnerAngle;
  62568. this._coneOuterAngle = coneOuterAngle;
  62569. this._coneOuterGain = coneOuterGain;
  62570. this._isDirectional = true;
  62571. if (this.isPlaying && this.loop) {
  62572. this.stop();
  62573. this.play();
  62574. }
  62575. };
  62576. Sound.prototype.setPosition = function (newPosition) {
  62577. this._position = newPosition;
  62578. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62579. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62580. }
  62581. };
  62582. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62583. this._localDirection = newLocalDirection;
  62584. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62585. this._updateDirection();
  62586. }
  62587. };
  62588. Sound.prototype._updateDirection = function () {
  62589. if (!this._connectedMesh || !this._soundPanner) {
  62590. return;
  62591. }
  62592. var mat = this._connectedMesh.getWorldMatrix();
  62593. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62594. direction.normalize();
  62595. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62596. };
  62597. Sound.prototype.updateDistanceFromListener = function () {
  62598. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62599. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62600. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62601. }
  62602. };
  62603. Sound.prototype.setAttenuationFunction = function (callback) {
  62604. this._customAttenuationFunction = callback;
  62605. };
  62606. /**
  62607. * Play the sound
  62608. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62609. * @param offset (optional) Start the sound setting it at a specific time
  62610. */
  62611. Sound.prototype.play = function (time, offset) {
  62612. var _this = this;
  62613. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62614. try {
  62615. if (this._startOffset < 0) {
  62616. time = -this._startOffset;
  62617. this._startOffset = 0;
  62618. }
  62619. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62620. if (!this._soundSource || !this._streamingSource) {
  62621. if (this.spatialSound && this._soundPanner) {
  62622. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62623. if (this._isDirectional) {
  62624. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62625. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62626. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62627. if (this._connectedMesh) {
  62628. this._updateDirection();
  62629. }
  62630. else {
  62631. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62632. }
  62633. }
  62634. }
  62635. }
  62636. if (this._streaming) {
  62637. if (!this._streamingSource) {
  62638. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62639. this._htmlAudioElement.onended = function () { _this._onended(); };
  62640. this._htmlAudioElement.playbackRate = this._playbackRate;
  62641. }
  62642. this._streamingSource.disconnect();
  62643. this._streamingSource.connect(this._inputAudioNode);
  62644. if (this._htmlAudioElement) {
  62645. this._htmlAudioElement.play();
  62646. }
  62647. }
  62648. else {
  62649. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62650. this._soundSource.buffer = this._audioBuffer;
  62651. this._soundSource.connect(this._inputAudioNode);
  62652. this._soundSource.loop = this.loop;
  62653. this._soundSource.playbackRate.value = this._playbackRate;
  62654. this._soundSource.onended = function () { _this._onended(); };
  62655. if (this._soundSource.buffer) {
  62656. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62657. }
  62658. }
  62659. this._startTime = startTime;
  62660. this.isPlaying = true;
  62661. this.isPaused = false;
  62662. }
  62663. catch (ex) {
  62664. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62665. }
  62666. }
  62667. };
  62668. Sound.prototype._onended = function () {
  62669. this.isPlaying = false;
  62670. if (this.onended) {
  62671. this.onended();
  62672. }
  62673. };
  62674. /**
  62675. * Stop the sound
  62676. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62677. */
  62678. Sound.prototype.stop = function (time) {
  62679. if (this.isPlaying) {
  62680. if (this._streaming) {
  62681. if (this._htmlAudioElement) {
  62682. this._htmlAudioElement.pause();
  62683. // Test needed for Firefox or it will generate an Invalid State Error
  62684. if (this._htmlAudioElement.currentTime > 0) {
  62685. this._htmlAudioElement.currentTime = 0;
  62686. }
  62687. }
  62688. else {
  62689. this._streamingSource.disconnect();
  62690. }
  62691. }
  62692. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62693. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62694. this._soundSource.stop(stopTime);
  62695. this._soundSource.onended = function () { };
  62696. if (!this.isPaused) {
  62697. this._startOffset = 0;
  62698. }
  62699. }
  62700. this.isPlaying = false;
  62701. }
  62702. };
  62703. Sound.prototype.pause = function () {
  62704. if (this.isPlaying) {
  62705. this.isPaused = true;
  62706. if (this._streaming) {
  62707. if (this._htmlAudioElement) {
  62708. this._htmlAudioElement.pause();
  62709. }
  62710. else {
  62711. this._streamingSource.disconnect();
  62712. }
  62713. }
  62714. else if (BABYLON.Engine.audioEngine.audioContext) {
  62715. this.stop(0);
  62716. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62717. }
  62718. }
  62719. };
  62720. Sound.prototype.setVolume = function (newVolume, time) {
  62721. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62722. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62723. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62724. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62725. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62726. }
  62727. else {
  62728. this._soundGain.gain.value = newVolume;
  62729. }
  62730. }
  62731. this._volume = newVolume;
  62732. };
  62733. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62734. this._playbackRate = newPlaybackRate;
  62735. if (this.isPlaying) {
  62736. if (this._streaming && this._htmlAudioElement) {
  62737. this._htmlAudioElement.playbackRate = this._playbackRate;
  62738. }
  62739. else if (this._soundSource) {
  62740. this._soundSource.playbackRate.value = this._playbackRate;
  62741. }
  62742. }
  62743. };
  62744. Sound.prototype.getVolume = function () {
  62745. return this._volume;
  62746. };
  62747. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62748. var _this = this;
  62749. if (this._connectedMesh && this._registerFunc) {
  62750. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62751. this._registerFunc = null;
  62752. }
  62753. this._connectedMesh = meshToConnectTo;
  62754. if (!this.spatialSound) {
  62755. this.spatialSound = true;
  62756. this._createSpatialParameters();
  62757. if (this.isPlaying && this.loop) {
  62758. this.stop();
  62759. this.play();
  62760. }
  62761. }
  62762. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62763. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62764. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62765. };
  62766. Sound.prototype.detachFromMesh = function () {
  62767. if (this._connectedMesh && this._registerFunc) {
  62768. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62769. this._registerFunc = null;
  62770. this._connectedMesh = null;
  62771. }
  62772. };
  62773. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62774. if (!node.getBoundingInfo) {
  62775. return;
  62776. }
  62777. var mesh = node;
  62778. var boundingInfo = mesh.getBoundingInfo();
  62779. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62780. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62781. this._updateDirection();
  62782. }
  62783. };
  62784. Sound.prototype.clone = function () {
  62785. var _this = this;
  62786. if (!this._streaming) {
  62787. var setBufferAndRun = function () {
  62788. if (_this._isReadyToPlay) {
  62789. clonedSound._audioBuffer = _this.getAudioBuffer();
  62790. clonedSound._isReadyToPlay = true;
  62791. if (clonedSound.autoplay) {
  62792. clonedSound.play();
  62793. }
  62794. }
  62795. else {
  62796. window.setTimeout(setBufferAndRun, 300);
  62797. }
  62798. };
  62799. var currentOptions = {
  62800. autoplay: this.autoplay, loop: this.loop,
  62801. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62802. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62803. refDistance: this.refDistance, distanceModel: this.distanceModel
  62804. };
  62805. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62806. if (this.useCustomAttenuation) {
  62807. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62808. }
  62809. clonedSound.setPosition(this._position);
  62810. clonedSound.setPlaybackRate(this._playbackRate);
  62811. setBufferAndRun();
  62812. return clonedSound;
  62813. }
  62814. // Can't clone a streaming sound
  62815. else {
  62816. return null;
  62817. }
  62818. };
  62819. Sound.prototype.getAudioBuffer = function () {
  62820. return this._audioBuffer;
  62821. };
  62822. Sound.prototype.serialize = function () {
  62823. var serializationObject = {
  62824. name: this.name,
  62825. url: this.name,
  62826. autoplay: this.autoplay,
  62827. loop: this.loop,
  62828. volume: this._volume,
  62829. spatialSound: this.spatialSound,
  62830. maxDistance: this.maxDistance,
  62831. rolloffFactor: this.rolloffFactor,
  62832. refDistance: this.refDistance,
  62833. distanceModel: this.distanceModel,
  62834. playbackRate: this._playbackRate,
  62835. panningModel: this._panningModel,
  62836. soundTrackId: this.soundTrackId
  62837. };
  62838. if (this.spatialSound) {
  62839. if (this._connectedMesh)
  62840. serializationObject.connectedMeshId = this._connectedMesh.id;
  62841. serializationObject.position = this._position.asArray();
  62842. serializationObject.refDistance = this.refDistance;
  62843. serializationObject.distanceModel = this.distanceModel;
  62844. serializationObject.isDirectional = this._isDirectional;
  62845. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62846. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62847. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62848. serializationObject.coneOuterGain = this._coneOuterGain;
  62849. }
  62850. return serializationObject;
  62851. };
  62852. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62853. var soundName = parsedSound.name;
  62854. var soundUrl;
  62855. if (parsedSound.url) {
  62856. soundUrl = rootUrl + parsedSound.url;
  62857. }
  62858. else {
  62859. soundUrl = rootUrl + soundName;
  62860. }
  62861. var options = {
  62862. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62863. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62864. rolloffFactor: parsedSound.rolloffFactor,
  62865. refDistance: parsedSound.refDistance,
  62866. distanceModel: parsedSound.distanceModel,
  62867. playbackRate: parsedSound.playbackRate
  62868. };
  62869. var newSound;
  62870. if (!sourceSound) {
  62871. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62872. scene._addPendingData(newSound);
  62873. }
  62874. else {
  62875. var setBufferAndRun = function () {
  62876. if (sourceSound._isReadyToPlay) {
  62877. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62878. newSound._isReadyToPlay = true;
  62879. if (newSound.autoplay) {
  62880. newSound.play();
  62881. }
  62882. }
  62883. else {
  62884. window.setTimeout(setBufferAndRun, 300);
  62885. }
  62886. };
  62887. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62888. setBufferAndRun();
  62889. }
  62890. if (parsedSound.position) {
  62891. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62892. newSound.setPosition(soundPosition);
  62893. }
  62894. if (parsedSound.isDirectional) {
  62895. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62896. if (parsedSound.localDirectionToMesh) {
  62897. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62898. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62899. }
  62900. }
  62901. if (parsedSound.connectedMeshId) {
  62902. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62903. if (connectedMesh) {
  62904. newSound.attachToMesh(connectedMesh);
  62905. }
  62906. }
  62907. return newSound;
  62908. };
  62909. return Sound;
  62910. }());
  62911. BABYLON.Sound = Sound;
  62912. })(BABYLON || (BABYLON = {}));
  62913. //# sourceMappingURL=babylon.sound.js.map
  62914. var BABYLON;
  62915. (function (BABYLON) {
  62916. var SoundTrack = /** @class */ (function () {
  62917. function SoundTrack(scene, options) {
  62918. this.id = -1;
  62919. this._isMainTrack = false;
  62920. this._isInitialized = false;
  62921. this._scene = scene;
  62922. this.soundCollection = new Array();
  62923. this._options = options;
  62924. if (!this._isMainTrack) {
  62925. this._scene.soundTracks.push(this);
  62926. this.id = this._scene.soundTracks.length - 1;
  62927. }
  62928. }
  62929. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62930. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62931. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62932. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62933. if (this._options) {
  62934. if (this._options.volume) {
  62935. this._outputAudioNode.gain.value = this._options.volume;
  62936. }
  62937. if (this._options.mainTrack) {
  62938. this._isMainTrack = this._options.mainTrack;
  62939. }
  62940. }
  62941. this._isInitialized = true;
  62942. }
  62943. };
  62944. SoundTrack.prototype.dispose = function () {
  62945. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62946. if (this._connectedAnalyser) {
  62947. this._connectedAnalyser.stopDebugCanvas();
  62948. }
  62949. while (this.soundCollection.length) {
  62950. this.soundCollection[0].dispose();
  62951. }
  62952. if (this._outputAudioNode) {
  62953. this._outputAudioNode.disconnect();
  62954. }
  62955. this._outputAudioNode = null;
  62956. }
  62957. };
  62958. SoundTrack.prototype.AddSound = function (sound) {
  62959. if (!this._isInitialized) {
  62960. this._initializeSoundTrackAudioGraph();
  62961. }
  62962. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62963. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62964. }
  62965. if (sound.soundTrackId) {
  62966. if (sound.soundTrackId === -1) {
  62967. this._scene.mainSoundTrack.RemoveSound(sound);
  62968. }
  62969. else {
  62970. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62971. }
  62972. }
  62973. this.soundCollection.push(sound);
  62974. sound.soundTrackId = this.id;
  62975. };
  62976. SoundTrack.prototype.RemoveSound = function (sound) {
  62977. var index = this.soundCollection.indexOf(sound);
  62978. if (index !== -1) {
  62979. this.soundCollection.splice(index, 1);
  62980. }
  62981. };
  62982. SoundTrack.prototype.setVolume = function (newVolume) {
  62983. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62984. this._outputAudioNode.gain.value = newVolume;
  62985. }
  62986. };
  62987. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62988. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62989. for (var i = 0; i < this.soundCollection.length; i++) {
  62990. this.soundCollection[i].switchPanningModelToHRTF();
  62991. }
  62992. }
  62993. };
  62994. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62995. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62996. for (var i = 0; i < this.soundCollection.length; i++) {
  62997. this.soundCollection[i].switchPanningModelToEqualPower();
  62998. }
  62999. }
  63000. };
  63001. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63002. if (this._connectedAnalyser) {
  63003. this._connectedAnalyser.stopDebugCanvas();
  63004. }
  63005. this._connectedAnalyser = analyser;
  63006. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63007. this._outputAudioNode.disconnect();
  63008. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63009. }
  63010. };
  63011. return SoundTrack;
  63012. }());
  63013. BABYLON.SoundTrack = SoundTrack;
  63014. })(BABYLON || (BABYLON = {}));
  63015. //# sourceMappingURL=babylon.soundtrack.js.map
  63016. var BABYLON;
  63017. (function (BABYLON) {
  63018. /**
  63019. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63020. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63021. */
  63022. var Analyser = /** @class */ (function () {
  63023. /**
  63024. * Creates a new analyser
  63025. * @param scene defines hosting scene
  63026. */
  63027. function Analyser(scene) {
  63028. /**
  63029. * Gets or sets the smoothing
  63030. * @ignorenaming
  63031. */
  63032. this.SMOOTHING = 0.75;
  63033. /**
  63034. * Gets or sets the FFT table size
  63035. * @ignorenaming
  63036. */
  63037. this.FFT_SIZE = 512;
  63038. /**
  63039. * Gets or sets the bar graph amplitude
  63040. * @ignorenaming
  63041. */
  63042. this.BARGRAPHAMPLITUDE = 256;
  63043. /**
  63044. * Gets or sets the position of the debug canvas
  63045. * @ignorenaming
  63046. */
  63047. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63048. /**
  63049. * Gets or sets the debug canvas size
  63050. * @ignorenaming
  63051. */
  63052. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63053. this._scene = scene;
  63054. this._audioEngine = BABYLON.Engine.audioEngine;
  63055. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63056. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63057. this._webAudioAnalyser.minDecibels = -140;
  63058. this._webAudioAnalyser.maxDecibels = 0;
  63059. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63060. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63061. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63062. }
  63063. }
  63064. /**
  63065. * Get the number of data values you will have to play with for the visualization
  63066. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63067. * @returns a number
  63068. */
  63069. Analyser.prototype.getFrequencyBinCount = function () {
  63070. if (this._audioEngine.canUseWebAudio) {
  63071. return this._webAudioAnalyser.frequencyBinCount;
  63072. }
  63073. else {
  63074. return 0;
  63075. }
  63076. };
  63077. /**
  63078. * Gets the current frequency data as a byte array
  63079. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63080. * @returns a Uint8Array
  63081. */
  63082. Analyser.prototype.getByteFrequencyData = function () {
  63083. if (this._audioEngine.canUseWebAudio) {
  63084. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63085. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63086. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63087. }
  63088. return this._byteFreqs;
  63089. };
  63090. /**
  63091. * Gets the current waveform as a byte array
  63092. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63093. * @returns a Uint8Array
  63094. */
  63095. Analyser.prototype.getByteTimeDomainData = function () {
  63096. if (this._audioEngine.canUseWebAudio) {
  63097. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63098. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63099. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63100. }
  63101. return this._byteTime;
  63102. };
  63103. /**
  63104. * Gets the current frequency data as a float array
  63105. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63106. * @returns a Float32Array
  63107. */
  63108. Analyser.prototype.getFloatFrequencyData = function () {
  63109. if (this._audioEngine.canUseWebAudio) {
  63110. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63111. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63112. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63113. }
  63114. return this._floatFreqs;
  63115. };
  63116. /**
  63117. * Renders the debug canvas
  63118. */
  63119. Analyser.prototype.drawDebugCanvas = function () {
  63120. var _this = this;
  63121. if (this._audioEngine.canUseWebAudio) {
  63122. if (!this._debugCanvas) {
  63123. this._debugCanvas = document.createElement("canvas");
  63124. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63125. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63126. this._debugCanvas.style.position = "absolute";
  63127. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63128. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63129. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63130. document.body.appendChild(this._debugCanvas);
  63131. this._registerFunc = function () {
  63132. _this.drawDebugCanvas();
  63133. };
  63134. this._scene.registerBeforeRender(this._registerFunc);
  63135. }
  63136. if (this._registerFunc && this._debugCanvasContext) {
  63137. var workingArray = this.getByteFrequencyData();
  63138. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63139. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63140. // Draw the frequency domain chart.
  63141. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63142. var value = workingArray[i];
  63143. var percent = value / this.BARGRAPHAMPLITUDE;
  63144. var height = this.DEBUGCANVASSIZE.height * percent;
  63145. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63146. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63147. var hue = i / this.getFrequencyBinCount() * 360;
  63148. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63149. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63150. }
  63151. }
  63152. }
  63153. };
  63154. /**
  63155. * Stops rendering the debug canvas and removes it
  63156. */
  63157. Analyser.prototype.stopDebugCanvas = function () {
  63158. if (this._debugCanvas) {
  63159. if (this._registerFunc) {
  63160. this._scene.unregisterBeforeRender(this._registerFunc);
  63161. this._registerFunc = null;
  63162. }
  63163. document.body.removeChild(this._debugCanvas);
  63164. this._debugCanvas = null;
  63165. this._debugCanvasContext = null;
  63166. }
  63167. };
  63168. /**
  63169. * Connects two audio nodes
  63170. * @param inputAudioNode defines first node to connect
  63171. * @param outputAudioNode defines second node to connect
  63172. */
  63173. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63174. if (this._audioEngine.canUseWebAudio) {
  63175. inputAudioNode.connect(this._webAudioAnalyser);
  63176. this._webAudioAnalyser.connect(outputAudioNode);
  63177. }
  63178. };
  63179. /**
  63180. * Releases all associated resources
  63181. */
  63182. Analyser.prototype.dispose = function () {
  63183. if (this._audioEngine.canUseWebAudio) {
  63184. this._webAudioAnalyser.disconnect();
  63185. }
  63186. };
  63187. return Analyser;
  63188. }());
  63189. BABYLON.Analyser = Analyser;
  63190. })(BABYLON || (BABYLON = {}));
  63191. //# sourceMappingURL=babylon.analyser.js.map
  63192. var BABYLON;
  63193. (function (BABYLON) {
  63194. var CubeTexture = /** @class */ (function (_super) {
  63195. __extends(CubeTexture, _super);
  63196. /**
  63197. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63198. * as prefiltered data.
  63199. * @param rootUrl defines the url of the texture or the root name of the six images
  63200. * @param scene defines the scene the texture is attached to
  63201. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63202. * @param noMipmap defines if mipmaps should be created or not
  63203. * @param files defines the six files to load for the different faces
  63204. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63205. * @param onError defines a callback triggered in case of error during load
  63206. * @param format defines the internal format to use for the texture once loaded
  63207. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63208. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63209. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63210. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63211. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63212. * @return the cube texture
  63213. */
  63214. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63215. if (extensions === void 0) { extensions = null; }
  63216. if (noMipmap === void 0) { noMipmap = false; }
  63217. if (files === void 0) { files = null; }
  63218. if (onLoad === void 0) { onLoad = null; }
  63219. if (onError === void 0) { onError = null; }
  63220. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63221. if (prefiltered === void 0) { prefiltered = false; }
  63222. if (forcedExtension === void 0) { forcedExtension = null; }
  63223. if (createPolynomials === void 0) { createPolynomials = false; }
  63224. if (lodScale === void 0) { lodScale = 0.8; }
  63225. if (lodOffset === void 0) { lodOffset = 0; }
  63226. var _this = _super.call(this, scene) || this;
  63227. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63228. /**
  63229. * Gets or sets the center of the bounding box associated with the cube texture
  63230. * It must define where the camera used to render the texture was set
  63231. */
  63232. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63233. _this._rotationY = 0;
  63234. /** @hidden */
  63235. _this._prefiltered = false;
  63236. _this.name = rootUrl;
  63237. _this.url = rootUrl;
  63238. _this._noMipmap = noMipmap;
  63239. _this.hasAlpha = false;
  63240. _this._format = format;
  63241. _this.isCube = true;
  63242. _this._textureMatrix = BABYLON.Matrix.Identity();
  63243. _this._createPolynomials = createPolynomials;
  63244. if (!rootUrl && !files) {
  63245. return _this;
  63246. }
  63247. var lastDot = rootUrl.lastIndexOf(".");
  63248. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63249. var isDDS = (extension === ".dds");
  63250. var isEnv = (extension === ".env");
  63251. if (isEnv) {
  63252. _this.gammaSpace = false;
  63253. _this._prefiltered = false;
  63254. }
  63255. else {
  63256. _this._prefiltered = prefiltered;
  63257. if (prefiltered) {
  63258. _this.gammaSpace = false;
  63259. }
  63260. }
  63261. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63262. if (!files) {
  63263. if (!isEnv && !isDDS && !extensions) {
  63264. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63265. }
  63266. files = [];
  63267. if (extensions) {
  63268. for (var index = 0; index < extensions.length; index++) {
  63269. files.push(rootUrl + extensions[index]);
  63270. }
  63271. }
  63272. }
  63273. _this._files = files;
  63274. if (!_this._texture) {
  63275. if (!scene.useDelayedTextureLoading) {
  63276. if (prefiltered) {
  63277. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63278. }
  63279. else {
  63280. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63281. }
  63282. }
  63283. else {
  63284. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63285. }
  63286. }
  63287. else if (onLoad) {
  63288. if (_this._texture.isReady) {
  63289. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63290. }
  63291. else {
  63292. _this._texture.onLoadedObservable.add(onLoad);
  63293. }
  63294. }
  63295. return _this;
  63296. }
  63297. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63298. get: function () {
  63299. return this._boundingBoxSize;
  63300. },
  63301. /**
  63302. * Gets or sets the size of the bounding box associated with the cube texture
  63303. * When defined, the cubemap will switch to local mode
  63304. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63305. * @example https://www.babylonjs-playground.com/#RNASML
  63306. */
  63307. set: function (value) {
  63308. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63309. return;
  63310. }
  63311. this._boundingBoxSize = value;
  63312. var scene = this.getScene();
  63313. if (scene) {
  63314. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63315. }
  63316. },
  63317. enumerable: true,
  63318. configurable: true
  63319. });
  63320. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63321. /**
  63322. * Gets texture matrix rotation angle around Y axis radians.
  63323. */
  63324. get: function () {
  63325. return this._rotationY;
  63326. },
  63327. /**
  63328. * Sets texture matrix rotation angle around Y axis in radians.
  63329. */
  63330. set: function (value) {
  63331. this._rotationY = value;
  63332. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63333. },
  63334. enumerable: true,
  63335. configurable: true
  63336. });
  63337. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63338. var rootUrlKey = "";
  63339. files.forEach(function (url) { return rootUrlKey += url; });
  63340. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63341. };
  63342. /**
  63343. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63344. * @param url defines the url of the prefiltered texture
  63345. * @param scene defines the scene the texture is attached to
  63346. * @param forcedExtension defines the extension of the file if different from the url
  63347. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63348. * @return the prefiltered texture
  63349. */
  63350. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63351. if (forcedExtension === void 0) { forcedExtension = null; }
  63352. if (createPolynomials === void 0) { createPolynomials = true; }
  63353. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63354. };
  63355. // Methods
  63356. CubeTexture.prototype.delayLoad = function () {
  63357. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63358. return;
  63359. }
  63360. var scene = this.getScene();
  63361. if (!scene) {
  63362. return;
  63363. }
  63364. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63365. this._texture = this._getFromCache(this.url, this._noMipmap);
  63366. if (!this._texture) {
  63367. if (this._prefiltered) {
  63368. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63369. }
  63370. else {
  63371. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63372. }
  63373. }
  63374. };
  63375. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63376. return this._textureMatrix;
  63377. };
  63378. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63379. this._textureMatrix = value;
  63380. };
  63381. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63382. var texture = BABYLON.SerializationHelper.Parse(function () {
  63383. var prefiltered = false;
  63384. if (parsedTexture.prefiltered) {
  63385. prefiltered = parsedTexture.prefiltered;
  63386. }
  63387. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63388. }, parsedTexture, scene);
  63389. // Local Cubemaps
  63390. if (parsedTexture.boundingBoxPosition) {
  63391. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63392. }
  63393. if (parsedTexture.boundingBoxSize) {
  63394. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63395. }
  63396. // Animations
  63397. if (parsedTexture.animations) {
  63398. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63399. var parsedAnimation = parsedTexture.animations[animationIndex];
  63400. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63401. }
  63402. }
  63403. return texture;
  63404. };
  63405. CubeTexture.prototype.clone = function () {
  63406. var _this = this;
  63407. return BABYLON.SerializationHelper.Clone(function () {
  63408. var scene = _this.getScene();
  63409. if (!scene) {
  63410. return _this;
  63411. }
  63412. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63413. }, this);
  63414. };
  63415. __decorate([
  63416. BABYLON.serialize("rotationY")
  63417. ], CubeTexture.prototype, "_rotationY", void 0);
  63418. return CubeTexture;
  63419. }(BABYLON.BaseTexture));
  63420. BABYLON.CubeTexture = CubeTexture;
  63421. })(BABYLON || (BABYLON = {}));
  63422. //# sourceMappingURL=babylon.cubeTexture.js.map
  63423. var BABYLON;
  63424. (function (BABYLON) {
  63425. var RenderTargetTexture = /** @class */ (function (_super) {
  63426. __extends(RenderTargetTexture, _super);
  63427. /**
  63428. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63429. * or used a shadow, depth texture...
  63430. * @param name The friendly name of the texture
  63431. * @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)
  63432. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63433. * @param generateMipMaps True if mip maps need to be generated after render.
  63434. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63435. * @param type The type of the buffer in the RTT (int, half float, float...)
  63436. * @param isCube True if a cube texture needs to be created
  63437. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63438. * @param generateDepthBuffer True to generate a depth buffer
  63439. * @param generateStencilBuffer True to generate a stencil buffer
  63440. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63441. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63442. */
  63443. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63444. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63445. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63446. if (isCube === void 0) { isCube = false; }
  63447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63448. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63449. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63450. if (isMulti === void 0) { isMulti = false; }
  63451. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63452. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63453. _this.isCube = isCube;
  63454. /**
  63455. * Use this list to define the list of mesh you want to render.
  63456. */
  63457. _this.renderList = new Array();
  63458. _this.renderParticles = true;
  63459. _this.renderSprites = false;
  63460. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63461. _this.ignoreCameraViewport = false;
  63462. // Events
  63463. /**
  63464. * An event triggered when the texture is unbind.
  63465. */
  63466. _this.onBeforeBindObservable = new BABYLON.Observable();
  63467. /**
  63468. * An event triggered when the texture is unbind.
  63469. */
  63470. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63471. /**
  63472. * An event triggered before rendering the texture
  63473. */
  63474. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63475. /**
  63476. * An event triggered after rendering the texture
  63477. */
  63478. _this.onAfterRenderObservable = new BABYLON.Observable();
  63479. /**
  63480. * An event triggered after the texture clear
  63481. */
  63482. _this.onClearObservable = new BABYLON.Observable();
  63483. _this._currentRefreshId = -1;
  63484. _this._refreshRate = 1;
  63485. _this._samples = 1;
  63486. /**
  63487. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63488. * It must define where the camera used to render the texture is set
  63489. */
  63490. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63491. scene = _this.getScene();
  63492. if (!scene) {
  63493. return _this;
  63494. }
  63495. _this._engine = scene.getEngine();
  63496. _this.name = name;
  63497. _this.isRenderTarget = true;
  63498. _this._initialSizeParameter = size;
  63499. _this._processSizeParameter(size);
  63500. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63501. });
  63502. _this._generateMipMaps = generateMipMaps ? true : false;
  63503. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63504. // Rendering groups
  63505. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63506. if (isMulti) {
  63507. return _this;
  63508. }
  63509. _this._renderTargetOptions = {
  63510. generateMipMaps: generateMipMaps,
  63511. type: type,
  63512. format: format,
  63513. samplingMode: samplingMode,
  63514. generateDepthBuffer: generateDepthBuffer,
  63515. generateStencilBuffer: generateStencilBuffer
  63516. };
  63517. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63518. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63519. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63520. }
  63521. if (isCube) {
  63522. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63523. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63524. _this._textureMatrix = BABYLON.Matrix.Identity();
  63525. }
  63526. else {
  63527. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63528. }
  63529. return _this;
  63530. }
  63531. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63532. get: function () {
  63533. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63534. },
  63535. enumerable: true,
  63536. configurable: true
  63537. });
  63538. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63539. get: function () {
  63540. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63541. },
  63542. enumerable: true,
  63543. configurable: true
  63544. });
  63545. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63546. get: function () {
  63547. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63548. },
  63549. enumerable: true,
  63550. configurable: true
  63551. });
  63552. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63553. set: function (callback) {
  63554. if (this._onAfterUnbindObserver) {
  63555. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63556. }
  63557. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63558. },
  63559. enumerable: true,
  63560. configurable: true
  63561. });
  63562. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63563. set: function (callback) {
  63564. if (this._onBeforeRenderObserver) {
  63565. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63566. }
  63567. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63568. },
  63569. enumerable: true,
  63570. configurable: true
  63571. });
  63572. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63573. set: function (callback) {
  63574. if (this._onAfterRenderObserver) {
  63575. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63576. }
  63577. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63578. },
  63579. enumerable: true,
  63580. configurable: true
  63581. });
  63582. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63583. set: function (callback) {
  63584. if (this._onClearObserver) {
  63585. this.onClearObservable.remove(this._onClearObserver);
  63586. }
  63587. this._onClearObserver = this.onClearObservable.add(callback);
  63588. },
  63589. enumerable: true,
  63590. configurable: true
  63591. });
  63592. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63593. get: function () {
  63594. return this._renderTargetOptions;
  63595. },
  63596. enumerable: true,
  63597. configurable: true
  63598. });
  63599. RenderTargetTexture.prototype._onRatioRescale = function () {
  63600. if (this._sizeRatio) {
  63601. this.resize(this._initialSizeParameter);
  63602. }
  63603. };
  63604. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63605. get: function () {
  63606. return this._boundingBoxSize;
  63607. },
  63608. /**
  63609. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63610. * When defined, the cubemap will switch to local mode
  63611. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63612. * @example https://www.babylonjs-playground.com/#RNASML
  63613. */
  63614. set: function (value) {
  63615. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63616. return;
  63617. }
  63618. this._boundingBoxSize = value;
  63619. var scene = this.getScene();
  63620. if (scene) {
  63621. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63622. }
  63623. },
  63624. enumerable: true,
  63625. configurable: true
  63626. });
  63627. /**
  63628. * Creates a depth stencil texture.
  63629. * This is only available in WebGL 2 or with the depth texture extension available.
  63630. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63631. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63632. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63633. */
  63634. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63635. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63636. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63637. if (generateStencil === void 0) { generateStencil = false; }
  63638. if (!this.getScene()) {
  63639. return;
  63640. }
  63641. var engine = this.getScene().getEngine();
  63642. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63643. bilinearFiltering: bilinearFiltering,
  63644. comparisonFunction: comparisonFunction,
  63645. generateStencil: generateStencil,
  63646. isCube: this.isCube
  63647. });
  63648. engine.setFrameBufferDepthStencilTexture(this);
  63649. };
  63650. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63651. if (size.ratio) {
  63652. this._sizeRatio = size.ratio;
  63653. this._size = {
  63654. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63655. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63656. };
  63657. }
  63658. else {
  63659. this._size = size;
  63660. }
  63661. };
  63662. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63663. get: function () {
  63664. return this._samples;
  63665. },
  63666. set: function (value) {
  63667. if (this._samples === value) {
  63668. return;
  63669. }
  63670. var scene = this.getScene();
  63671. if (!scene) {
  63672. return;
  63673. }
  63674. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63675. },
  63676. enumerable: true,
  63677. configurable: true
  63678. });
  63679. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63680. this._currentRefreshId = -1;
  63681. };
  63682. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63683. get: function () {
  63684. return this._refreshRate;
  63685. },
  63686. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63687. set: function (value) {
  63688. this._refreshRate = value;
  63689. this.resetRefreshCounter();
  63690. },
  63691. enumerable: true,
  63692. configurable: true
  63693. });
  63694. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63695. if (!this._postProcessManager) {
  63696. var scene = this.getScene();
  63697. if (!scene) {
  63698. return;
  63699. }
  63700. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63701. this._postProcesses = new Array();
  63702. }
  63703. this._postProcesses.push(postProcess);
  63704. this._postProcesses[0].autoClear = false;
  63705. };
  63706. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63707. if (!this._postProcesses) {
  63708. return;
  63709. }
  63710. if (dispose) {
  63711. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63712. var postProcess = _a[_i];
  63713. postProcess.dispose();
  63714. }
  63715. }
  63716. this._postProcesses = [];
  63717. };
  63718. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63719. if (!this._postProcesses) {
  63720. return;
  63721. }
  63722. var index = this._postProcesses.indexOf(postProcess);
  63723. if (index === -1) {
  63724. return;
  63725. }
  63726. this._postProcesses.splice(index, 1);
  63727. if (this._postProcesses.length > 0) {
  63728. this._postProcesses[0].autoClear = false;
  63729. }
  63730. };
  63731. RenderTargetTexture.prototype._shouldRender = function () {
  63732. if (this._currentRefreshId === -1) { // At least render once
  63733. this._currentRefreshId = 1;
  63734. return true;
  63735. }
  63736. if (this.refreshRate === this._currentRefreshId) {
  63737. this._currentRefreshId = 1;
  63738. return true;
  63739. }
  63740. this._currentRefreshId++;
  63741. return false;
  63742. };
  63743. RenderTargetTexture.prototype.getRenderSize = function () {
  63744. if (this._size.width) {
  63745. return this._size.width;
  63746. }
  63747. return this._size;
  63748. };
  63749. RenderTargetTexture.prototype.getRenderWidth = function () {
  63750. if (this._size.width) {
  63751. return this._size.width;
  63752. }
  63753. return this._size;
  63754. };
  63755. RenderTargetTexture.prototype.getRenderHeight = function () {
  63756. if (this._size.width) {
  63757. return this._size.height;
  63758. }
  63759. return this._size;
  63760. };
  63761. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63762. get: function () {
  63763. return true;
  63764. },
  63765. enumerable: true,
  63766. configurable: true
  63767. });
  63768. RenderTargetTexture.prototype.scale = function (ratio) {
  63769. var newSize = this.getRenderSize() * ratio;
  63770. this.resize(newSize);
  63771. };
  63772. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63773. if (this.isCube) {
  63774. return this._textureMatrix;
  63775. }
  63776. return _super.prototype.getReflectionTextureMatrix.call(this);
  63777. };
  63778. RenderTargetTexture.prototype.resize = function (size) {
  63779. this.releaseInternalTexture();
  63780. var scene = this.getScene();
  63781. if (!scene) {
  63782. return;
  63783. }
  63784. this._processSizeParameter(size);
  63785. if (this.isCube) {
  63786. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63787. }
  63788. else {
  63789. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63790. }
  63791. };
  63792. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63793. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63794. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63795. var scene = this.getScene();
  63796. if (!scene) {
  63797. return;
  63798. }
  63799. var engine = scene.getEngine();
  63800. if (this.useCameraPostProcesses !== undefined) {
  63801. useCameraPostProcess = this.useCameraPostProcesses;
  63802. }
  63803. if (this._waitingRenderList) {
  63804. this.renderList = [];
  63805. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63806. var id = this._waitingRenderList[index];
  63807. var mesh_1 = scene.getMeshByID(id);
  63808. if (mesh_1) {
  63809. this.renderList.push(mesh_1);
  63810. }
  63811. }
  63812. delete this._waitingRenderList;
  63813. }
  63814. // Is predicate defined?
  63815. if (this.renderListPredicate) {
  63816. if (this.renderList) {
  63817. this.renderList.splice(0); // Clear previous renderList
  63818. }
  63819. else {
  63820. this.renderList = [];
  63821. }
  63822. var scene = this.getScene();
  63823. if (!scene) {
  63824. return;
  63825. }
  63826. var sceneMeshes = scene.meshes;
  63827. for (var index = 0; index < sceneMeshes.length; index++) {
  63828. var mesh = sceneMeshes[index];
  63829. if (this.renderListPredicate(mesh)) {
  63830. this.renderList.push(mesh);
  63831. }
  63832. }
  63833. }
  63834. this.onBeforeBindObservable.notifyObservers(this);
  63835. // Set custom projection.
  63836. // Needs to be before binding to prevent changing the aspect ratio.
  63837. var camera;
  63838. if (this.activeCamera) {
  63839. camera = this.activeCamera;
  63840. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63841. if (this.activeCamera !== scene.activeCamera) {
  63842. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63843. }
  63844. }
  63845. else {
  63846. camera = scene.activeCamera;
  63847. if (camera) {
  63848. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63849. }
  63850. }
  63851. // Prepare renderingManager
  63852. this._renderingManager.reset();
  63853. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63854. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63855. var sceneRenderId = scene.getRenderId();
  63856. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63857. var mesh = currentRenderList[meshIndex];
  63858. if (mesh) {
  63859. if (!mesh.isReady(this.refreshRate === 0)) {
  63860. this.resetRefreshCounter();
  63861. continue;
  63862. }
  63863. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63864. var isMasked = void 0;
  63865. if (!this.renderList && camera) {
  63866. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63867. }
  63868. else {
  63869. isMasked = false;
  63870. }
  63871. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63872. mesh._activate(sceneRenderId);
  63873. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63874. var subMesh = mesh.subMeshes[subIndex];
  63875. scene._activeIndices.addCount(subMesh.indexCount, false);
  63876. this._renderingManager.dispatch(subMesh, mesh);
  63877. }
  63878. }
  63879. }
  63880. }
  63881. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63882. var particleSystem = scene.particleSystems[particleIndex];
  63883. var emitter = particleSystem.emitter;
  63884. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63885. continue;
  63886. }
  63887. if (currentRenderList.indexOf(emitter) >= 0) {
  63888. this._renderingManager.dispatchParticles(particleSystem);
  63889. }
  63890. }
  63891. if (this.isCube) {
  63892. for (var face = 0; face < 6; face++) {
  63893. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63894. scene.incrementRenderId();
  63895. scene.resetCachedMaterial();
  63896. }
  63897. }
  63898. else {
  63899. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63900. }
  63901. this.onAfterUnbindObservable.notifyObservers(this);
  63902. if (scene.activeCamera) {
  63903. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63904. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63905. }
  63906. engine.setViewport(scene.activeCamera.viewport);
  63907. }
  63908. scene.resetCachedMaterial();
  63909. };
  63910. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63911. var minimum = 128;
  63912. var x = renderDimension * scale;
  63913. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63914. // Ensure we don't exceed the render dimension (while staying POT)
  63915. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63916. };
  63917. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63918. var _this = this;
  63919. if (!this._texture) {
  63920. return;
  63921. }
  63922. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63923. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63924. });
  63925. };
  63926. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63927. var scene = this.getScene();
  63928. if (!scene) {
  63929. return;
  63930. }
  63931. var engine = scene.getEngine();
  63932. if (!this._texture) {
  63933. return;
  63934. }
  63935. // Bind
  63936. if (this._postProcessManager) {
  63937. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63938. }
  63939. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63940. if (this._texture) {
  63941. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63942. }
  63943. }
  63944. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63945. // Clear
  63946. if (this.onClearObservable.hasObservers()) {
  63947. this.onClearObservable.notifyObservers(engine);
  63948. }
  63949. else {
  63950. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63951. }
  63952. if (!this._doNotChangeAspectRatio) {
  63953. scene.updateTransformMatrix(true);
  63954. }
  63955. // Render
  63956. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63957. if (this._postProcessManager) {
  63958. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63959. }
  63960. else if (useCameraPostProcess) {
  63961. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63962. }
  63963. if (!this._doNotChangeAspectRatio) {
  63964. scene.updateTransformMatrix(true);
  63965. }
  63966. // Dump ?
  63967. if (dumpForDebug) {
  63968. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63969. }
  63970. // Unbind
  63971. if (!this.isCube || faceIndex === 5) {
  63972. if (this.isCube) {
  63973. if (faceIndex === 5) {
  63974. engine.generateMipMapsForCubemap(this._texture);
  63975. }
  63976. }
  63977. this.unbindFrameBuffer(engine, faceIndex);
  63978. }
  63979. else {
  63980. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63981. }
  63982. };
  63983. /**
  63984. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63985. * This allowed control for front to back rendering or reversly depending of the special needs.
  63986. *
  63987. * @param renderingGroupId The rendering group id corresponding to its index
  63988. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63989. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63990. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63991. */
  63992. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63993. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63994. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63995. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63996. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63997. };
  63998. /**
  63999. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64000. *
  64001. * @param renderingGroupId The rendering group id corresponding to its index
  64002. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64003. */
  64004. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64005. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64006. };
  64007. RenderTargetTexture.prototype.clone = function () {
  64008. var textureSize = this.getSize();
  64009. 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);
  64010. // Base texture
  64011. newTexture.hasAlpha = this.hasAlpha;
  64012. newTexture.level = this.level;
  64013. // RenderTarget Texture
  64014. newTexture.coordinatesMode = this.coordinatesMode;
  64015. if (this.renderList) {
  64016. newTexture.renderList = this.renderList.slice(0);
  64017. }
  64018. return newTexture;
  64019. };
  64020. RenderTargetTexture.prototype.serialize = function () {
  64021. if (!this.name) {
  64022. return null;
  64023. }
  64024. var serializationObject = _super.prototype.serialize.call(this);
  64025. serializationObject.renderTargetSize = this.getRenderSize();
  64026. serializationObject.renderList = [];
  64027. if (this.renderList) {
  64028. for (var index = 0; index < this.renderList.length; index++) {
  64029. serializationObject.renderList.push(this.renderList[index].id);
  64030. }
  64031. }
  64032. return serializationObject;
  64033. };
  64034. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64035. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64036. var objBuffer = this.getInternalTexture();
  64037. var scene = this.getScene();
  64038. if (objBuffer && scene) {
  64039. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64040. }
  64041. };
  64042. RenderTargetTexture.prototype.dispose = function () {
  64043. if (this._postProcessManager) {
  64044. this._postProcessManager.dispose();
  64045. this._postProcessManager = null;
  64046. }
  64047. this.clearPostProcesses(true);
  64048. if (this._resizeObserver) {
  64049. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64050. this._resizeObserver = null;
  64051. }
  64052. this.renderList = null;
  64053. // Remove from custom render targets
  64054. var scene = this.getScene();
  64055. if (!scene) {
  64056. return;
  64057. }
  64058. var index = scene.customRenderTargets.indexOf(this);
  64059. if (index >= 0) {
  64060. scene.customRenderTargets.splice(index, 1);
  64061. }
  64062. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64063. var camera = _a[_i];
  64064. index = camera.customRenderTargets.indexOf(this);
  64065. if (index >= 0) {
  64066. camera.customRenderTargets.splice(index, 1);
  64067. }
  64068. }
  64069. _super.prototype.dispose.call(this);
  64070. };
  64071. RenderTargetTexture.prototype._rebuild = function () {
  64072. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64073. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64074. }
  64075. if (this._postProcessManager) {
  64076. this._postProcessManager._rebuild();
  64077. }
  64078. };
  64079. /**
  64080. * Clear the info related to rendering groups preventing retention point in material dispose.
  64081. */
  64082. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64083. if (this._renderingManager) {
  64084. this._renderingManager.freeRenderingGroups();
  64085. }
  64086. };
  64087. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64088. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64089. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64090. return RenderTargetTexture;
  64091. }(BABYLON.Texture));
  64092. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64093. })(BABYLON || (BABYLON = {}));
  64094. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64095. var BABYLON;
  64096. (function (BABYLON) {
  64097. ;
  64098. var MultiRenderTarget = /** @class */ (function (_super) {
  64099. __extends(MultiRenderTarget, _super);
  64100. function MultiRenderTarget(name, size, count, scene, options) {
  64101. var _this = this;
  64102. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64103. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64104. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64105. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64106. _this._engine = scene.getEngine();
  64107. if (!_this.isSupported) {
  64108. _this.dispose();
  64109. return;
  64110. }
  64111. var types = [];
  64112. var samplingModes = [];
  64113. for (var i = 0; i < count; i++) {
  64114. if (options && options.types && options.types[i] !== undefined) {
  64115. types.push(options.types[i]);
  64116. }
  64117. else {
  64118. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64119. }
  64120. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64121. samplingModes.push(options.samplingModes[i]);
  64122. }
  64123. else {
  64124. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64125. }
  64126. }
  64127. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64128. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64129. _this._size = size;
  64130. _this._multiRenderTargetOptions = {
  64131. samplingModes: samplingModes,
  64132. generateMipMaps: generateMipMaps,
  64133. generateDepthBuffer: generateDepthBuffer,
  64134. generateStencilBuffer: generateStencilBuffer,
  64135. generateDepthTexture: generateDepthTexture,
  64136. types: types,
  64137. textureCount: count
  64138. };
  64139. _this._createInternalTextures();
  64140. _this._createTextures();
  64141. return _this;
  64142. }
  64143. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64144. get: function () {
  64145. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64146. },
  64147. enumerable: true,
  64148. configurable: true
  64149. });
  64150. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64151. get: function () {
  64152. return this._textures;
  64153. },
  64154. enumerable: true,
  64155. configurable: true
  64156. });
  64157. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64158. get: function () {
  64159. return this._textures[this._textures.length - 1];
  64160. },
  64161. enumerable: true,
  64162. configurable: true
  64163. });
  64164. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64165. set: function (wrap) {
  64166. if (this._textures) {
  64167. for (var i = 0; i < this._textures.length; i++) {
  64168. this._textures[i].wrapU = wrap;
  64169. }
  64170. }
  64171. },
  64172. enumerable: true,
  64173. configurable: true
  64174. });
  64175. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64176. set: function (wrap) {
  64177. if (this._textures) {
  64178. for (var i = 0; i < this._textures.length; i++) {
  64179. this._textures[i].wrapV = wrap;
  64180. }
  64181. }
  64182. },
  64183. enumerable: true,
  64184. configurable: true
  64185. });
  64186. MultiRenderTarget.prototype._rebuild = function () {
  64187. this.releaseInternalTextures();
  64188. this._createInternalTextures();
  64189. for (var i = 0; i < this._internalTextures.length; i++) {
  64190. var texture = this._textures[i];
  64191. texture._texture = this._internalTextures[i];
  64192. }
  64193. // Keeps references to frame buffer and stencil/depth buffer
  64194. this._texture = this._internalTextures[0];
  64195. };
  64196. MultiRenderTarget.prototype._createInternalTextures = function () {
  64197. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64198. };
  64199. MultiRenderTarget.prototype._createTextures = function () {
  64200. this._textures = [];
  64201. for (var i = 0; i < this._internalTextures.length; i++) {
  64202. var texture = new BABYLON.Texture(null, this.getScene());
  64203. texture._texture = this._internalTextures[i];
  64204. this._textures.push(texture);
  64205. }
  64206. // Keeps references to frame buffer and stencil/depth buffer
  64207. this._texture = this._internalTextures[0];
  64208. };
  64209. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64210. get: function () {
  64211. return this._samples;
  64212. },
  64213. set: function (value) {
  64214. if (this._samples === value) {
  64215. return;
  64216. }
  64217. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64218. },
  64219. enumerable: true,
  64220. configurable: true
  64221. });
  64222. MultiRenderTarget.prototype.resize = function (size) {
  64223. this.releaseInternalTextures();
  64224. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64225. this._createInternalTextures();
  64226. };
  64227. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64228. var _this = this;
  64229. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64230. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64231. });
  64232. };
  64233. MultiRenderTarget.prototype.dispose = function () {
  64234. this.releaseInternalTextures();
  64235. _super.prototype.dispose.call(this);
  64236. };
  64237. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64238. if (!this._internalTextures) {
  64239. return;
  64240. }
  64241. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64242. if (this._internalTextures[i] !== undefined) {
  64243. this._internalTextures[i].dispose();
  64244. this._internalTextures.splice(i, 1);
  64245. }
  64246. }
  64247. };
  64248. return MultiRenderTarget;
  64249. }(BABYLON.RenderTargetTexture));
  64250. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64251. })(BABYLON || (BABYLON = {}));
  64252. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64253. var BABYLON;
  64254. (function (BABYLON) {
  64255. var MirrorTexture = /** @class */ (function (_super) {
  64256. __extends(MirrorTexture, _super);
  64257. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64258. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64260. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64261. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64262. _this.scene = scene;
  64263. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64264. _this._transformMatrix = BABYLON.Matrix.Zero();
  64265. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64266. _this._adaptiveBlurKernel = 0;
  64267. _this._blurKernelX = 0;
  64268. _this._blurKernelY = 0;
  64269. _this._blurRatio = 1.0;
  64270. _this.ignoreCameraViewport = true;
  64271. _this._updateGammaSpace();
  64272. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64273. _this._updateGammaSpace;
  64274. });
  64275. _this.onBeforeRenderObservable.add(function () {
  64276. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64277. _this._savedViewMatrix = scene.getViewMatrix();
  64278. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64279. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64280. scene.clipPlane = _this.mirrorPlane;
  64281. scene.getEngine().cullBackFaces = false;
  64282. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64283. });
  64284. _this.onAfterRenderObservable.add(function () {
  64285. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64286. scene.getEngine().cullBackFaces = true;
  64287. scene._mirroredCameraPosition = null;
  64288. delete scene.clipPlane;
  64289. });
  64290. return _this;
  64291. }
  64292. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64293. get: function () {
  64294. return this._blurRatio;
  64295. },
  64296. set: function (value) {
  64297. if (this._blurRatio === value) {
  64298. return;
  64299. }
  64300. this._blurRatio = value;
  64301. this._preparePostProcesses();
  64302. },
  64303. enumerable: true,
  64304. configurable: true
  64305. });
  64306. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64307. set: function (value) {
  64308. this._adaptiveBlurKernel = value;
  64309. this._autoComputeBlurKernel();
  64310. },
  64311. enumerable: true,
  64312. configurable: true
  64313. });
  64314. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64315. set: function (value) {
  64316. this.blurKernelX = value;
  64317. this.blurKernelY = value;
  64318. },
  64319. enumerable: true,
  64320. configurable: true
  64321. });
  64322. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64323. get: function () {
  64324. return this._blurKernelX;
  64325. },
  64326. set: function (value) {
  64327. if (this._blurKernelX === value) {
  64328. return;
  64329. }
  64330. this._blurKernelX = value;
  64331. this._preparePostProcesses();
  64332. },
  64333. enumerable: true,
  64334. configurable: true
  64335. });
  64336. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64337. get: function () {
  64338. return this._blurKernelY;
  64339. },
  64340. set: function (value) {
  64341. if (this._blurKernelY === value) {
  64342. return;
  64343. }
  64344. this._blurKernelY = value;
  64345. this._preparePostProcesses();
  64346. },
  64347. enumerable: true,
  64348. configurable: true
  64349. });
  64350. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64351. var engine = this.getScene().getEngine();
  64352. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64353. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64354. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64355. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64356. };
  64357. MirrorTexture.prototype._onRatioRescale = function () {
  64358. if (this._sizeRatio) {
  64359. this.resize(this._initialSizeParameter);
  64360. if (!this._adaptiveBlurKernel) {
  64361. this._preparePostProcesses();
  64362. }
  64363. }
  64364. if (this._adaptiveBlurKernel) {
  64365. this._autoComputeBlurKernel();
  64366. }
  64367. };
  64368. MirrorTexture.prototype._updateGammaSpace = function () {
  64369. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64370. };
  64371. MirrorTexture.prototype._preparePostProcesses = function () {
  64372. this.clearPostProcesses(true);
  64373. if (this._blurKernelX && this._blurKernelY) {
  64374. var engine = this.getScene().getEngine();
  64375. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64376. 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);
  64377. this._blurX.autoClear = false;
  64378. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64379. this._blurX.inputTexture = this._texture;
  64380. }
  64381. else {
  64382. this._blurX.alwaysForcePOT = true;
  64383. }
  64384. 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);
  64385. this._blurY.autoClear = false;
  64386. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64387. this.addPostProcess(this._blurX);
  64388. this.addPostProcess(this._blurY);
  64389. }
  64390. else {
  64391. if (this._blurY) {
  64392. this.removePostProcess(this._blurY);
  64393. this._blurY.dispose();
  64394. this._blurY = null;
  64395. }
  64396. if (this._blurX) {
  64397. this.removePostProcess(this._blurX);
  64398. this._blurX.dispose();
  64399. this._blurX = null;
  64400. }
  64401. }
  64402. };
  64403. MirrorTexture.prototype.clone = function () {
  64404. var scene = this.getScene();
  64405. if (!scene) {
  64406. return this;
  64407. }
  64408. var textureSize = this.getSize();
  64409. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64410. // Base texture
  64411. newTexture.hasAlpha = this.hasAlpha;
  64412. newTexture.level = this.level;
  64413. // Mirror Texture
  64414. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64415. if (this.renderList) {
  64416. newTexture.renderList = this.renderList.slice(0);
  64417. }
  64418. return newTexture;
  64419. };
  64420. MirrorTexture.prototype.serialize = function () {
  64421. if (!this.name) {
  64422. return null;
  64423. }
  64424. var serializationObject = _super.prototype.serialize.call(this);
  64425. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64426. return serializationObject;
  64427. };
  64428. MirrorTexture.prototype.dispose = function () {
  64429. _super.prototype.dispose.call(this);
  64430. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64431. };
  64432. return MirrorTexture;
  64433. }(BABYLON.RenderTargetTexture));
  64434. BABYLON.MirrorTexture = MirrorTexture;
  64435. })(BABYLON || (BABYLON = {}));
  64436. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64437. var BABYLON;
  64438. (function (BABYLON) {
  64439. /**
  64440. * Creates a refraction texture used by refraction channel of the standard material.
  64441. * @param name the texture name
  64442. * @param size size of the underlying texture
  64443. * @param scene root scene
  64444. */
  64445. var RefractionTexture = /** @class */ (function (_super) {
  64446. __extends(RefractionTexture, _super);
  64447. function RefractionTexture(name, size, scene, generateMipMaps) {
  64448. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64449. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64450. _this.depth = 2.0;
  64451. _this.onBeforeRenderObservable.add(function () {
  64452. scene.clipPlane = _this.refractionPlane;
  64453. });
  64454. _this.onAfterRenderObservable.add(function () {
  64455. delete scene.clipPlane;
  64456. });
  64457. return _this;
  64458. }
  64459. RefractionTexture.prototype.clone = function () {
  64460. var scene = this.getScene();
  64461. if (!scene) {
  64462. return this;
  64463. }
  64464. var textureSize = this.getSize();
  64465. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64466. // Base texture
  64467. newTexture.hasAlpha = this.hasAlpha;
  64468. newTexture.level = this.level;
  64469. // Refraction Texture
  64470. newTexture.refractionPlane = this.refractionPlane.clone();
  64471. if (this.renderList) {
  64472. newTexture.renderList = this.renderList.slice(0);
  64473. }
  64474. newTexture.depth = this.depth;
  64475. return newTexture;
  64476. };
  64477. RefractionTexture.prototype.serialize = function () {
  64478. if (!this.name) {
  64479. return null;
  64480. }
  64481. var serializationObject = _super.prototype.serialize.call(this);
  64482. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64483. serializationObject.depth = this.depth;
  64484. return serializationObject;
  64485. };
  64486. return RefractionTexture;
  64487. }(BABYLON.RenderTargetTexture));
  64488. BABYLON.RefractionTexture = RefractionTexture;
  64489. })(BABYLON || (BABYLON = {}));
  64490. //# sourceMappingURL=babylon.refractionTexture.js.map
  64491. var BABYLON;
  64492. (function (BABYLON) {
  64493. /**
  64494. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64495. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64496. */
  64497. var DynamicTexture = /** @class */ (function (_super) {
  64498. __extends(DynamicTexture, _super);
  64499. /**
  64500. * Creates a {BABYLON.DynamicTexture}
  64501. * @param name defines the name of the texture
  64502. * @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
  64503. * @param scene defines the scene where you want the texture
  64504. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64505. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64506. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64507. */
  64508. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64509. if (scene === void 0) { scene = null; }
  64510. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64511. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64512. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64513. _this.name = name;
  64514. _this._engine = _this.getScene().getEngine();
  64515. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64516. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64517. _this._generateMipMaps = generateMipMaps;
  64518. if (options.getContext) {
  64519. _this._canvas = options;
  64520. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64521. }
  64522. else {
  64523. _this._canvas = document.createElement("canvas");
  64524. if (options.width || options.width === 0) {
  64525. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64526. }
  64527. else {
  64528. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64529. }
  64530. }
  64531. var textureSize = _this.getSize();
  64532. _this._canvas.width = textureSize.width;
  64533. _this._canvas.height = textureSize.height;
  64534. _this._context = _this._canvas.getContext("2d");
  64535. return _this;
  64536. }
  64537. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64538. /**
  64539. * Gets the current state of canRescale
  64540. */
  64541. get: function () {
  64542. return true;
  64543. },
  64544. enumerable: true,
  64545. configurable: true
  64546. });
  64547. DynamicTexture.prototype._recreate = function (textureSize) {
  64548. this._canvas.width = textureSize.width;
  64549. this._canvas.height = textureSize.height;
  64550. this.releaseInternalTexture();
  64551. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64552. };
  64553. /**
  64554. * Scales the texture
  64555. * @param ratio the scale factor to apply to both width and height
  64556. */
  64557. DynamicTexture.prototype.scale = function (ratio) {
  64558. var textureSize = this.getSize();
  64559. textureSize.width *= ratio;
  64560. textureSize.height *= ratio;
  64561. this._recreate(textureSize);
  64562. };
  64563. /**
  64564. * Resizes the texture
  64565. * @param width the new width
  64566. * @param height the new height
  64567. */
  64568. DynamicTexture.prototype.scaleTo = function (width, height) {
  64569. var textureSize = this.getSize();
  64570. textureSize.width = width;
  64571. textureSize.height = height;
  64572. this._recreate(textureSize);
  64573. };
  64574. /**
  64575. * Gets the context of the canvas used by the texture
  64576. * @returns the canvas context of the dynamic texture
  64577. */
  64578. DynamicTexture.prototype.getContext = function () {
  64579. return this._context;
  64580. };
  64581. /**
  64582. * Clears the texture
  64583. */
  64584. DynamicTexture.prototype.clear = function () {
  64585. var size = this.getSize();
  64586. this._context.fillRect(0, 0, size.width, size.height);
  64587. };
  64588. /**
  64589. * Updates the texture
  64590. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64591. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64592. */
  64593. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64594. if (premulAlpha === void 0) { premulAlpha = false; }
  64595. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64596. };
  64597. /**
  64598. * Draws text onto the texture
  64599. * @param text defines the text to be drawn
  64600. * @param x defines the placement of the text from the left
  64601. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64602. * @param font defines the font to be used with font-style, font-size, font-name
  64603. * @param color defines the color used for the text
  64604. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64605. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64606. * @param update defines whether texture is immediately update (default is true)
  64607. */
  64608. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64609. if (update === void 0) { update = true; }
  64610. var size = this.getSize();
  64611. if (clearColor) {
  64612. this._context.fillStyle = clearColor;
  64613. this._context.fillRect(0, 0, size.width, size.height);
  64614. }
  64615. this._context.font = font;
  64616. if (x === null || x === undefined) {
  64617. var textSize = this._context.measureText(text);
  64618. x = (size.width - textSize.width) / 2;
  64619. }
  64620. if (y === null || y === undefined) {
  64621. var fontSize = parseInt((font.replace(/\D/g, '')));
  64622. y = (size.height / 2) + (fontSize / 3.65);
  64623. }
  64624. this._context.fillStyle = color;
  64625. this._context.fillText(text, x, y);
  64626. if (update) {
  64627. this.update(invertY);
  64628. }
  64629. };
  64630. /**
  64631. * Clones the texture
  64632. * @returns the clone of the texture.
  64633. */
  64634. DynamicTexture.prototype.clone = function () {
  64635. var scene = this.getScene();
  64636. if (!scene) {
  64637. return this;
  64638. }
  64639. var textureSize = this.getSize();
  64640. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64641. // Base texture
  64642. newTexture.hasAlpha = this.hasAlpha;
  64643. newTexture.level = this.level;
  64644. // Dynamic Texture
  64645. newTexture.wrapU = this.wrapU;
  64646. newTexture.wrapV = this.wrapV;
  64647. return newTexture;
  64648. };
  64649. /** @hidden */
  64650. DynamicTexture.prototype._rebuild = function () {
  64651. this.update();
  64652. };
  64653. return DynamicTexture;
  64654. }(BABYLON.Texture));
  64655. BABYLON.DynamicTexture = DynamicTexture;
  64656. })(BABYLON || (BABYLON = {}));
  64657. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64658. var BABYLON;
  64659. (function (BABYLON) {
  64660. var VideoTexture = /** @class */ (function (_super) {
  64661. __extends(VideoTexture, _super);
  64662. /**
  64663. * Creates a video texture.
  64664. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64665. * @param {string | null} name optional name, will detect from video source, if not defined
  64666. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64667. * @param {BABYLON.Scene} scene is obviously the current scene.
  64668. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64669. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64670. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64671. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64672. */
  64673. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64674. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64675. if (invertY === void 0) { invertY = false; }
  64676. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64677. if (settings === void 0) { settings = {
  64678. autoPlay: true,
  64679. loop: true,
  64680. autoUpdateTexture: true,
  64681. }; }
  64682. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64683. _this._onUserActionRequestedObservable = null;
  64684. _this._stillImageCaptured = false;
  64685. _this._createInternalTexture = function () {
  64686. if (_this._texture != null) {
  64687. return;
  64688. }
  64689. if (!_this._engine.needPOTTextures ||
  64690. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64691. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64692. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64693. }
  64694. else {
  64695. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64696. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64697. _this._generateMipMaps = false;
  64698. }
  64699. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64700. if (!_this.video.autoplay) {
  64701. var oldHandler_1 = _this.video.onplaying;
  64702. var error_1 = false;
  64703. _this.video.onplaying = function () {
  64704. _this.video.onplaying = oldHandler_1;
  64705. _this._texture.isReady = true;
  64706. _this._updateInternalTexture();
  64707. if (!error_1) {
  64708. _this.video.pause();
  64709. }
  64710. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64711. _this.onLoadObservable.notifyObservers(_this);
  64712. }
  64713. };
  64714. var playing = _this.video.play();
  64715. if (playing) {
  64716. playing.then(function () {
  64717. // Everything is good.
  64718. })
  64719. .catch(function () {
  64720. error_1 = true;
  64721. // On Chrome for instance, new policies might prevent playing without user interaction.
  64722. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64723. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64724. }
  64725. });
  64726. }
  64727. else {
  64728. _this.video.onplaying = oldHandler_1;
  64729. _this._texture.isReady = true;
  64730. _this._updateInternalTexture();
  64731. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64732. _this.onLoadObservable.notifyObservers(_this);
  64733. }
  64734. }
  64735. }
  64736. else {
  64737. _this._texture.isReady = true;
  64738. _this._updateInternalTexture();
  64739. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64740. _this.onLoadObservable.notifyObservers(_this);
  64741. }
  64742. }
  64743. };
  64744. _this.reset = function () {
  64745. if (_this._texture == null) {
  64746. return;
  64747. }
  64748. _this._texture.dispose();
  64749. _this._texture = null;
  64750. };
  64751. _this._updateInternalTexture = function (e) {
  64752. if (_this._texture == null || !_this._texture.isReady) {
  64753. return;
  64754. }
  64755. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64756. return;
  64757. }
  64758. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64759. };
  64760. _this._engine = _this.getScene().getEngine();
  64761. _this._generateMipMaps = generateMipMaps;
  64762. _this._samplingMode = samplingMode;
  64763. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64764. _this.name = name || _this._getName(src);
  64765. _this.video = _this._getVideo(src);
  64766. if (settings.poster) {
  64767. _this.video.poster = settings.poster;
  64768. }
  64769. if (settings.autoPlay !== undefined) {
  64770. _this.video.autoplay = settings.autoPlay;
  64771. }
  64772. if (settings.loop !== undefined) {
  64773. _this.video.loop = settings.loop;
  64774. }
  64775. _this.video.setAttribute("playsinline", "");
  64776. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64777. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64778. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64779. _this.video.addEventListener("emptied", _this.reset);
  64780. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64781. _this._createInternalTexture();
  64782. }
  64783. return _this;
  64784. }
  64785. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64786. get: function () {
  64787. if (!this._onUserActionRequestedObservable) {
  64788. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64789. }
  64790. return this._onUserActionRequestedObservable;
  64791. },
  64792. enumerable: true,
  64793. configurable: true
  64794. });
  64795. VideoTexture.prototype._getName = function (src) {
  64796. if (src instanceof HTMLVideoElement) {
  64797. return src.currentSrc;
  64798. }
  64799. if (typeof src === "object") {
  64800. return src.toString();
  64801. }
  64802. return src;
  64803. };
  64804. ;
  64805. VideoTexture.prototype._getVideo = function (src) {
  64806. if (src instanceof HTMLVideoElement) {
  64807. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64808. return src;
  64809. }
  64810. var video = document.createElement("video");
  64811. if (typeof src === "string") {
  64812. BABYLON.Tools.SetCorsBehavior(src, video);
  64813. video.src = src;
  64814. }
  64815. else {
  64816. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64817. src.forEach(function (url) {
  64818. var source = document.createElement("source");
  64819. source.src = url;
  64820. video.appendChild(source);
  64821. });
  64822. }
  64823. return video;
  64824. };
  64825. ;
  64826. /**
  64827. * Internal method to initiate `update`.
  64828. */
  64829. VideoTexture.prototype._rebuild = function () {
  64830. this.update();
  64831. };
  64832. /**
  64833. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64834. */
  64835. VideoTexture.prototype.update = function () {
  64836. if (!this.autoUpdateTexture) {
  64837. // Expecting user to call `updateTexture` manually
  64838. return;
  64839. }
  64840. this.updateTexture(true);
  64841. };
  64842. /**
  64843. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64844. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64845. */
  64846. VideoTexture.prototype.updateTexture = function (isVisible) {
  64847. if (!isVisible) {
  64848. return;
  64849. }
  64850. if (this.video.paused && this._stillImageCaptured) {
  64851. return;
  64852. }
  64853. this._stillImageCaptured = true;
  64854. this._updateInternalTexture();
  64855. };
  64856. /**
  64857. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64858. * @param url New url.
  64859. */
  64860. VideoTexture.prototype.updateURL = function (url) {
  64861. this.video.src = url;
  64862. };
  64863. VideoTexture.prototype.dispose = function () {
  64864. _super.prototype.dispose.call(this);
  64865. if (this._onUserActionRequestedObservable) {
  64866. this._onUserActionRequestedObservable.clear();
  64867. this._onUserActionRequestedObservable = null;
  64868. }
  64869. this.video.removeEventListener("canplay", this._createInternalTexture);
  64870. this.video.removeEventListener("paused", this._updateInternalTexture);
  64871. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64872. this.video.removeEventListener("emptied", this.reset);
  64873. this.video.pause();
  64874. };
  64875. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64876. var video = document.createElement("video");
  64877. video.setAttribute('autoplay', '');
  64878. video.setAttribute('muted', '');
  64879. video.setAttribute('playsinline', '');
  64880. var constraintsDeviceId;
  64881. if (constraints && constraints.deviceId) {
  64882. constraintsDeviceId = {
  64883. exact: constraints.deviceId,
  64884. };
  64885. }
  64886. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64887. if (navigator.mediaDevices) {
  64888. navigator.mediaDevices.getUserMedia({ video: constraints })
  64889. .then(function (stream) {
  64890. if (video.mozSrcObject !== undefined) {
  64891. // hack for Firefox < 19
  64892. video.mozSrcObject = stream;
  64893. }
  64894. else {
  64895. video.srcObject = stream;
  64896. }
  64897. var onPlaying = function () {
  64898. if (onReady) {
  64899. onReady(new VideoTexture("video", video, scene, true, true));
  64900. }
  64901. video.removeEventListener("playing", onPlaying);
  64902. };
  64903. video.addEventListener("playing", onPlaying);
  64904. video.play();
  64905. })
  64906. .catch(function (err) {
  64907. BABYLON.Tools.Error(err.name);
  64908. });
  64909. }
  64910. else {
  64911. navigator.getUserMedia =
  64912. navigator.getUserMedia ||
  64913. navigator.webkitGetUserMedia ||
  64914. navigator.mozGetUserMedia ||
  64915. navigator.msGetUserMedia;
  64916. if (navigator.getUserMedia) {
  64917. navigator.getUserMedia({
  64918. video: {
  64919. deviceId: constraintsDeviceId,
  64920. width: {
  64921. min: (constraints && constraints.minWidth) || 256,
  64922. max: (constraints && constraints.maxWidth) || 640,
  64923. },
  64924. height: {
  64925. min: (constraints && constraints.minHeight) || 256,
  64926. max: (constraints && constraints.maxHeight) || 480,
  64927. },
  64928. },
  64929. }, function (stream) {
  64930. if (video.mozSrcObject !== undefined) {
  64931. // hack for Firefox < 19
  64932. video.mozSrcObject = stream;
  64933. }
  64934. else {
  64935. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64936. }
  64937. video.play();
  64938. if (onReady) {
  64939. onReady(new VideoTexture("video", video, scene, true, true));
  64940. }
  64941. }, function (e) {
  64942. BABYLON.Tools.Error(e.name);
  64943. });
  64944. }
  64945. }
  64946. };
  64947. return VideoTexture;
  64948. }(BABYLON.Texture));
  64949. BABYLON.VideoTexture = VideoTexture;
  64950. })(BABYLON || (BABYLON = {}));
  64951. //# sourceMappingURL=babylon.videoTexture.js.map
  64952. var BABYLON;
  64953. (function (BABYLON) {
  64954. var RawTexture = /** @class */ (function (_super) {
  64955. __extends(RawTexture, _super);
  64956. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64957. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64958. if (invertY === void 0) { invertY = false; }
  64959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64960. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64961. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64962. _this.format = format;
  64963. _this._engine = scene.getEngine();
  64964. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64965. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64966. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64967. return _this;
  64968. }
  64969. RawTexture.prototype.update = function (data) {
  64970. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64971. };
  64972. // Statics
  64973. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64974. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64975. if (invertY === void 0) { invertY = false; }
  64976. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64977. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64978. };
  64979. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64980. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64981. if (invertY === void 0) { invertY = false; }
  64982. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64983. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64984. };
  64985. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64986. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64987. if (invertY === void 0) { invertY = false; }
  64988. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64989. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64990. };
  64991. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64992. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64993. if (invertY === void 0) { invertY = false; }
  64994. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64995. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64996. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64997. };
  64998. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64999. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65000. if (invertY === void 0) { invertY = false; }
  65001. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65002. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65003. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65004. };
  65005. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65006. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65007. if (invertY === void 0) { invertY = false; }
  65008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65009. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65010. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65011. };
  65012. return RawTexture;
  65013. }(BABYLON.Texture));
  65014. BABYLON.RawTexture = RawTexture;
  65015. })(BABYLON || (BABYLON = {}));
  65016. //# sourceMappingURL=babylon.rawTexture.js.map
  65017. var BABYLON;
  65018. (function (BABYLON) {
  65019. /**
  65020. * Class used to store 3D textures containing user data
  65021. */
  65022. var RawTexture3D = /** @class */ (function (_super) {
  65023. __extends(RawTexture3D, _super);
  65024. /**
  65025. * Create a new RawTexture3D
  65026. * @param data defines the data of the texture
  65027. * @param width defines the width of the texture
  65028. * @param height defines the height of the texture
  65029. * @param depth defines the depth of the texture
  65030. * @param format defines the texture format to use
  65031. * @param scene defines the hosting scene
  65032. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65033. * @param invertY defines if texture must be stored with Y axis inverted
  65034. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65035. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65036. */
  65037. function RawTexture3D(data, width, height, depth,
  65038. /** Gets or sets the texture format to use */
  65039. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65040. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65041. if (invertY === void 0) { invertY = false; }
  65042. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65043. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65044. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65045. _this.format = format;
  65046. _this._engine = scene.getEngine();
  65047. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65048. _this.is3D = true;
  65049. return _this;
  65050. }
  65051. /**
  65052. * Update the texture with new data
  65053. * @param data defines the data to store in the texture
  65054. */
  65055. RawTexture3D.prototype.update = function (data) {
  65056. if (!this._texture) {
  65057. return;
  65058. }
  65059. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65060. };
  65061. return RawTexture3D;
  65062. }(BABYLON.Texture));
  65063. BABYLON.RawTexture3D = RawTexture3D;
  65064. })(BABYLON || (BABYLON = {}));
  65065. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65066. var BABYLON;
  65067. (function (BABYLON) {
  65068. /**
  65069. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65070. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65071. */
  65072. var PostProcessManager = /** @class */ (function () {
  65073. /**
  65074. * Creates a new instance PostProcess
  65075. * @param scene The scene that the post process is associated with.
  65076. */
  65077. function PostProcessManager(scene) {
  65078. this._vertexBuffers = {};
  65079. this._scene = scene;
  65080. }
  65081. PostProcessManager.prototype._prepareBuffers = function () {
  65082. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65083. return;
  65084. }
  65085. // VBO
  65086. var vertices = [];
  65087. vertices.push(1, 1);
  65088. vertices.push(-1, 1);
  65089. vertices.push(-1, -1);
  65090. vertices.push(1, -1);
  65091. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65092. this._buildIndexBuffer();
  65093. };
  65094. PostProcessManager.prototype._buildIndexBuffer = function () {
  65095. // Indices
  65096. var indices = [];
  65097. indices.push(0);
  65098. indices.push(1);
  65099. indices.push(2);
  65100. indices.push(0);
  65101. indices.push(2);
  65102. indices.push(3);
  65103. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65104. };
  65105. /**
  65106. * Rebuilds the vertex buffers of the manager.
  65107. */
  65108. PostProcessManager.prototype._rebuild = function () {
  65109. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65110. if (!vb) {
  65111. return;
  65112. }
  65113. vb._rebuild();
  65114. this._buildIndexBuffer();
  65115. };
  65116. // Methods
  65117. /**
  65118. * Prepares a frame to be run through a post process.
  65119. * @param sourceTexture The input texture to the post procesess. (default: null)
  65120. * @param postProcesses An array of post processes to be run. (default: null)
  65121. * @returns True if the post processes were able to be run.
  65122. */
  65123. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65124. if (sourceTexture === void 0) { sourceTexture = null; }
  65125. if (postProcesses === void 0) { postProcesses = null; }
  65126. var camera = this._scene.activeCamera;
  65127. if (!camera) {
  65128. return false;
  65129. }
  65130. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65131. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65132. return false;
  65133. }
  65134. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65135. return true;
  65136. };
  65137. /**
  65138. * Manually render a set of post processes to a texture.
  65139. * @param postProcesses An array of post processes to be run.
  65140. * @param targetTexture The target texture to render to.
  65141. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65142. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65143. * @param lodLevel defines which lod of the texture to render to
  65144. */
  65145. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65146. if (targetTexture === void 0) { targetTexture = null; }
  65147. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65148. if (faceIndex === void 0) { faceIndex = 0; }
  65149. if (lodLevel === void 0) { lodLevel = 0; }
  65150. var engine = this._scene.getEngine();
  65151. for (var index = 0; index < postProcesses.length; index++) {
  65152. if (index < postProcesses.length - 1) {
  65153. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65154. }
  65155. else {
  65156. if (targetTexture) {
  65157. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65158. }
  65159. else {
  65160. engine.restoreDefaultFramebuffer();
  65161. }
  65162. }
  65163. var pp = postProcesses[index];
  65164. var effect = pp.apply();
  65165. if (effect) {
  65166. pp.onBeforeRenderObservable.notifyObservers(effect);
  65167. // VBOs
  65168. this._prepareBuffers();
  65169. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65170. // Draw order
  65171. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65172. pp.onAfterRenderObservable.notifyObservers(effect);
  65173. }
  65174. }
  65175. // Restore depth buffer
  65176. engine.setDepthBuffer(true);
  65177. engine.setDepthWrite(true);
  65178. };
  65179. /**
  65180. * Finalize the result of the output of the postprocesses.
  65181. * @param doNotPresent If true the result will not be displayed to the screen.
  65182. * @param targetTexture The target texture to render to.
  65183. * @param faceIndex The index of the face to bind the target texture to.
  65184. * @param postProcesses The array of post processes to render.
  65185. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65186. */
  65187. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65188. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65189. var camera = this._scene.activeCamera;
  65190. if (!camera) {
  65191. return;
  65192. }
  65193. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65194. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65195. return;
  65196. }
  65197. var engine = this._scene.getEngine();
  65198. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65199. var pp = postProcesses[index];
  65200. if (index < len - 1) {
  65201. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65202. }
  65203. else {
  65204. if (targetTexture) {
  65205. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65206. pp._outputTexture = targetTexture;
  65207. }
  65208. else {
  65209. engine.restoreDefaultFramebuffer();
  65210. pp._outputTexture = null;
  65211. }
  65212. }
  65213. if (doNotPresent) {
  65214. break;
  65215. }
  65216. var effect = pp.apply();
  65217. if (effect) {
  65218. pp.onBeforeRenderObservable.notifyObservers(effect);
  65219. // VBOs
  65220. this._prepareBuffers();
  65221. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65222. // Draw order
  65223. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65224. pp.onAfterRenderObservable.notifyObservers(effect);
  65225. }
  65226. }
  65227. // Restore states
  65228. engine.setDepthBuffer(true);
  65229. engine.setDepthWrite(true);
  65230. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65231. };
  65232. /**
  65233. * Disposes of the post process manager.
  65234. */
  65235. PostProcessManager.prototype.dispose = function () {
  65236. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65237. if (buffer) {
  65238. buffer.dispose();
  65239. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65240. }
  65241. if (this._indexBuffer) {
  65242. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65243. this._indexBuffer = null;
  65244. }
  65245. };
  65246. return PostProcessManager;
  65247. }());
  65248. BABYLON.PostProcessManager = PostProcessManager;
  65249. })(BABYLON || (BABYLON = {}));
  65250. //# sourceMappingURL=babylon.postProcessManager.js.map
  65251. var BABYLON;
  65252. (function (BABYLON) {
  65253. /**
  65254. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65255. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65256. */
  65257. var PostProcess = /** @class */ (function () {
  65258. /**
  65259. * Creates a new instance PostProcess
  65260. * @param name The name of the PostProcess.
  65261. * @param fragmentUrl The url of the fragment shader to be used.
  65262. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65263. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65264. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65265. * @param camera The camera to apply the render pass to.
  65266. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65267. * @param engine The engine which the post process will be applied. (default: current engine)
  65268. * @param reusable If the post process can be reused on the same frame. (default: false)
  65269. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65270. * @param textureType Type of textures used when performing the post process. (default: 0)
  65271. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65272. * @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
  65273. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65274. */
  65275. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65276. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65277. if (defines === void 0) { defines = null; }
  65278. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65279. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65280. if (blockCompilation === void 0) { blockCompilation = false; }
  65281. this.name = name;
  65282. /**
  65283. * Width of the texture to apply the post process on
  65284. */
  65285. this.width = -1;
  65286. /**
  65287. * Height of the texture to apply the post process on
  65288. */
  65289. this.height = -1;
  65290. /**
  65291. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65292. */
  65293. this._outputTexture = null;
  65294. /**
  65295. * If the buffer needs to be cleared before applying the post process. (default: true)
  65296. * Should be set to false if shader will overwrite all previous pixels.
  65297. */
  65298. this.autoClear = true;
  65299. /**
  65300. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65301. */
  65302. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65303. /**
  65304. * Animations to be used for the post processing
  65305. */
  65306. this.animations = new Array();
  65307. /**
  65308. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65309. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65310. */
  65311. this.enablePixelPerfectMode = false;
  65312. /**
  65313. * Force the postprocess to be applied without taking in account viewport
  65314. */
  65315. this.forceFullscreenViewport = true;
  65316. /**
  65317. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65318. *
  65319. * | Value | Type | Description |
  65320. * | ----- | ----------------------------------- | ----------- |
  65321. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65322. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65323. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65324. *
  65325. */
  65326. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65327. /**
  65328. * Force textures to be a power of two (default: false)
  65329. */
  65330. this.alwaysForcePOT = false;
  65331. /**
  65332. * Number of sample textures (default: 1)
  65333. */
  65334. this.samples = 1;
  65335. /**
  65336. * Modify the scale of the post process to be the same as the viewport (default: false)
  65337. */
  65338. this.adaptScaleToCurrentViewport = false;
  65339. this._reusable = false;
  65340. /**
  65341. * Smart array of input and output textures for the post process.
  65342. */
  65343. this._textures = new BABYLON.SmartArray(2);
  65344. /**
  65345. * The index in _textures that corresponds to the output texture.
  65346. */
  65347. this._currentRenderTextureInd = 0;
  65348. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65349. this._texelSize = BABYLON.Vector2.Zero();
  65350. // Events
  65351. /**
  65352. * An event triggered when the postprocess is activated.
  65353. */
  65354. this.onActivateObservable = new BABYLON.Observable();
  65355. /**
  65356. * An event triggered when the postprocess changes its size.
  65357. */
  65358. this.onSizeChangedObservable = new BABYLON.Observable();
  65359. /**
  65360. * An event triggered when the postprocess applies its effect.
  65361. */
  65362. this.onApplyObservable = new BABYLON.Observable();
  65363. /**
  65364. * An event triggered before rendering the postprocess
  65365. */
  65366. this.onBeforeRenderObservable = new BABYLON.Observable();
  65367. /**
  65368. * An event triggered after rendering the postprocess
  65369. */
  65370. this.onAfterRenderObservable = new BABYLON.Observable();
  65371. if (camera != null) {
  65372. this._camera = camera;
  65373. this._scene = camera.getScene();
  65374. camera.attachPostProcess(this);
  65375. this._engine = this._scene.getEngine();
  65376. this._scene.postProcesses.push(this);
  65377. }
  65378. else if (engine) {
  65379. this._engine = engine;
  65380. this._engine.postProcesses.push(this);
  65381. }
  65382. this._options = options;
  65383. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65384. this._reusable = reusable || false;
  65385. this._textureType = textureType;
  65386. this._samplers = samplers || [];
  65387. this._samplers.push("textureSampler");
  65388. this._fragmentUrl = fragmentUrl;
  65389. this._vertexUrl = vertexUrl;
  65390. this._parameters = parameters || [];
  65391. this._parameters.push("scale");
  65392. this._indexParameters = indexParameters;
  65393. if (!blockCompilation) {
  65394. this.updateEffect(defines);
  65395. }
  65396. }
  65397. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65398. /**
  65399. * A function that is added to the onActivateObservable
  65400. */
  65401. set: function (callback) {
  65402. if (this._onActivateObserver) {
  65403. this.onActivateObservable.remove(this._onActivateObserver);
  65404. }
  65405. if (callback) {
  65406. this._onActivateObserver = this.onActivateObservable.add(callback);
  65407. }
  65408. },
  65409. enumerable: true,
  65410. configurable: true
  65411. });
  65412. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65413. /**
  65414. * A function that is added to the onSizeChangedObservable
  65415. */
  65416. set: function (callback) {
  65417. if (this._onSizeChangedObserver) {
  65418. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65419. }
  65420. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65421. },
  65422. enumerable: true,
  65423. configurable: true
  65424. });
  65425. Object.defineProperty(PostProcess.prototype, "onApply", {
  65426. /**
  65427. * A function that is added to the onApplyObservable
  65428. */
  65429. set: function (callback) {
  65430. if (this._onApplyObserver) {
  65431. this.onApplyObservable.remove(this._onApplyObserver);
  65432. }
  65433. this._onApplyObserver = this.onApplyObservable.add(callback);
  65434. },
  65435. enumerable: true,
  65436. configurable: true
  65437. });
  65438. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65439. /**
  65440. * A function that is added to the onBeforeRenderObservable
  65441. */
  65442. set: function (callback) {
  65443. if (this._onBeforeRenderObserver) {
  65444. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65445. }
  65446. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65447. },
  65448. enumerable: true,
  65449. configurable: true
  65450. });
  65451. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65452. /**
  65453. * A function that is added to the onAfterRenderObservable
  65454. */
  65455. set: function (callback) {
  65456. if (this._onAfterRenderObserver) {
  65457. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65458. }
  65459. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65460. },
  65461. enumerable: true,
  65462. configurable: true
  65463. });
  65464. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65465. /**
  65466. * 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
  65467. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65468. */
  65469. get: function () {
  65470. return this._textures.data[this._currentRenderTextureInd];
  65471. },
  65472. set: function (value) {
  65473. this._forcedOutputTexture = value;
  65474. },
  65475. enumerable: true,
  65476. configurable: true
  65477. });
  65478. /**
  65479. * Gets the camera which post process is applied to.
  65480. * @returns The camera the post process is applied to.
  65481. */
  65482. PostProcess.prototype.getCamera = function () {
  65483. return this._camera;
  65484. };
  65485. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65486. /**
  65487. * Gets the texel size of the postprocess.
  65488. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65489. */
  65490. get: function () {
  65491. if (this._shareOutputWithPostProcess) {
  65492. return this._shareOutputWithPostProcess.texelSize;
  65493. }
  65494. if (this._forcedOutputTexture) {
  65495. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65496. }
  65497. return this._texelSize;
  65498. },
  65499. enumerable: true,
  65500. configurable: true
  65501. });
  65502. /**
  65503. * Gets the engine which this post process belongs to.
  65504. * @returns The engine the post process was enabled with.
  65505. */
  65506. PostProcess.prototype.getEngine = function () {
  65507. return this._engine;
  65508. };
  65509. /**
  65510. * The effect that is created when initializing the post process.
  65511. * @returns The created effect corrisponding the the postprocess.
  65512. */
  65513. PostProcess.prototype.getEffect = function () {
  65514. return this._effect;
  65515. };
  65516. /**
  65517. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65518. * @param postProcess The post process to share the output with.
  65519. * @returns This post process.
  65520. */
  65521. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65522. this._disposeTextures();
  65523. this._shareOutputWithPostProcess = postProcess;
  65524. return this;
  65525. };
  65526. /**
  65527. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65528. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65529. */
  65530. PostProcess.prototype.useOwnOutput = function () {
  65531. if (this._textures.length == 0) {
  65532. this._textures = new BABYLON.SmartArray(2);
  65533. }
  65534. this._shareOutputWithPostProcess = null;
  65535. };
  65536. /**
  65537. * Updates the effect with the current post process compile time values and recompiles the shader.
  65538. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65539. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65540. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65541. * @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
  65542. * @param onCompiled Called when the shader has been compiled.
  65543. * @param onError Called if there is an error when compiling a shader.
  65544. */
  65545. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65546. if (defines === void 0) { defines = null; }
  65547. if (uniforms === void 0) { uniforms = null; }
  65548. if (samplers === void 0) { samplers = null; }
  65549. 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);
  65550. };
  65551. /**
  65552. * The post process is reusable if it can be used multiple times within one frame.
  65553. * @returns If the post process is reusable
  65554. */
  65555. PostProcess.prototype.isReusable = function () {
  65556. return this._reusable;
  65557. };
  65558. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65559. PostProcess.prototype.markTextureDirty = function () {
  65560. this.width = -1;
  65561. };
  65562. /**
  65563. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65564. * 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.
  65565. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65566. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65567. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65568. * @returns The target texture that was bound to be written to.
  65569. */
  65570. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65571. var _this = this;
  65572. if (sourceTexture === void 0) { sourceTexture = null; }
  65573. camera = camera || this._camera;
  65574. var scene = camera.getScene();
  65575. var engine = scene.getEngine();
  65576. var maxSize = engine.getCaps().maxTextureSize;
  65577. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65578. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65579. // 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
  65580. var webVRCamera = camera.parent;
  65581. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65582. requiredWidth /= 2;
  65583. }
  65584. var desiredWidth = (this._options.width || requiredWidth);
  65585. var desiredHeight = this._options.height || requiredHeight;
  65586. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65587. if (this.adaptScaleToCurrentViewport) {
  65588. var currentViewport = engine.currentViewport;
  65589. if (currentViewport) {
  65590. desiredWidth *= currentViewport.width;
  65591. desiredHeight *= currentViewport.height;
  65592. }
  65593. }
  65594. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65595. if (!this._options.width) {
  65596. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65597. }
  65598. if (!this._options.height) {
  65599. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65600. }
  65601. }
  65602. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65603. if (this._textures.length > 0) {
  65604. for (var i = 0; i < this._textures.length; i++) {
  65605. this._engine._releaseTexture(this._textures.data[i]);
  65606. }
  65607. this._textures.reset();
  65608. }
  65609. this.width = desiredWidth;
  65610. this.height = desiredHeight;
  65611. var textureSize = { width: this.width, height: this.height };
  65612. var textureOptions = {
  65613. generateMipMaps: false,
  65614. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65615. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65616. samplingMode: this.renderTargetSamplingMode,
  65617. type: this._textureType
  65618. };
  65619. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65620. if (this._reusable) {
  65621. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65622. }
  65623. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65624. this.onSizeChangedObservable.notifyObservers(this);
  65625. }
  65626. this._textures.forEach(function (texture) {
  65627. if (texture.samples !== _this.samples) {
  65628. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65629. }
  65630. });
  65631. }
  65632. var target;
  65633. if (this._shareOutputWithPostProcess) {
  65634. target = this._shareOutputWithPostProcess.inputTexture;
  65635. }
  65636. else if (this._forcedOutputTexture) {
  65637. target = this._forcedOutputTexture;
  65638. this.width = this._forcedOutputTexture.width;
  65639. this.height = this._forcedOutputTexture.height;
  65640. }
  65641. else {
  65642. target = this.inputTexture;
  65643. }
  65644. // Bind the input of this post process to be used as the output of the previous post process.
  65645. if (this.enablePixelPerfectMode) {
  65646. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65647. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65648. }
  65649. else {
  65650. this._scaleRatio.copyFromFloats(1, 1);
  65651. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65652. }
  65653. this.onActivateObservable.notifyObservers(camera);
  65654. // Clear
  65655. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65656. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65657. }
  65658. if (this._reusable) {
  65659. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65660. }
  65661. return target;
  65662. };
  65663. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65664. /**
  65665. * If the post process is supported.
  65666. */
  65667. get: function () {
  65668. return this._effect.isSupported;
  65669. },
  65670. enumerable: true,
  65671. configurable: true
  65672. });
  65673. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65674. /**
  65675. * The aspect ratio of the output texture.
  65676. */
  65677. get: function () {
  65678. if (this._shareOutputWithPostProcess) {
  65679. return this._shareOutputWithPostProcess.aspectRatio;
  65680. }
  65681. if (this._forcedOutputTexture) {
  65682. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65683. }
  65684. return this.width / this.height;
  65685. },
  65686. enumerable: true,
  65687. configurable: true
  65688. });
  65689. /**
  65690. * Get a value indicating if the post-process is ready to be used
  65691. * @returns true if the post-process is ready (shader is compiled)
  65692. */
  65693. PostProcess.prototype.isReady = function () {
  65694. return this._effect && this._effect.isReady();
  65695. };
  65696. /**
  65697. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65698. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65699. */
  65700. PostProcess.prototype.apply = function () {
  65701. // Check
  65702. if (!this._effect || !this._effect.isReady())
  65703. return null;
  65704. // States
  65705. this._engine.enableEffect(this._effect);
  65706. this._engine.setState(false);
  65707. this._engine.setDepthBuffer(false);
  65708. this._engine.setDepthWrite(false);
  65709. // Alpha
  65710. this._engine.setAlphaMode(this.alphaMode);
  65711. if (this.alphaConstants) {
  65712. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65713. }
  65714. // Bind the output texture of the preivous post process as the input to this post process.
  65715. var source;
  65716. if (this._shareOutputWithPostProcess) {
  65717. source = this._shareOutputWithPostProcess.inputTexture;
  65718. }
  65719. else if (this._forcedOutputTexture) {
  65720. source = this._forcedOutputTexture;
  65721. }
  65722. else {
  65723. source = this.inputTexture;
  65724. }
  65725. this._effect._bindTexture("textureSampler", source);
  65726. // Parameters
  65727. this._effect.setVector2("scale", this._scaleRatio);
  65728. this.onApplyObservable.notifyObservers(this._effect);
  65729. return this._effect;
  65730. };
  65731. PostProcess.prototype._disposeTextures = function () {
  65732. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65733. return;
  65734. }
  65735. if (this._textures.length > 0) {
  65736. for (var i = 0; i < this._textures.length; i++) {
  65737. this._engine._releaseTexture(this._textures.data[i]);
  65738. }
  65739. }
  65740. this._textures.dispose();
  65741. };
  65742. /**
  65743. * Disposes the post process.
  65744. * @param camera The camera to dispose the post process on.
  65745. */
  65746. PostProcess.prototype.dispose = function (camera) {
  65747. camera = camera || this._camera;
  65748. this._disposeTextures();
  65749. if (this._scene) {
  65750. var index_1 = this._scene.postProcesses.indexOf(this);
  65751. if (index_1 !== -1) {
  65752. this._scene.postProcesses.splice(index_1, 1);
  65753. }
  65754. }
  65755. else {
  65756. var index_2 = this._engine.postProcesses.indexOf(this);
  65757. if (index_2 !== -1) {
  65758. this._engine.postProcesses.splice(index_2, 1);
  65759. }
  65760. }
  65761. if (!camera) {
  65762. return;
  65763. }
  65764. camera.detachPostProcess(this);
  65765. var index = camera._postProcesses.indexOf(this);
  65766. if (index === 0 && camera._postProcesses.length > 0) {
  65767. var firstPostProcess = this._camera._getFirstPostProcess();
  65768. if (firstPostProcess) {
  65769. firstPostProcess.markTextureDirty();
  65770. }
  65771. }
  65772. this.onActivateObservable.clear();
  65773. this.onAfterRenderObservable.clear();
  65774. this.onApplyObservable.clear();
  65775. this.onBeforeRenderObservable.clear();
  65776. this.onSizeChangedObservable.clear();
  65777. };
  65778. return PostProcess;
  65779. }());
  65780. BABYLON.PostProcess = PostProcess;
  65781. })(BABYLON || (BABYLON = {}));
  65782. //# sourceMappingURL=babylon.postProcess.js.map
  65783. var BABYLON;
  65784. (function (BABYLON) {
  65785. var PassPostProcess = /** @class */ (function (_super) {
  65786. __extends(PassPostProcess, _super);
  65787. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65788. if (camera === void 0) { camera = null; }
  65789. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65790. if (blockCompilation === void 0) { blockCompilation = false; }
  65791. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65792. }
  65793. return PassPostProcess;
  65794. }(BABYLON.PostProcess));
  65795. BABYLON.PassPostProcess = PassPostProcess;
  65796. })(BABYLON || (BABYLON = {}));
  65797. //# sourceMappingURL=babylon.passPostProcess.js.map
  65798. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65799. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65800. s = arguments[i];
  65801. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65802. t[p] = s[p];
  65803. }
  65804. return t;
  65805. };
  65806. var BABYLON;
  65807. (function (BABYLON) {
  65808. /**
  65809. * Default implementation IShadowGenerator.
  65810. * This is the main object responsible of generating shadows in the framework.
  65811. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65812. */
  65813. var ShadowGenerator = /** @class */ (function () {
  65814. /**
  65815. * Creates a ShadowGenerator object.
  65816. * A ShadowGenerator is the required tool to use the shadows.
  65817. * Each light casting shadows needs to use its own ShadowGenerator.
  65818. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65819. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65820. * @param light The light object generating the shadows.
  65821. * @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.
  65822. */
  65823. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65824. this._bias = 0.00005;
  65825. this._normalBias = 0;
  65826. this._blurBoxOffset = 1;
  65827. this._blurScale = 2;
  65828. this._blurKernel = 1;
  65829. this._useKernelBlur = false;
  65830. this._filter = ShadowGenerator.FILTER_NONE;
  65831. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65832. this._contactHardeningLightSizeUVRatio = 0.1;
  65833. this._darkness = 0;
  65834. this._transparencyShadow = false;
  65835. /**
  65836. * Controls the extent to which the shadows fade out at the edge of the frustum
  65837. * Used only by directionals and spots
  65838. */
  65839. this.frustumEdgeFalloff = 0;
  65840. /**
  65841. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65842. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65843. * It might on the other hand introduce peter panning.
  65844. */
  65845. this.forceBackFacesOnly = false;
  65846. this._lightDirection = BABYLON.Vector3.Zero();
  65847. this._viewMatrix = BABYLON.Matrix.Zero();
  65848. this._projectionMatrix = BABYLON.Matrix.Zero();
  65849. this._transformMatrix = BABYLON.Matrix.Zero();
  65850. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65851. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65852. this._currentFaceIndex = 0;
  65853. this._currentFaceIndexCache = 0;
  65854. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65855. this._mapSize = mapSize;
  65856. this._light = light;
  65857. this._scene = light.getScene();
  65858. light._shadowGenerator = this;
  65859. // Texture type fallback from float to int if not supported.
  65860. var caps = this._scene.getEngine().getCaps();
  65861. if (!useFullFloatFirst) {
  65862. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65863. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65864. }
  65865. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65866. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65867. }
  65868. else {
  65869. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65870. }
  65871. }
  65872. else {
  65873. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65874. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65875. }
  65876. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65877. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65878. }
  65879. else {
  65880. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65881. }
  65882. }
  65883. this._initializeGenerator();
  65884. this._applyFilterValues();
  65885. }
  65886. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65887. /**
  65888. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65889. */
  65890. get: function () {
  65891. return this._bias;
  65892. },
  65893. /**
  65894. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65895. */
  65896. set: function (bias) {
  65897. this._bias = bias;
  65898. },
  65899. enumerable: true,
  65900. configurable: true
  65901. });
  65902. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65903. /**
  65904. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65905. */
  65906. get: function () {
  65907. return this._normalBias;
  65908. },
  65909. /**
  65910. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65911. */
  65912. set: function (normalBias) {
  65913. this._normalBias = normalBias;
  65914. },
  65915. enumerable: true,
  65916. configurable: true
  65917. });
  65918. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65919. /**
  65920. * Gets the blur box offset: offset applied during the blur pass.
  65921. * Only usefull if useKernelBlur = false
  65922. */
  65923. get: function () {
  65924. return this._blurBoxOffset;
  65925. },
  65926. /**
  65927. * Sets the blur box offset: offset applied during the blur pass.
  65928. * Only usefull if useKernelBlur = false
  65929. */
  65930. set: function (value) {
  65931. if (this._blurBoxOffset === value) {
  65932. return;
  65933. }
  65934. this._blurBoxOffset = value;
  65935. this._disposeBlurPostProcesses();
  65936. },
  65937. enumerable: true,
  65938. configurable: true
  65939. });
  65940. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65941. /**
  65942. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65943. * 2 means half of the size.
  65944. */
  65945. get: function () {
  65946. return this._blurScale;
  65947. },
  65948. /**
  65949. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65950. * 2 means half of the size.
  65951. */
  65952. set: function (value) {
  65953. if (this._blurScale === value) {
  65954. return;
  65955. }
  65956. this._blurScale = value;
  65957. this._disposeBlurPostProcesses();
  65958. },
  65959. enumerable: true,
  65960. configurable: true
  65961. });
  65962. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65963. /**
  65964. * Gets the blur kernel: kernel size of the blur pass.
  65965. * Only usefull if useKernelBlur = true
  65966. */
  65967. get: function () {
  65968. return this._blurKernel;
  65969. },
  65970. /**
  65971. * Sets the blur kernel: kernel size of the blur pass.
  65972. * Only usefull if useKernelBlur = true
  65973. */
  65974. set: function (value) {
  65975. if (this._blurKernel === value) {
  65976. return;
  65977. }
  65978. this._blurKernel = value;
  65979. this._disposeBlurPostProcesses();
  65980. },
  65981. enumerable: true,
  65982. configurable: true
  65983. });
  65984. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65985. /**
  65986. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65987. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65988. */
  65989. get: function () {
  65990. return this._useKernelBlur;
  65991. },
  65992. /**
  65993. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65994. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65995. */
  65996. set: function (value) {
  65997. if (this._useKernelBlur === value) {
  65998. return;
  65999. }
  66000. this._useKernelBlur = value;
  66001. this._disposeBlurPostProcesses();
  66002. },
  66003. enumerable: true,
  66004. configurable: true
  66005. });
  66006. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66007. /**
  66008. * Gets the depth scale used in ESM mode.
  66009. */
  66010. get: function () {
  66011. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66012. },
  66013. /**
  66014. * Sets the depth scale used in ESM mode.
  66015. * This can override the scale stored on the light.
  66016. */
  66017. set: function (value) {
  66018. this._depthScale = value;
  66019. },
  66020. enumerable: true,
  66021. configurable: true
  66022. });
  66023. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66024. /**
  66025. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66026. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66027. */
  66028. get: function () {
  66029. return this._filter;
  66030. },
  66031. /**
  66032. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66033. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66034. */
  66035. set: function (value) {
  66036. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66037. if (this._light.needCube()) {
  66038. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66039. this.useExponentialShadowMap = true;
  66040. return;
  66041. }
  66042. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66043. this.useCloseExponentialShadowMap = true;
  66044. return;
  66045. }
  66046. // PCF on cubemap would also be expensive
  66047. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66048. this.usePoissonSampling = true;
  66049. return;
  66050. }
  66051. }
  66052. // Weblg1 fallback for PCF.
  66053. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66054. if (this._scene.getEngine().webGLVersion === 1) {
  66055. this.usePoissonSampling = true;
  66056. return;
  66057. }
  66058. }
  66059. if (this._filter === value) {
  66060. return;
  66061. }
  66062. this._filter = value;
  66063. this._disposeBlurPostProcesses();
  66064. this._applyFilterValues();
  66065. this._light._markMeshesAsLightDirty();
  66066. },
  66067. enumerable: true,
  66068. configurable: true
  66069. });
  66070. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66071. /**
  66072. * Gets if the current filter is set to Poisson Sampling.
  66073. */
  66074. get: function () {
  66075. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66076. },
  66077. /**
  66078. * Sets the current filter to Poisson Sampling.
  66079. */
  66080. set: function (value) {
  66081. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66082. return;
  66083. }
  66084. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66085. },
  66086. enumerable: true,
  66087. configurable: true
  66088. });
  66089. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66090. /**
  66091. * Gets if the current filter is set to VSM.
  66092. * DEPRECATED. Should use useExponentialShadowMap instead.
  66093. */
  66094. get: function () {
  66095. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66096. return this.useExponentialShadowMap;
  66097. },
  66098. /**
  66099. * Sets the current filter is to VSM.
  66100. * DEPRECATED. Should use useExponentialShadowMap instead.
  66101. */
  66102. set: function (value) {
  66103. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66104. this.useExponentialShadowMap = value;
  66105. },
  66106. enumerable: true,
  66107. configurable: true
  66108. });
  66109. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66110. /**
  66111. * Gets if the current filter is set to blurred VSM.
  66112. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66113. */
  66114. get: function () {
  66115. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66116. return this.useBlurExponentialShadowMap;
  66117. },
  66118. /**
  66119. * Sets the current filter is to blurred VSM.
  66120. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66121. */
  66122. set: function (value) {
  66123. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66124. this.useBlurExponentialShadowMap = value;
  66125. },
  66126. enumerable: true,
  66127. configurable: true
  66128. });
  66129. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66130. /**
  66131. * Gets if the current filter is set to ESM.
  66132. */
  66133. get: function () {
  66134. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66135. },
  66136. /**
  66137. * Sets the current filter is to ESM.
  66138. */
  66139. set: function (value) {
  66140. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66141. return;
  66142. }
  66143. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66144. },
  66145. enumerable: true,
  66146. configurable: true
  66147. });
  66148. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66149. /**
  66150. * Gets if the current filter is set to filtered ESM.
  66151. */
  66152. get: function () {
  66153. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66154. },
  66155. /**
  66156. * Gets if the current filter is set to filtered ESM.
  66157. */
  66158. set: function (value) {
  66159. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66160. return;
  66161. }
  66162. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66163. },
  66164. enumerable: true,
  66165. configurable: true
  66166. });
  66167. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66168. /**
  66169. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66170. * exponential to prevent steep falloff artifacts).
  66171. */
  66172. get: function () {
  66173. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66174. },
  66175. /**
  66176. * Sets the current filter to "close ESM" (using the inverse of the
  66177. * exponential to prevent steep falloff artifacts).
  66178. */
  66179. set: function (value) {
  66180. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66181. return;
  66182. }
  66183. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66184. },
  66185. enumerable: true,
  66186. configurable: true
  66187. });
  66188. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66189. /**
  66190. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66191. * exponential to prevent steep falloff artifacts).
  66192. */
  66193. get: function () {
  66194. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66195. },
  66196. /**
  66197. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66198. * exponential to prevent steep falloff artifacts).
  66199. */
  66200. set: function (value) {
  66201. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66202. return;
  66203. }
  66204. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66205. },
  66206. enumerable: true,
  66207. configurable: true
  66208. });
  66209. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66210. /**
  66211. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66212. */
  66213. get: function () {
  66214. return this.filter === ShadowGenerator.FILTER_PCF;
  66215. },
  66216. /**
  66217. * Sets the current filter to "PCF" (percentage closer filtering).
  66218. */
  66219. set: function (value) {
  66220. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66221. return;
  66222. }
  66223. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66224. },
  66225. enumerable: true,
  66226. configurable: true
  66227. });
  66228. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66229. /**
  66230. * Gets the PCF or PCSS Quality.
  66231. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66232. */
  66233. get: function () {
  66234. return this._filteringQuality;
  66235. },
  66236. /**
  66237. * Sets the PCF or PCSS Quality.
  66238. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66239. */
  66240. set: function (filteringQuality) {
  66241. this._filteringQuality = filteringQuality;
  66242. },
  66243. enumerable: true,
  66244. configurable: true
  66245. });
  66246. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66247. /**
  66248. * Gets if the current filter is set to "PCSS" (contact hardening).
  66249. */
  66250. get: function () {
  66251. return this.filter === ShadowGenerator.FILTER_PCSS;
  66252. },
  66253. /**
  66254. * Sets the current filter to "PCSS" (contact hardening).
  66255. */
  66256. set: function (value) {
  66257. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66258. return;
  66259. }
  66260. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66261. },
  66262. enumerable: true,
  66263. configurable: true
  66264. });
  66265. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66266. /**
  66267. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66268. * Using a ratio helps keeping shape stability independently of the map size.
  66269. *
  66270. * It does not account for the light projection as it was having too much
  66271. * instability during the light setup or during light position changes.
  66272. *
  66273. * Only valid if useContactHardeningShadow is true.
  66274. */
  66275. get: function () {
  66276. return this._contactHardeningLightSizeUVRatio;
  66277. },
  66278. /**
  66279. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66280. * Using a ratio helps keeping shape stability independently of the map size.
  66281. *
  66282. * It does not account for the light projection as it was having too much
  66283. * instability during the light setup or during light position changes.
  66284. *
  66285. * Only valid if useContactHardeningShadow is true.
  66286. */
  66287. set: function (contactHardeningLightSizeUVRatio) {
  66288. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66289. },
  66290. enumerable: true,
  66291. configurable: true
  66292. });
  66293. /**
  66294. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66295. * 0 means strongest and 1 would means no shadow.
  66296. * @returns the darkness.
  66297. */
  66298. ShadowGenerator.prototype.getDarkness = function () {
  66299. return this._darkness;
  66300. };
  66301. /**
  66302. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66303. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66304. * @returns the shadow generator allowing fluent coding.
  66305. */
  66306. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66307. if (darkness >= 1.0)
  66308. this._darkness = 1.0;
  66309. else if (darkness <= 0.0)
  66310. this._darkness = 0.0;
  66311. else
  66312. this._darkness = darkness;
  66313. return this;
  66314. };
  66315. /**
  66316. * Sets the ability to have transparent shadow (boolean).
  66317. * @param transparent True if transparent else False
  66318. * @returns the shadow generator allowing fluent coding
  66319. */
  66320. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66321. this._transparencyShadow = transparent;
  66322. return this;
  66323. };
  66324. /**
  66325. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66326. * @returns The render target texture if present otherwise, null
  66327. */
  66328. ShadowGenerator.prototype.getShadowMap = function () {
  66329. return this._shadowMap;
  66330. };
  66331. /**
  66332. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66333. * @returns The render target texture if the shadow map is present otherwise, null
  66334. */
  66335. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66336. if (this._shadowMap2) {
  66337. return this._shadowMap2;
  66338. }
  66339. return this._shadowMap;
  66340. };
  66341. /**
  66342. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66343. * @param mesh Mesh to add
  66344. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66345. * @returns the Shadow Generator itself
  66346. */
  66347. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66348. if (includeDescendants === void 0) { includeDescendants = true; }
  66349. if (!this._shadowMap) {
  66350. return this;
  66351. }
  66352. if (!this._shadowMap.renderList) {
  66353. this._shadowMap.renderList = [];
  66354. }
  66355. this._shadowMap.renderList.push(mesh);
  66356. if (includeDescendants) {
  66357. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66358. }
  66359. return this;
  66360. var _a;
  66361. };
  66362. /**
  66363. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66364. * @param mesh Mesh to remove
  66365. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66366. * @returns the Shadow Generator itself
  66367. */
  66368. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66369. if (includeDescendants === void 0) { includeDescendants = true; }
  66370. if (!this._shadowMap || !this._shadowMap.renderList) {
  66371. return this;
  66372. }
  66373. var index = this._shadowMap.renderList.indexOf(mesh);
  66374. if (index !== -1) {
  66375. this._shadowMap.renderList.splice(index, 1);
  66376. }
  66377. if (includeDescendants) {
  66378. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66379. var child = _a[_i];
  66380. this.removeShadowCaster(child);
  66381. }
  66382. }
  66383. return this;
  66384. };
  66385. /**
  66386. * Returns the associated light object.
  66387. * @returns the light generating the shadow
  66388. */
  66389. ShadowGenerator.prototype.getLight = function () {
  66390. return this._light;
  66391. };
  66392. ShadowGenerator.prototype._initializeGenerator = function () {
  66393. this._light._markMeshesAsLightDirty();
  66394. this._initializeShadowMap();
  66395. };
  66396. ShadowGenerator.prototype._initializeShadowMap = function () {
  66397. var _this = this;
  66398. // Render target
  66399. var engine = this._scene.getEngine();
  66400. if (engine.webGLVersion > 1) {
  66401. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66402. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66403. }
  66404. else {
  66405. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66406. }
  66407. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66408. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66409. this._shadowMap.anisotropicFilteringLevel = 1;
  66410. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66411. this._shadowMap.renderParticles = false;
  66412. this._shadowMap.ignoreCameraViewport = true;
  66413. // Record Face Index before render.
  66414. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66415. _this._currentFaceIndex = faceIndex;
  66416. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66417. engine.setColorWrite(false);
  66418. }
  66419. });
  66420. // Custom render function.
  66421. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66422. // Blur if required afer render.
  66423. this._shadowMap.onAfterUnbindObservable.add(function () {
  66424. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66425. engine.setColorWrite(true);
  66426. }
  66427. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66428. return;
  66429. }
  66430. var shadowMap = _this.getShadowMapForRendering();
  66431. if (shadowMap) {
  66432. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66433. }
  66434. });
  66435. // Clear according to the chosen filter.
  66436. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66437. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66438. this._shadowMap.onClearObservable.add(function (engine) {
  66439. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66440. engine.clear(clearOne, false, true, false);
  66441. }
  66442. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66443. engine.clear(clearZero, true, true, false);
  66444. }
  66445. else {
  66446. engine.clear(clearOne, true, true, false);
  66447. }
  66448. });
  66449. };
  66450. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66451. var _this = this;
  66452. var engine = this._scene.getEngine();
  66453. var targetSize = this._mapSize / this.blurScale;
  66454. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66455. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66456. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66457. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66458. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66459. }
  66460. if (this.useKernelBlur) {
  66461. 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);
  66462. this._kernelBlurXPostprocess.width = targetSize;
  66463. this._kernelBlurXPostprocess.height = targetSize;
  66464. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66465. effect.setTexture("textureSampler", _this._shadowMap);
  66466. });
  66467. 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);
  66468. this._kernelBlurXPostprocess.autoClear = false;
  66469. this._kernelBlurYPostprocess.autoClear = false;
  66470. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66471. this._kernelBlurXPostprocess.packedFloat = true;
  66472. this._kernelBlurYPostprocess.packedFloat = true;
  66473. }
  66474. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66475. }
  66476. else {
  66477. 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);
  66478. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66479. effect.setFloat2("screenSize", targetSize, targetSize);
  66480. effect.setTexture("textureSampler", _this._shadowMap);
  66481. });
  66482. this._boxBlurPostprocess.autoClear = false;
  66483. this._blurPostProcesses = [this._boxBlurPostprocess];
  66484. }
  66485. };
  66486. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66487. var index;
  66488. var engine = this._scene.getEngine();
  66489. if (depthOnlySubMeshes.length) {
  66490. engine.setColorWrite(false);
  66491. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66492. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66493. }
  66494. engine.setColorWrite(true);
  66495. }
  66496. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66497. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66498. }
  66499. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66500. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66501. }
  66502. if (this._transparencyShadow) {
  66503. for (index = 0; index < transparentSubMeshes.length; index++) {
  66504. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66505. }
  66506. }
  66507. };
  66508. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66509. var _this = this;
  66510. var mesh = subMesh.getRenderingMesh();
  66511. var scene = this._scene;
  66512. var engine = scene.getEngine();
  66513. var material = subMesh.getMaterial();
  66514. if (!material) {
  66515. return;
  66516. }
  66517. // Culling
  66518. engine.setState(material.backFaceCulling);
  66519. // Managing instances
  66520. var batch = mesh._getInstancesRenderList(subMesh._id);
  66521. if (batch.mustReturn) {
  66522. return;
  66523. }
  66524. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66525. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66526. engine.enableEffect(this._effect);
  66527. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66528. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66529. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66530. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66531. this._effect.setVector3("lightData", this._cachedDirection);
  66532. }
  66533. else {
  66534. this._effect.setVector3("lightData", this._cachedPosition);
  66535. }
  66536. if (scene.activeCamera) {
  66537. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66538. }
  66539. // Alpha test
  66540. if (material && material.needAlphaTesting()) {
  66541. var alphaTexture = material.getAlphaTestTexture();
  66542. if (alphaTexture) {
  66543. this._effect.setTexture("diffuseSampler", alphaTexture);
  66544. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66545. }
  66546. }
  66547. // Bones
  66548. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66549. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66550. }
  66551. // Morph targets
  66552. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66553. if (this.forceBackFacesOnly) {
  66554. engine.setState(true, 0, false, true);
  66555. }
  66556. // Draw
  66557. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66558. if (this.forceBackFacesOnly) {
  66559. engine.setState(true, 0, false, false);
  66560. }
  66561. }
  66562. else {
  66563. // Need to reset refresh rate of the shadowMap
  66564. if (this._shadowMap) {
  66565. this._shadowMap.resetRefreshCounter();
  66566. }
  66567. }
  66568. };
  66569. ShadowGenerator.prototype._applyFilterValues = function () {
  66570. if (!this._shadowMap) {
  66571. return;
  66572. }
  66573. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66574. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66575. }
  66576. else {
  66577. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66578. }
  66579. };
  66580. /**
  66581. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66582. * @param onCompiled Callback triggered at the and of the effects compilation
  66583. * @param options Sets of optional options forcing the compilation with different modes
  66584. */
  66585. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66586. var _this = this;
  66587. var localOptions = __assign({ useInstances: false }, options);
  66588. var shadowMap = this.getShadowMap();
  66589. if (!shadowMap) {
  66590. if (onCompiled) {
  66591. onCompiled(this);
  66592. }
  66593. return;
  66594. }
  66595. var renderList = shadowMap.renderList;
  66596. if (!renderList) {
  66597. if (onCompiled) {
  66598. onCompiled(this);
  66599. }
  66600. return;
  66601. }
  66602. var subMeshes = new Array();
  66603. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66604. var mesh = renderList_1[_i];
  66605. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66606. }
  66607. if (subMeshes.length === 0) {
  66608. if (onCompiled) {
  66609. onCompiled(this);
  66610. }
  66611. return;
  66612. }
  66613. var currentIndex = 0;
  66614. var checkReady = function () {
  66615. if (!_this._scene || !_this._scene.getEngine()) {
  66616. return;
  66617. }
  66618. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66619. currentIndex++;
  66620. if (currentIndex >= subMeshes.length) {
  66621. if (onCompiled) {
  66622. onCompiled(_this);
  66623. }
  66624. return;
  66625. }
  66626. }
  66627. setTimeout(checkReady, 16);
  66628. };
  66629. checkReady();
  66630. };
  66631. /**
  66632. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66633. * @param options Sets of optional options forcing the compilation with different modes
  66634. * @returns A promise that resolves when the compilation completes
  66635. */
  66636. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66637. var _this = this;
  66638. return new Promise(function (resolve) {
  66639. _this.forceCompilation(function () {
  66640. resolve();
  66641. }, options);
  66642. });
  66643. };
  66644. /**
  66645. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66646. * @param subMesh The submesh we want to render in the shadow map
  66647. * @param useInstances Defines wether will draw in the map using instances
  66648. * @returns true if ready otherwise, false
  66649. */
  66650. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66651. var defines = [];
  66652. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66653. defines.push("#define FLOAT");
  66654. }
  66655. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66656. defines.push("#define ESM");
  66657. }
  66658. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66659. defines.push("#define DEPTHTEXTURE");
  66660. }
  66661. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66662. var mesh = subMesh.getMesh();
  66663. var material = subMesh.getMaterial();
  66664. // Normal bias.
  66665. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66666. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66667. defines.push("#define NORMAL");
  66668. if (mesh.nonUniformScaling) {
  66669. defines.push("#define NONUNIFORMSCALING");
  66670. }
  66671. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66672. defines.push("#define DIRECTIONINLIGHTDATA");
  66673. }
  66674. }
  66675. // Alpha test
  66676. if (material && material.needAlphaTesting()) {
  66677. var alphaTexture = material.getAlphaTestTexture();
  66678. if (alphaTexture) {
  66679. defines.push("#define ALPHATEST");
  66680. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66681. attribs.push(BABYLON.VertexBuffer.UVKind);
  66682. defines.push("#define UV1");
  66683. }
  66684. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66685. if (alphaTexture.coordinatesIndex === 1) {
  66686. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66687. defines.push("#define UV2");
  66688. }
  66689. }
  66690. }
  66691. }
  66692. // Bones
  66693. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66694. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66695. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66696. if (mesh.numBoneInfluencers > 4) {
  66697. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66698. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66699. }
  66700. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66701. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66702. }
  66703. else {
  66704. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66705. }
  66706. // Morph targets
  66707. var manager = mesh.morphTargetManager;
  66708. var morphInfluencers = 0;
  66709. if (manager) {
  66710. if (manager.numInfluencers > 0) {
  66711. defines.push("#define MORPHTARGETS");
  66712. morphInfluencers = manager.numInfluencers;
  66713. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66714. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66715. }
  66716. }
  66717. // Instances
  66718. if (useInstances) {
  66719. defines.push("#define INSTANCES");
  66720. attribs.push("world0");
  66721. attribs.push("world1");
  66722. attribs.push("world2");
  66723. attribs.push("world3");
  66724. }
  66725. // Get correct effect
  66726. var join = defines.join("\n");
  66727. if (this._cachedDefines !== join) {
  66728. this._cachedDefines = join;
  66729. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66730. }
  66731. if (!this._effect.isReady()) {
  66732. return false;
  66733. }
  66734. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66735. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66736. this._initializeBlurRTTAndPostProcesses();
  66737. }
  66738. }
  66739. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66740. return false;
  66741. }
  66742. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66743. return false;
  66744. }
  66745. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66746. return false;
  66747. }
  66748. return true;
  66749. };
  66750. /**
  66751. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66752. * @param defines Defines of the material we want to update
  66753. * @param lightIndex Index of the light in the enabled light list of the material
  66754. */
  66755. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66756. var scene = this._scene;
  66757. var light = this._light;
  66758. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66759. return;
  66760. }
  66761. defines["SHADOW" + lightIndex] = true;
  66762. if (this.useContactHardeningShadow) {
  66763. defines["SHADOWPCSS" + lightIndex] = true;
  66764. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66765. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66766. }
  66767. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66768. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66769. }
  66770. // else default to high.
  66771. }
  66772. if (this.usePercentageCloserFiltering) {
  66773. defines["SHADOWPCF" + lightIndex] = true;
  66774. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66775. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66776. }
  66777. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66778. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66779. }
  66780. // else default to high.
  66781. }
  66782. else if (this.usePoissonSampling) {
  66783. defines["SHADOWPOISSON" + lightIndex] = true;
  66784. }
  66785. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66786. defines["SHADOWESM" + lightIndex] = true;
  66787. }
  66788. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66789. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66790. }
  66791. if (light.needCube()) {
  66792. defines["SHADOWCUBE" + lightIndex] = true;
  66793. }
  66794. };
  66795. /**
  66796. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66797. * defined in the generator but impacting the effect).
  66798. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66799. * @param effect The effect we are binfing the information for
  66800. */
  66801. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66802. var light = this._light;
  66803. var scene = this._scene;
  66804. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66805. return;
  66806. }
  66807. var camera = scene.activeCamera;
  66808. if (!camera) {
  66809. return;
  66810. }
  66811. var shadowMap = this.getShadowMap();
  66812. if (!shadowMap) {
  66813. return;
  66814. }
  66815. if (!light.needCube()) {
  66816. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66817. }
  66818. // Only PCF uses depth stencil texture.
  66819. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66820. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66821. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66822. }
  66823. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66824. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66825. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66826. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66827. }
  66828. else {
  66829. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66830. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66831. }
  66832. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66833. };
  66834. /**
  66835. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66836. * (eq to shadow prjection matrix * light transform matrix)
  66837. * @returns The transform matrix used to create the shadow map
  66838. */
  66839. ShadowGenerator.prototype.getTransformMatrix = function () {
  66840. var scene = this._scene;
  66841. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66842. return this._transformMatrix;
  66843. }
  66844. this._currentRenderID = scene.getRenderId();
  66845. this._currentFaceIndexCache = this._currentFaceIndex;
  66846. var lightPosition = this._light.position;
  66847. if (this._light.computeTransformedInformation()) {
  66848. lightPosition = this._light.transformedPosition;
  66849. }
  66850. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66851. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66852. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66853. }
  66854. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66855. this._cachedPosition.copyFrom(lightPosition);
  66856. this._cachedDirection.copyFrom(this._lightDirection);
  66857. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66858. var shadowMap = this.getShadowMap();
  66859. if (shadowMap) {
  66860. var renderList = shadowMap.renderList;
  66861. if (renderList) {
  66862. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66863. }
  66864. }
  66865. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66866. }
  66867. return this._transformMatrix;
  66868. };
  66869. /**
  66870. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66871. * Cube and 2D textures for instance.
  66872. */
  66873. ShadowGenerator.prototype.recreateShadowMap = function () {
  66874. var shadowMap = this._shadowMap;
  66875. if (!shadowMap) {
  66876. return;
  66877. }
  66878. // Track render list.
  66879. var renderList = shadowMap.renderList;
  66880. // Clean up existing data.
  66881. this._disposeRTTandPostProcesses();
  66882. // Reinitializes.
  66883. this._initializeGenerator();
  66884. // Reaffect the filter to ensure a correct fallback if necessary.
  66885. this.filter = this.filter;
  66886. // Reaffect the filter.
  66887. this._applyFilterValues();
  66888. // Reaffect Render List.
  66889. this._shadowMap.renderList = renderList;
  66890. };
  66891. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66892. if (this._shadowMap2) {
  66893. this._shadowMap2.dispose();
  66894. this._shadowMap2 = null;
  66895. }
  66896. if (this._boxBlurPostprocess) {
  66897. this._boxBlurPostprocess.dispose();
  66898. this._boxBlurPostprocess = null;
  66899. }
  66900. if (this._kernelBlurXPostprocess) {
  66901. this._kernelBlurXPostprocess.dispose();
  66902. this._kernelBlurXPostprocess = null;
  66903. }
  66904. if (this._kernelBlurYPostprocess) {
  66905. this._kernelBlurYPostprocess.dispose();
  66906. this._kernelBlurYPostprocess = null;
  66907. }
  66908. this._blurPostProcesses = [];
  66909. };
  66910. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66911. if (this._shadowMap) {
  66912. this._shadowMap.dispose();
  66913. this._shadowMap = null;
  66914. }
  66915. this._disposeBlurPostProcesses();
  66916. };
  66917. /**
  66918. * Disposes the ShadowGenerator.
  66919. * Returns nothing.
  66920. */
  66921. ShadowGenerator.prototype.dispose = function () {
  66922. this._disposeRTTandPostProcesses();
  66923. if (this._light) {
  66924. this._light._shadowGenerator = null;
  66925. this._light._markMeshesAsLightDirty();
  66926. }
  66927. };
  66928. /**
  66929. * Serializes the shadow generator setup to a json object.
  66930. * @returns The serialized JSON object
  66931. */
  66932. ShadowGenerator.prototype.serialize = function () {
  66933. var serializationObject = {};
  66934. var shadowMap = this.getShadowMap();
  66935. if (!shadowMap) {
  66936. return serializationObject;
  66937. }
  66938. serializationObject.lightId = this._light.id;
  66939. serializationObject.mapSize = shadowMap.getRenderSize();
  66940. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66941. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66942. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66943. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66944. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66945. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66946. serializationObject.depthScale = this.depthScale;
  66947. serializationObject.darkness = this.getDarkness();
  66948. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66949. serializationObject.blurKernel = this.blurKernel;
  66950. serializationObject.blurScale = this.blurScale;
  66951. serializationObject.useKernelBlur = this.useKernelBlur;
  66952. serializationObject.transparencyShadow = this._transparencyShadow;
  66953. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  66954. serializationObject.bias = this.bias;
  66955. serializationObject.normalBias = this.normalBias;
  66956. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66957. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66958. serializationObject.filteringQuality = this.filteringQuality;
  66959. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66960. serializationObject.renderList = [];
  66961. if (shadowMap.renderList) {
  66962. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66963. var mesh = shadowMap.renderList[meshIndex];
  66964. serializationObject.renderList.push(mesh.id);
  66965. }
  66966. }
  66967. return serializationObject;
  66968. };
  66969. /**
  66970. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66971. * @param parsedShadowGenerator The JSON object to parse
  66972. * @param scene The scene to create the shadow map for
  66973. * @returns The parsed shadow generator
  66974. */
  66975. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66976. //casting to point light, as light is missing the position attr and typescript complains.
  66977. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66978. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66979. var shadowMap = shadowGenerator.getShadowMap();
  66980. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66981. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66982. meshes.forEach(function (mesh) {
  66983. if (!shadowMap) {
  66984. return;
  66985. }
  66986. if (!shadowMap.renderList) {
  66987. shadowMap.renderList = [];
  66988. }
  66989. shadowMap.renderList.push(mesh);
  66990. });
  66991. }
  66992. if (parsedShadowGenerator.usePoissonSampling) {
  66993. shadowGenerator.usePoissonSampling = true;
  66994. }
  66995. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66996. shadowGenerator.useExponentialShadowMap = true;
  66997. }
  66998. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66999. shadowGenerator.useBlurExponentialShadowMap = true;
  67000. }
  67001. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67002. shadowGenerator.useCloseExponentialShadowMap = true;
  67003. }
  67004. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67005. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67006. }
  67007. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67008. shadowGenerator.usePercentageCloserFiltering = true;
  67009. }
  67010. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67011. shadowGenerator.useContactHardeningShadow = true;
  67012. }
  67013. if (parsedShadowGenerator.filteringQuality) {
  67014. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67015. }
  67016. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67017. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67018. }
  67019. // Backward compat
  67020. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67021. shadowGenerator.useExponentialShadowMap = true;
  67022. }
  67023. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67024. shadowGenerator.useBlurExponentialShadowMap = true;
  67025. }
  67026. if (parsedShadowGenerator.depthScale) {
  67027. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67028. }
  67029. if (parsedShadowGenerator.blurScale) {
  67030. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67031. }
  67032. if (parsedShadowGenerator.blurBoxOffset) {
  67033. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67034. }
  67035. if (parsedShadowGenerator.useKernelBlur) {
  67036. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67037. }
  67038. if (parsedShadowGenerator.blurKernel) {
  67039. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67040. }
  67041. if (parsedShadowGenerator.bias !== undefined) {
  67042. shadowGenerator.bias = parsedShadowGenerator.bias;
  67043. }
  67044. if (parsedShadowGenerator.normalBias !== undefined) {
  67045. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67046. }
  67047. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67048. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67049. }
  67050. if (parsedShadowGenerator.darkness) {
  67051. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67052. }
  67053. if (parsedShadowGenerator.transparencyShadow) {
  67054. shadowGenerator.setTransparencyShadow(true);
  67055. }
  67056. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67057. return shadowGenerator;
  67058. };
  67059. /**
  67060. * Shadow generator mode None: no filtering applied.
  67061. */
  67062. ShadowGenerator.FILTER_NONE = 0;
  67063. /**
  67064. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67065. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67066. */
  67067. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67068. /**
  67069. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67070. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67071. */
  67072. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67073. /**
  67074. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67075. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67076. */
  67077. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67078. /**
  67079. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67080. * edge artifacts on steep falloff.
  67081. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67082. */
  67083. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67084. /**
  67085. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67086. * edge artifacts on steep falloff.
  67087. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67088. */
  67089. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67090. /**
  67091. * Shadow generator mode PCF: Percentage Closer Filtering
  67092. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67093. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67094. */
  67095. ShadowGenerator.FILTER_PCF = 6;
  67096. /**
  67097. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67098. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67099. * Contact Hardening
  67100. */
  67101. ShadowGenerator.FILTER_PCSS = 7;
  67102. /**
  67103. * Reserved for PCF and PCSS
  67104. * Highest Quality.
  67105. *
  67106. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67107. *
  67108. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67109. */
  67110. ShadowGenerator.QUALITY_HIGH = 0;
  67111. /**
  67112. * Reserved for PCF and PCSS
  67113. * Good tradeoff for quality/perf cross devices
  67114. *
  67115. * Execute PCF on a 3*3 kernel.
  67116. *
  67117. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67118. */
  67119. ShadowGenerator.QUALITY_MEDIUM = 1;
  67120. /**
  67121. * Reserved for PCF and PCSS
  67122. * The lowest quality but the fastest.
  67123. *
  67124. * Execute PCF on a 1*1 kernel.
  67125. *
  67126. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67127. */
  67128. ShadowGenerator.QUALITY_LOW = 2;
  67129. return ShadowGenerator;
  67130. }());
  67131. BABYLON.ShadowGenerator = ShadowGenerator;
  67132. })(BABYLON || (BABYLON = {}));
  67133. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67134. var BABYLON;
  67135. (function (BABYLON) {
  67136. var DefaultLoadingScreen = /** @class */ (function () {
  67137. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67138. if (_loadingText === void 0) { _loadingText = ""; }
  67139. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67140. var _this = this;
  67141. this._renderingCanvas = _renderingCanvas;
  67142. this._loadingText = _loadingText;
  67143. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67144. // Resize
  67145. this._resizeLoadingUI = function () {
  67146. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67147. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67148. if (!_this._loadingDiv) {
  67149. return;
  67150. }
  67151. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67152. _this._loadingDiv.style.left = canvasRect.left + "px";
  67153. _this._loadingDiv.style.top = canvasRect.top + "px";
  67154. _this._loadingDiv.style.width = canvasRect.width + "px";
  67155. _this._loadingDiv.style.height = canvasRect.height + "px";
  67156. };
  67157. }
  67158. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67159. if (this._loadingDiv) {
  67160. // Do not add a loading screen if there is already one
  67161. return;
  67162. }
  67163. this._loadingDiv = document.createElement("div");
  67164. this._loadingDiv.id = "babylonjsLoadingDiv";
  67165. this._loadingDiv.style.opacity = "0";
  67166. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67167. this._loadingDiv.style.pointerEvents = "none";
  67168. // Loading text
  67169. this._loadingTextDiv = document.createElement("div");
  67170. this._loadingTextDiv.style.position = "absolute";
  67171. this._loadingTextDiv.style.left = "0";
  67172. this._loadingTextDiv.style.top = "50%";
  67173. this._loadingTextDiv.style.marginTop = "80px";
  67174. this._loadingTextDiv.style.width = "100%";
  67175. this._loadingTextDiv.style.height = "20px";
  67176. this._loadingTextDiv.style.fontFamily = "Arial";
  67177. this._loadingTextDiv.style.fontSize = "14px";
  67178. this._loadingTextDiv.style.color = "white";
  67179. this._loadingTextDiv.style.textAlign = "center";
  67180. this._loadingTextDiv.innerHTML = "Loading";
  67181. this._loadingDiv.appendChild(this._loadingTextDiv);
  67182. //set the predefined text
  67183. this._loadingTextDiv.innerHTML = this._loadingText;
  67184. // Generating keyframes
  67185. var style = document.createElement('style');
  67186. style.type = 'text/css';
  67187. 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 }";
  67188. style.innerHTML = keyFrames;
  67189. document.getElementsByTagName('head')[0].appendChild(style);
  67190. // Loading img
  67191. var imgBack = new Image();
  67192. 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";
  67193. imgBack.style.position = "absolute";
  67194. imgBack.style.left = "50%";
  67195. imgBack.style.top = "50%";
  67196. imgBack.style.marginLeft = "-60px";
  67197. imgBack.style.marginTop = "-60px";
  67198. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67199. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67200. imgBack.style.transformOrigin = "50% 50%";
  67201. imgBack.style.webkitTransformOrigin = "50% 50%";
  67202. this._loadingDiv.appendChild(imgBack);
  67203. this._resizeLoadingUI();
  67204. window.addEventListener("resize", this._resizeLoadingUI);
  67205. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67206. document.body.appendChild(this._loadingDiv);
  67207. this._loadingDiv.style.opacity = "1";
  67208. };
  67209. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67210. var _this = this;
  67211. if (!this._loadingDiv) {
  67212. return;
  67213. }
  67214. var onTransitionEnd = function () {
  67215. if (!_this._loadingDiv) {
  67216. return;
  67217. }
  67218. document.body.removeChild(_this._loadingDiv);
  67219. window.removeEventListener("resize", _this._resizeLoadingUI);
  67220. _this._loadingDiv = null;
  67221. };
  67222. this._loadingDiv.style.opacity = "0";
  67223. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67224. };
  67225. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67226. set: function (text) {
  67227. this._loadingText = text;
  67228. if (this._loadingTextDiv) {
  67229. this._loadingTextDiv.innerHTML = this._loadingText;
  67230. }
  67231. },
  67232. enumerable: true,
  67233. configurable: true
  67234. });
  67235. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67236. get: function () {
  67237. return this._loadingDivBackgroundColor;
  67238. },
  67239. set: function (color) {
  67240. this._loadingDivBackgroundColor = color;
  67241. if (!this._loadingDiv) {
  67242. return;
  67243. }
  67244. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67245. },
  67246. enumerable: true,
  67247. configurable: true
  67248. });
  67249. return DefaultLoadingScreen;
  67250. }());
  67251. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67252. })(BABYLON || (BABYLON = {}));
  67253. //# sourceMappingURL=babylon.loadingScreen.js.map
  67254. var BABYLON;
  67255. (function (BABYLON) {
  67256. var SceneLoaderProgressEvent = /** @class */ (function () {
  67257. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67258. this.lengthComputable = lengthComputable;
  67259. this.loaded = loaded;
  67260. this.total = total;
  67261. }
  67262. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67263. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67264. };
  67265. return SceneLoaderProgressEvent;
  67266. }());
  67267. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67268. var SceneLoader = /** @class */ (function () {
  67269. function SceneLoader() {
  67270. }
  67271. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67272. get: function () {
  67273. return 0;
  67274. },
  67275. enumerable: true,
  67276. configurable: true
  67277. });
  67278. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67279. get: function () {
  67280. return 1;
  67281. },
  67282. enumerable: true,
  67283. configurable: true
  67284. });
  67285. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67286. get: function () {
  67287. return 2;
  67288. },
  67289. enumerable: true,
  67290. configurable: true
  67291. });
  67292. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67293. get: function () {
  67294. return 3;
  67295. },
  67296. enumerable: true,
  67297. configurable: true
  67298. });
  67299. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67300. get: function () {
  67301. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67302. },
  67303. set: function (value) {
  67304. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67305. },
  67306. enumerable: true,
  67307. configurable: true
  67308. });
  67309. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67310. get: function () {
  67311. return SceneLoader._ShowLoadingScreen;
  67312. },
  67313. set: function (value) {
  67314. SceneLoader._ShowLoadingScreen = value;
  67315. },
  67316. enumerable: true,
  67317. configurable: true
  67318. });
  67319. Object.defineProperty(SceneLoader, "loggingLevel", {
  67320. get: function () {
  67321. return SceneLoader._loggingLevel;
  67322. },
  67323. set: function (value) {
  67324. SceneLoader._loggingLevel = value;
  67325. },
  67326. enumerable: true,
  67327. configurable: true
  67328. });
  67329. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67330. get: function () {
  67331. return SceneLoader._CleanBoneMatrixWeights;
  67332. },
  67333. set: function (value) {
  67334. SceneLoader._CleanBoneMatrixWeights = value;
  67335. },
  67336. enumerable: true,
  67337. configurable: true
  67338. });
  67339. SceneLoader._getDefaultPlugin = function () {
  67340. return SceneLoader._registeredPlugins[".babylon"];
  67341. };
  67342. SceneLoader._getPluginForExtension = function (extension) {
  67343. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67344. if (registeredPlugin) {
  67345. return registeredPlugin;
  67346. }
  67347. 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");
  67348. return SceneLoader._getDefaultPlugin();
  67349. };
  67350. SceneLoader._getPluginForDirectLoad = function (data) {
  67351. for (var extension in SceneLoader._registeredPlugins) {
  67352. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67353. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67354. return SceneLoader._registeredPlugins[extension];
  67355. }
  67356. }
  67357. return SceneLoader._getDefaultPlugin();
  67358. };
  67359. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67360. if (sceneFilename.name) {
  67361. sceneFilename = sceneFilename.name;
  67362. }
  67363. var queryStringPosition = sceneFilename.indexOf("?");
  67364. if (queryStringPosition !== -1) {
  67365. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67366. }
  67367. var dotPosition = sceneFilename.lastIndexOf(".");
  67368. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67369. return SceneLoader._getPluginForExtension(extension);
  67370. };
  67371. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67372. SceneLoader._getDirectLoad = function (sceneFilename) {
  67373. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67374. return sceneFilename.substr(5);
  67375. }
  67376. return null;
  67377. };
  67378. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67379. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67380. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67381. var plugin;
  67382. if (registeredPlugin.plugin.createPlugin) {
  67383. plugin = registeredPlugin.plugin.createPlugin();
  67384. }
  67385. else {
  67386. plugin = registeredPlugin.plugin;
  67387. }
  67388. var useArrayBuffer = registeredPlugin.isBinary;
  67389. var database;
  67390. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67391. var dataCallback = function (data, responseURL) {
  67392. if (scene.isDisposed) {
  67393. onError("Scene has been disposed");
  67394. return;
  67395. }
  67396. scene.database = database;
  67397. onSuccess(plugin, data, responseURL);
  67398. };
  67399. var request = null;
  67400. var pluginDisposed = false;
  67401. var onDisposeObservable = plugin.onDisposeObservable;
  67402. if (onDisposeObservable) {
  67403. onDisposeObservable.add(function () {
  67404. pluginDisposed = true;
  67405. if (request) {
  67406. request.abort();
  67407. request = null;
  67408. }
  67409. onDispose();
  67410. });
  67411. }
  67412. var manifestChecked = function () {
  67413. if (pluginDisposed) {
  67414. return;
  67415. }
  67416. var url = rootUrl + sceneFilename;
  67417. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67418. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67419. } : undefined, database, useArrayBuffer, function (request, exception) {
  67420. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67421. });
  67422. };
  67423. if (directLoad) {
  67424. dataCallback(directLoad);
  67425. return plugin;
  67426. }
  67427. if (rootUrl.indexOf("file:") === -1) {
  67428. var engine = scene.getEngine();
  67429. var canUseOfflineSupport = engine.enableOfflineSupport;
  67430. if (canUseOfflineSupport) {
  67431. // Also check for exceptions
  67432. var exceptionFound = false;
  67433. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67434. var regex = _a[_i];
  67435. if (regex.test(rootUrl + sceneFilename)) {
  67436. exceptionFound = true;
  67437. break;
  67438. }
  67439. }
  67440. canUseOfflineSupport = !exceptionFound;
  67441. }
  67442. if (canUseOfflineSupport) {
  67443. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67444. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67445. }
  67446. else {
  67447. manifestChecked();
  67448. }
  67449. }
  67450. // Loading file from disk via input file or drag'n'drop
  67451. else {
  67452. var fileOrString = sceneFilename;
  67453. if (fileOrString.name) { // File
  67454. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67455. }
  67456. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67457. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67458. }
  67459. else {
  67460. onError("Unable to find file named " + sceneFilename);
  67461. }
  67462. }
  67463. return plugin;
  67464. };
  67465. // Public functions
  67466. SceneLoader.GetPluginForExtension = function (extension) {
  67467. return SceneLoader._getPluginForExtension(extension).plugin;
  67468. };
  67469. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67470. return !!SceneLoader._registeredPlugins[extension];
  67471. };
  67472. SceneLoader.RegisterPlugin = function (plugin) {
  67473. if (typeof plugin.extensions === "string") {
  67474. var extension = plugin.extensions;
  67475. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67476. plugin: plugin,
  67477. isBinary: false
  67478. };
  67479. }
  67480. else {
  67481. var extensions = plugin.extensions;
  67482. Object.keys(extensions).forEach(function (extension) {
  67483. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67484. plugin: plugin,
  67485. isBinary: extensions[extension].isBinary
  67486. };
  67487. });
  67488. }
  67489. };
  67490. /**
  67491. * Import meshes into a scene
  67492. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67493. * @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)
  67494. * @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)
  67495. * @param scene the instance of BABYLON.Scene to append to
  67496. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67497. * @param onProgress a callback with a progress event for each file being loaded
  67498. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67499. * @param pluginExtension the extension used to determine the plugin
  67500. * @returns The loaded plugin
  67501. */
  67502. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67503. if (sceneFilename === void 0) { sceneFilename = ""; }
  67504. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67505. if (onSuccess === void 0) { onSuccess = null; }
  67506. if (onProgress === void 0) { onProgress = null; }
  67507. if (onError === void 0) { onError = null; }
  67508. if (pluginExtension === void 0) { pluginExtension = null; }
  67509. if (!scene) {
  67510. BABYLON.Tools.Error("No scene available to import mesh to");
  67511. return null;
  67512. }
  67513. if (!sceneFilename) {
  67514. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67515. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67516. }
  67517. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67518. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67519. return null;
  67520. }
  67521. var loadingToken = {};
  67522. scene._addPendingData(loadingToken);
  67523. var disposeHandler = function () {
  67524. scene._removePendingData(loadingToken);
  67525. };
  67526. var errorHandler = function (message, exception) {
  67527. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67528. if (onError) {
  67529. onError(scene, errorMessage, exception);
  67530. }
  67531. else {
  67532. BABYLON.Tools.Error(errorMessage);
  67533. // should the exception be thrown?
  67534. }
  67535. disposeHandler();
  67536. };
  67537. var progressHandler = onProgress ? function (event) {
  67538. try {
  67539. onProgress(event);
  67540. }
  67541. catch (e) {
  67542. errorHandler("Error in onProgress callback", e);
  67543. }
  67544. } : undefined;
  67545. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67546. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67547. if (onSuccess) {
  67548. try {
  67549. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67550. }
  67551. catch (e) {
  67552. errorHandler("Error in onSuccess callback", e);
  67553. }
  67554. }
  67555. scene._removePendingData(loadingToken);
  67556. };
  67557. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67558. if (plugin.rewriteRootURL) {
  67559. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67560. }
  67561. if (sceneFilename === "") {
  67562. if (sceneFilename === "") {
  67563. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67564. }
  67565. }
  67566. if (plugin.importMesh) {
  67567. var syncedPlugin = plugin;
  67568. var meshes = new Array();
  67569. var particleSystems = new Array();
  67570. var skeletons = new Array();
  67571. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67572. return;
  67573. }
  67574. scene.loadingPluginName = plugin.name;
  67575. successHandler(meshes, particleSystems, skeletons, []);
  67576. }
  67577. else {
  67578. var asyncedPlugin = plugin;
  67579. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67580. scene.loadingPluginName = plugin.name;
  67581. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67582. }).catch(function (error) {
  67583. errorHandler(error.message, error);
  67584. });
  67585. }
  67586. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67587. };
  67588. /**
  67589. * Import meshes into a scene
  67590. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67591. * @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)
  67592. * @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)
  67593. * @param scene the instance of BABYLON.Scene to append to
  67594. * @param onProgress a callback with a progress event for each file being loaded
  67595. * @param pluginExtension the extension used to determine the plugin
  67596. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67597. */
  67598. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67599. if (sceneFilename === void 0) { sceneFilename = ""; }
  67600. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67601. if (onProgress === void 0) { onProgress = null; }
  67602. if (pluginExtension === void 0) { pluginExtension = null; }
  67603. return new Promise(function (resolve, reject) {
  67604. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67605. resolve({
  67606. meshes: meshes,
  67607. particleSystems: particleSystems,
  67608. skeletons: skeletons,
  67609. animationGroups: animationGroups
  67610. });
  67611. }, onProgress, function (scene, message, exception) {
  67612. reject(exception || new Error(message));
  67613. }, pluginExtension);
  67614. });
  67615. };
  67616. /**
  67617. * Load a scene
  67618. * @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)
  67619. * @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)
  67620. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67621. * @param onSuccess a callback with the scene when import succeeds
  67622. * @param onProgress a callback with a progress event for each file being loaded
  67623. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67624. * @param pluginExtension the extension used to determine the plugin
  67625. * @returns The loaded plugin
  67626. */
  67627. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67628. if (onSuccess === void 0) { onSuccess = null; }
  67629. if (onProgress === void 0) { onProgress = null; }
  67630. if (onError === void 0) { onError = null; }
  67631. if (pluginExtension === void 0) { pluginExtension = null; }
  67632. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67633. };
  67634. /**
  67635. * Load a scene
  67636. * @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)
  67637. * @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)
  67638. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67639. * @param onProgress a callback with a progress event for each file being loaded
  67640. * @param pluginExtension the extension used to determine the plugin
  67641. * @returns The loaded scene
  67642. */
  67643. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67644. if (onProgress === void 0) { onProgress = null; }
  67645. if (pluginExtension === void 0) { pluginExtension = null; }
  67646. return new Promise(function (resolve, reject) {
  67647. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67648. resolve(scene);
  67649. }, onProgress, function (scene, message, exception) {
  67650. reject(exception || new Error(message));
  67651. }, pluginExtension);
  67652. });
  67653. };
  67654. /**
  67655. * Append a scene
  67656. * @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)
  67657. * @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)
  67658. * @param scene is the instance of BABYLON.Scene to append to
  67659. * @param onSuccess a callback with the scene when import succeeds
  67660. * @param onProgress a callback with a progress event for each file being loaded
  67661. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67662. * @param pluginExtension the extension used to determine the plugin
  67663. * @returns The loaded plugin
  67664. */
  67665. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67666. if (sceneFilename === void 0) { sceneFilename = ""; }
  67667. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67668. if (onSuccess === void 0) { onSuccess = null; }
  67669. if (onProgress === void 0) { onProgress = null; }
  67670. if (onError === void 0) { onError = null; }
  67671. if (pluginExtension === void 0) { pluginExtension = null; }
  67672. if (!scene) {
  67673. BABYLON.Tools.Error("No scene available to append to");
  67674. return null;
  67675. }
  67676. if (!sceneFilename) {
  67677. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67678. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67679. }
  67680. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67681. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67682. return null;
  67683. }
  67684. if (SceneLoader.ShowLoadingScreen) {
  67685. scene.getEngine().displayLoadingUI();
  67686. }
  67687. var loadingToken = {};
  67688. scene._addPendingData(loadingToken);
  67689. var disposeHandler = function () {
  67690. scene._removePendingData(loadingToken);
  67691. scene.getEngine().hideLoadingUI();
  67692. };
  67693. var errorHandler = function (message, exception) {
  67694. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67695. if (onError) {
  67696. onError(scene, errorMessage, exception);
  67697. }
  67698. else {
  67699. BABYLON.Tools.Error(errorMessage);
  67700. // should the exception be thrown?
  67701. }
  67702. disposeHandler();
  67703. };
  67704. var progressHandler = onProgress ? function (event) {
  67705. try {
  67706. onProgress(event);
  67707. }
  67708. catch (e) {
  67709. errorHandler("Error in onProgress callback", e);
  67710. }
  67711. } : undefined;
  67712. var successHandler = function () {
  67713. if (onSuccess) {
  67714. try {
  67715. onSuccess(scene);
  67716. }
  67717. catch (e) {
  67718. errorHandler("Error in onSuccess callback", e);
  67719. }
  67720. }
  67721. scene._removePendingData(loadingToken);
  67722. };
  67723. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67724. if (sceneFilename === "") {
  67725. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67726. }
  67727. if (plugin.load) {
  67728. var syncedPlugin = plugin;
  67729. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67730. return;
  67731. }
  67732. scene.loadingPluginName = plugin.name;
  67733. successHandler();
  67734. }
  67735. else {
  67736. var asyncedPlugin = plugin;
  67737. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67738. scene.loadingPluginName = plugin.name;
  67739. successHandler();
  67740. }).catch(function (error) {
  67741. errorHandler(error.message, error);
  67742. });
  67743. }
  67744. if (SceneLoader.ShowLoadingScreen) {
  67745. scene.executeWhenReady(function () {
  67746. scene.getEngine().hideLoadingUI();
  67747. });
  67748. }
  67749. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67750. };
  67751. /**
  67752. * Append a scene
  67753. * @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)
  67754. * @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)
  67755. * @param scene is the instance of BABYLON.Scene to append to
  67756. * @param onProgress a callback with a progress event for each file being loaded
  67757. * @param pluginExtension the extension used to determine the plugin
  67758. * @returns The given scene
  67759. */
  67760. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67761. if (sceneFilename === void 0) { sceneFilename = ""; }
  67762. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67763. if (onProgress === void 0) { onProgress = null; }
  67764. if (pluginExtension === void 0) { pluginExtension = null; }
  67765. return new Promise(function (resolve, reject) {
  67766. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67767. resolve(scene);
  67768. }, onProgress, function (scene, message, exception) {
  67769. reject(exception || new Error(message));
  67770. }, pluginExtension);
  67771. });
  67772. };
  67773. /**
  67774. * Load a scene into an asset container
  67775. * @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)
  67776. * @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)
  67777. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67778. * @param onSuccess a callback with the scene when import succeeds
  67779. * @param onProgress a callback with a progress event for each file being loaded
  67780. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67781. * @param pluginExtension the extension used to determine the plugin
  67782. * @returns The loaded plugin
  67783. */
  67784. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67785. if (sceneFilename === void 0) { sceneFilename = ""; }
  67786. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67787. if (onSuccess === void 0) { onSuccess = null; }
  67788. if (onProgress === void 0) { onProgress = null; }
  67789. if (onError === void 0) { onError = null; }
  67790. if (pluginExtension === void 0) { pluginExtension = null; }
  67791. if (!scene) {
  67792. BABYLON.Tools.Error("No scene available to load asset container to");
  67793. return null;
  67794. }
  67795. if (!sceneFilename) {
  67796. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67797. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67798. }
  67799. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67800. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67801. return null;
  67802. }
  67803. var loadingToken = {};
  67804. scene._addPendingData(loadingToken);
  67805. var disposeHandler = function () {
  67806. scene._removePendingData(loadingToken);
  67807. };
  67808. var errorHandler = function (message, exception) {
  67809. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67810. if (onError) {
  67811. onError(scene, errorMessage, exception);
  67812. }
  67813. else {
  67814. BABYLON.Tools.Error(errorMessage);
  67815. // should the exception be thrown?
  67816. }
  67817. disposeHandler();
  67818. };
  67819. var progressHandler = onProgress ? function (event) {
  67820. try {
  67821. onProgress(event);
  67822. }
  67823. catch (e) {
  67824. errorHandler("Error in onProgress callback", e);
  67825. }
  67826. } : undefined;
  67827. var successHandler = function (assets) {
  67828. if (onSuccess) {
  67829. try {
  67830. onSuccess(assets);
  67831. }
  67832. catch (e) {
  67833. errorHandler("Error in onSuccess callback", e);
  67834. }
  67835. }
  67836. scene._removePendingData(loadingToken);
  67837. };
  67838. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67839. if (plugin.loadAssetContainer) {
  67840. var syncedPlugin = plugin;
  67841. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67842. if (!assetContainer) {
  67843. return;
  67844. }
  67845. scene.loadingPluginName = plugin.name;
  67846. successHandler(assetContainer);
  67847. }
  67848. else if (plugin.loadAssetContainerAsync) {
  67849. var asyncedPlugin = plugin;
  67850. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67851. scene.loadingPluginName = plugin.name;
  67852. successHandler(assetContainer);
  67853. }).catch(function (error) {
  67854. errorHandler(error.message, error);
  67855. });
  67856. }
  67857. else {
  67858. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67859. }
  67860. if (SceneLoader.ShowLoadingScreen) {
  67861. scene.executeWhenReady(function () {
  67862. scene.getEngine().hideLoadingUI();
  67863. });
  67864. }
  67865. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67866. };
  67867. /**
  67868. * Load a scene into an asset container
  67869. * @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)
  67870. * @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)
  67871. * @param scene is the instance of BABYLON.Scene to append to
  67872. * @param onProgress a callback with a progress event for each file being loaded
  67873. * @param pluginExtension the extension used to determine the plugin
  67874. * @returns The loaded asset container
  67875. */
  67876. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67877. if (sceneFilename === void 0) { sceneFilename = ""; }
  67878. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67879. if (onProgress === void 0) { onProgress = null; }
  67880. if (pluginExtension === void 0) { pluginExtension = null; }
  67881. return new Promise(function (resolve, reject) {
  67882. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67883. resolve(assetContainer);
  67884. }, onProgress, function (scene, message, exception) {
  67885. reject(exception || new Error(message));
  67886. }, pluginExtension);
  67887. });
  67888. };
  67889. // Flags
  67890. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67891. SceneLoader._ShowLoadingScreen = true;
  67892. SceneLoader._CleanBoneMatrixWeights = false;
  67893. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67894. // Members
  67895. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67896. SceneLoader._registeredPlugins = {};
  67897. return SceneLoader;
  67898. }());
  67899. BABYLON.SceneLoader = SceneLoader;
  67900. ;
  67901. })(BABYLON || (BABYLON = {}));
  67902. //# sourceMappingURL=babylon.sceneLoader.js.map
  67903. var BABYLON;
  67904. (function (BABYLON) {
  67905. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67906. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67907. var parsedMaterial = parsedData.materials[index];
  67908. if (parsedMaterial.id === id) {
  67909. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67910. }
  67911. }
  67912. return null;
  67913. };
  67914. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67915. for (var i in names) {
  67916. if (mesh.name === names[i]) {
  67917. hierarchyIds.push(mesh.id);
  67918. return true;
  67919. }
  67920. }
  67921. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67922. hierarchyIds.push(mesh.id);
  67923. return true;
  67924. }
  67925. return false;
  67926. };
  67927. var logOperation = function (operation, producer) {
  67928. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67929. };
  67930. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67931. if (addToScene === void 0) { addToScene = false; }
  67932. var container = new BABYLON.AssetContainer(scene);
  67933. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67934. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67935. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67936. // and avoid problems with multiple concurrent .babylon loads.
  67937. var log = "importScene has failed JSON parse";
  67938. try {
  67939. var parsedData = JSON.parse(data);
  67940. log = "";
  67941. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67942. var index;
  67943. var cache;
  67944. // Lights
  67945. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67946. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67947. var parsedLight = parsedData.lights[index];
  67948. var light = BABYLON.Light.Parse(parsedLight, scene);
  67949. if (light) {
  67950. container.lights.push(light);
  67951. log += (index === 0 ? "\n\tLights:" : "");
  67952. log += "\n\t\t" + light.toString(fullDetails);
  67953. }
  67954. }
  67955. }
  67956. // Animations
  67957. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67958. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67959. var parsedAnimation = parsedData.animations[index];
  67960. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67961. scene.animations.push(animation);
  67962. container.animations.push(animation);
  67963. log += (index === 0 ? "\n\tAnimations:" : "");
  67964. log += "\n\t\t" + animation.toString(fullDetails);
  67965. }
  67966. }
  67967. // Materials
  67968. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67969. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67970. var parsedMaterial = parsedData.materials[index];
  67971. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67972. container.materials.push(mat);
  67973. log += (index === 0 ? "\n\tMaterials:" : "");
  67974. log += "\n\t\t" + mat.toString(fullDetails);
  67975. }
  67976. }
  67977. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67978. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67979. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67980. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67981. container.multiMaterials.push(mmat);
  67982. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67983. log += "\n\t\t" + mmat.toString(fullDetails);
  67984. }
  67985. }
  67986. // Morph targets
  67987. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67988. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67989. var managerData = _a[_i];
  67990. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67991. }
  67992. }
  67993. // Skeletons
  67994. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67995. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67996. var parsedSkeleton = parsedData.skeletons[index];
  67997. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67998. container.skeletons.push(skeleton);
  67999. log += (index === 0 ? "\n\tSkeletons:" : "");
  68000. log += "\n\t\t" + skeleton.toString(fullDetails);
  68001. }
  68002. }
  68003. // Geometries
  68004. var geometries = parsedData.geometries;
  68005. if (geometries !== undefined && geometries !== null) {
  68006. var addedGeometry = new Array();
  68007. // Boxes
  68008. var boxes = geometries.boxes;
  68009. if (boxes !== undefined && boxes !== null) {
  68010. for (index = 0, cache = boxes.length; index < cache; index++) {
  68011. var parsedBox = boxes[index];
  68012. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68013. }
  68014. }
  68015. // Spheres
  68016. var spheres = geometries.spheres;
  68017. if (spheres !== undefined && spheres !== null) {
  68018. for (index = 0, cache = spheres.length; index < cache; index++) {
  68019. var parsedSphere = spheres[index];
  68020. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68021. }
  68022. }
  68023. // Cylinders
  68024. var cylinders = geometries.cylinders;
  68025. if (cylinders !== undefined && cylinders !== null) {
  68026. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68027. var parsedCylinder = cylinders[index];
  68028. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68029. }
  68030. }
  68031. // Toruses
  68032. var toruses = geometries.toruses;
  68033. if (toruses !== undefined && toruses !== null) {
  68034. for (index = 0, cache = toruses.length; index < cache; index++) {
  68035. var parsedTorus = toruses[index];
  68036. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68037. }
  68038. }
  68039. // Grounds
  68040. var grounds = geometries.grounds;
  68041. if (grounds !== undefined && grounds !== null) {
  68042. for (index = 0, cache = grounds.length; index < cache; index++) {
  68043. var parsedGround = grounds[index];
  68044. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68045. }
  68046. }
  68047. // Planes
  68048. var planes = geometries.planes;
  68049. if (planes !== undefined && planes !== null) {
  68050. for (index = 0, cache = planes.length; index < cache; index++) {
  68051. var parsedPlane = planes[index];
  68052. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68053. }
  68054. }
  68055. // TorusKnots
  68056. var torusKnots = geometries.torusKnots;
  68057. if (torusKnots !== undefined && torusKnots !== null) {
  68058. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68059. var parsedTorusKnot = torusKnots[index];
  68060. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68061. }
  68062. }
  68063. // VertexData
  68064. var vertexData = geometries.vertexData;
  68065. if (vertexData !== undefined && vertexData !== null) {
  68066. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68067. var parsedVertexData = vertexData[index];
  68068. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68069. }
  68070. }
  68071. addedGeometry.forEach(function (g) {
  68072. if (g) {
  68073. container.geometries.push(g);
  68074. }
  68075. });
  68076. }
  68077. // Transform nodes
  68078. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68079. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68080. var parsedTransformNode = parsedData.transformNodes[index];
  68081. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68082. container.transformNodes.push(node);
  68083. }
  68084. }
  68085. // Meshes
  68086. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68087. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68088. var parsedMesh = parsedData.meshes[index];
  68089. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68090. container.meshes.push(mesh);
  68091. log += (index === 0 ? "\n\tMeshes:" : "");
  68092. log += "\n\t\t" + mesh.toString(fullDetails);
  68093. }
  68094. }
  68095. // Cameras
  68096. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68097. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68098. var parsedCamera = parsedData.cameras[index];
  68099. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68100. container.cameras.push(camera);
  68101. log += (index === 0 ? "\n\tCameras:" : "");
  68102. log += "\n\t\t" + camera.toString(fullDetails);
  68103. }
  68104. }
  68105. // Browsing all the graph to connect the dots
  68106. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68107. var camera = scene.cameras[index];
  68108. if (camera._waitingParentId) {
  68109. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68110. camera._waitingParentId = null;
  68111. }
  68112. }
  68113. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68114. var light_1 = scene.lights[index];
  68115. if (light_1 && light_1._waitingParentId) {
  68116. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68117. light_1._waitingParentId = null;
  68118. }
  68119. }
  68120. // Sounds
  68121. // TODO: add sound
  68122. var loadedSounds = [];
  68123. var loadedSound;
  68124. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68125. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68126. var parsedSound = parsedData.sounds[index];
  68127. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68128. if (!parsedSound.url)
  68129. parsedSound.url = parsedSound.name;
  68130. if (!loadedSounds[parsedSound.url]) {
  68131. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68132. loadedSounds[parsedSound.url] = loadedSound;
  68133. container.sounds.push(loadedSound);
  68134. }
  68135. else {
  68136. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68137. }
  68138. }
  68139. else {
  68140. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68141. }
  68142. }
  68143. }
  68144. loadedSounds = [];
  68145. // Connect parents & children and parse actions
  68146. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68147. var transformNode = scene.transformNodes[index];
  68148. if (transformNode._waitingParentId) {
  68149. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68150. transformNode._waitingParentId = null;
  68151. }
  68152. }
  68153. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68154. var mesh = scene.meshes[index];
  68155. if (mesh._waitingParentId) {
  68156. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68157. mesh._waitingParentId = null;
  68158. }
  68159. if (mesh._waitingActions) {
  68160. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68161. mesh._waitingActions = null;
  68162. }
  68163. }
  68164. // freeze world matrix application
  68165. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68166. var currentMesh = scene.meshes[index];
  68167. if (currentMesh._waitingFreezeWorldMatrix) {
  68168. currentMesh.freezeWorldMatrix();
  68169. currentMesh._waitingFreezeWorldMatrix = null;
  68170. }
  68171. else {
  68172. currentMesh.computeWorldMatrix(true);
  68173. }
  68174. }
  68175. // Particles Systems
  68176. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68177. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68178. var parsedParticleSystem = parsedData.particleSystems[index];
  68179. if (parsedParticleSystem.activeParticleCount) {
  68180. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68181. container.particleSystems.push(ps);
  68182. }
  68183. else {
  68184. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68185. container.particleSystems.push(ps);
  68186. }
  68187. }
  68188. }
  68189. // Lens flares
  68190. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68191. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68192. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68193. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68194. container.lensFlareSystems.push(lf);
  68195. }
  68196. }
  68197. // Shadows
  68198. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68199. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68200. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68201. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68202. container.shadowGenerators.push(sg);
  68203. }
  68204. }
  68205. // Lights exclusions / inclusions
  68206. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68207. var light_2 = scene.lights[index];
  68208. // Excluded check
  68209. if (light_2._excludedMeshesIds.length > 0) {
  68210. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68211. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68212. if (excludedMesh) {
  68213. light_2.excludedMeshes.push(excludedMesh);
  68214. }
  68215. }
  68216. light_2._excludedMeshesIds = [];
  68217. }
  68218. // Included check
  68219. if (light_2._includedOnlyMeshesIds.length > 0) {
  68220. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68221. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68222. if (includedOnlyMesh) {
  68223. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68224. }
  68225. }
  68226. light_2._includedOnlyMeshesIds = [];
  68227. }
  68228. }
  68229. // Effect layers
  68230. if (parsedData.effectLayers) {
  68231. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68232. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68233. container.effectLayers.push(effectLayer);
  68234. }
  68235. }
  68236. // Actions (scene)
  68237. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68238. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68239. }
  68240. if (!addToScene) {
  68241. container.removeAllFromScene();
  68242. }
  68243. }
  68244. catch (err) {
  68245. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68246. if (onError) {
  68247. onError(msg, err);
  68248. }
  68249. else {
  68250. BABYLON.Tools.Log(msg);
  68251. throw err;
  68252. }
  68253. }
  68254. finally {
  68255. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68256. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68257. }
  68258. }
  68259. return container;
  68260. };
  68261. BABYLON.SceneLoader.RegisterPlugin({
  68262. name: "babylon.js",
  68263. extensions: ".babylon",
  68264. canDirectLoad: function (data) {
  68265. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68266. return true;
  68267. }
  68268. return false;
  68269. },
  68270. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68271. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68272. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68273. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68274. // and avoid problems with multiple concurrent .babylon loads.
  68275. var log = "importMesh has failed JSON parse";
  68276. try {
  68277. var parsedData = JSON.parse(data);
  68278. log = "";
  68279. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68280. if (!meshesNames) {
  68281. meshesNames = null;
  68282. }
  68283. else if (!Array.isArray(meshesNames)) {
  68284. meshesNames = [meshesNames];
  68285. }
  68286. var hierarchyIds = new Array();
  68287. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68288. var loadedSkeletonsIds = [];
  68289. var loadedMaterialsIds = [];
  68290. var index;
  68291. var cache;
  68292. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68293. var parsedMesh = parsedData.meshes[index];
  68294. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68295. if (meshesNames !== null) {
  68296. // Remove found mesh name from list.
  68297. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68298. }
  68299. //Geometry?
  68300. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68301. //does the file contain geometries?
  68302. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68303. //find the correct geometry and add it to the scene
  68304. var found = false;
  68305. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68306. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68307. return;
  68308. }
  68309. else {
  68310. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68311. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68312. switch (geometryType) {
  68313. case "boxes":
  68314. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68315. break;
  68316. case "spheres":
  68317. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68318. break;
  68319. case "cylinders":
  68320. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68321. break;
  68322. case "toruses":
  68323. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68324. break;
  68325. case "grounds":
  68326. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68327. break;
  68328. case "planes":
  68329. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68330. break;
  68331. case "torusKnots":
  68332. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68333. break;
  68334. case "vertexData":
  68335. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68336. break;
  68337. }
  68338. found = true;
  68339. }
  68340. });
  68341. }
  68342. });
  68343. if (found === false) {
  68344. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68345. }
  68346. }
  68347. }
  68348. // Material ?
  68349. if (parsedMesh.materialId) {
  68350. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68351. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68352. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68353. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68354. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68355. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68356. var subMatId = parsedMultiMaterial.materials[matIndex];
  68357. loadedMaterialsIds.push(subMatId);
  68358. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68359. if (mat) {
  68360. log += "\n\tMaterial " + mat.toString(fullDetails);
  68361. }
  68362. }
  68363. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68364. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68365. if (mmat) {
  68366. materialFound = true;
  68367. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68368. }
  68369. break;
  68370. }
  68371. }
  68372. }
  68373. if (materialFound === false) {
  68374. loadedMaterialsIds.push(parsedMesh.materialId);
  68375. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68376. if (!mat) {
  68377. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68378. }
  68379. else {
  68380. log += "\n\tMaterial " + mat.toString(fullDetails);
  68381. }
  68382. }
  68383. }
  68384. // Skeleton ?
  68385. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68386. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68387. if (skeletonAlreadyLoaded === false) {
  68388. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68389. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68390. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68391. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68392. skeletons.push(skeleton);
  68393. loadedSkeletonsIds.push(parsedSkeleton.id);
  68394. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68395. }
  68396. }
  68397. }
  68398. }
  68399. // Morph targets ?
  68400. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68401. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68402. var managerData = _a[_i];
  68403. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68404. }
  68405. }
  68406. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68407. meshes.push(mesh);
  68408. log += "\n\tMesh " + mesh.toString(fullDetails);
  68409. }
  68410. }
  68411. // Connecting parents
  68412. var currentMesh;
  68413. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68414. currentMesh = scene.meshes[index];
  68415. if (currentMesh._waitingParentId) {
  68416. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68417. currentMesh._waitingParentId = null;
  68418. }
  68419. }
  68420. // freeze and compute world matrix application
  68421. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68422. currentMesh = scene.meshes[index];
  68423. if (currentMesh._waitingFreezeWorldMatrix) {
  68424. currentMesh.freezeWorldMatrix();
  68425. currentMesh._waitingFreezeWorldMatrix = null;
  68426. }
  68427. else {
  68428. currentMesh.computeWorldMatrix(true);
  68429. }
  68430. }
  68431. }
  68432. // Particles
  68433. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68434. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68435. var parsedParticleSystem = parsedData.particleSystems[index];
  68436. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68437. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68438. }
  68439. }
  68440. }
  68441. return true;
  68442. }
  68443. catch (err) {
  68444. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68445. if (onError) {
  68446. onError(msg, err);
  68447. }
  68448. else {
  68449. BABYLON.Tools.Log(msg);
  68450. throw err;
  68451. }
  68452. }
  68453. finally {
  68454. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68455. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68456. }
  68457. }
  68458. return false;
  68459. },
  68460. load: function (scene, data, rootUrl, onError) {
  68461. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68462. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68463. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68464. // and avoid problems with multiple concurrent .babylon loads.
  68465. var log = "importScene has failed JSON parse";
  68466. try {
  68467. var parsedData = JSON.parse(data);
  68468. log = "";
  68469. // Scene
  68470. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68471. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68472. }
  68473. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68474. scene.autoClear = parsedData.autoClear;
  68475. }
  68476. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68477. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68478. }
  68479. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68480. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68481. }
  68482. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68483. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68484. }
  68485. // Fog
  68486. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68487. scene.fogMode = parsedData.fogMode;
  68488. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68489. scene.fogStart = parsedData.fogStart;
  68490. scene.fogEnd = parsedData.fogEnd;
  68491. scene.fogDensity = parsedData.fogDensity;
  68492. log += "\tFog mode for scene: ";
  68493. switch (scene.fogMode) {
  68494. // getters not compiling, so using hardcoded
  68495. case 1:
  68496. log += "exp\n";
  68497. break;
  68498. case 2:
  68499. log += "exp2\n";
  68500. break;
  68501. case 3:
  68502. log += "linear\n";
  68503. break;
  68504. }
  68505. }
  68506. //Physics
  68507. if (parsedData.physicsEnabled) {
  68508. var physicsPlugin;
  68509. if (parsedData.physicsEngine === "cannon") {
  68510. physicsPlugin = new BABYLON.CannonJSPlugin();
  68511. }
  68512. else if (parsedData.physicsEngine === "oimo") {
  68513. physicsPlugin = new BABYLON.OimoJSPlugin();
  68514. }
  68515. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68516. //else - default engine, which is currently oimo
  68517. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68518. scene.enablePhysics(physicsGravity, physicsPlugin);
  68519. }
  68520. // Metadata
  68521. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68522. scene.metadata = parsedData.metadata;
  68523. }
  68524. //collisions, if defined. otherwise, default is true
  68525. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68526. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68527. }
  68528. scene.workerCollisions = !!parsedData.workerCollisions;
  68529. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68530. if (!container) {
  68531. return false;
  68532. }
  68533. if (parsedData.autoAnimate) {
  68534. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68535. }
  68536. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68537. scene.setActiveCameraByID(parsedData.activeCameraID);
  68538. }
  68539. // Environment texture
  68540. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68541. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68542. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68543. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68544. if (parsedData.environmentTextureRotationY) {
  68545. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68546. }
  68547. scene.environmentTexture = hdrTexture;
  68548. }
  68549. else {
  68550. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68551. if (parsedData.environmentTextureRotationY) {
  68552. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68553. }
  68554. scene.environmentTexture = cubeTexture;
  68555. }
  68556. if (parsedData.createDefaultSkybox === true) {
  68557. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68558. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68559. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68560. }
  68561. }
  68562. // Finish
  68563. return true;
  68564. }
  68565. catch (err) {
  68566. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68567. if (onError) {
  68568. onError(msg, err);
  68569. }
  68570. else {
  68571. BABYLON.Tools.Log(msg);
  68572. throw err;
  68573. }
  68574. }
  68575. finally {
  68576. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68577. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68578. }
  68579. }
  68580. return false;
  68581. },
  68582. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68583. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68584. return container;
  68585. }
  68586. });
  68587. })(BABYLON || (BABYLON = {}));
  68588. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68589. var BABYLON;
  68590. (function (BABYLON) {
  68591. var FilesInput = /** @class */ (function () {
  68592. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68593. this.onProcessFileCallback = function () { return true; };
  68594. this._engine = engine;
  68595. this._currentScene = scene;
  68596. this._sceneLoadedCallback = sceneLoadedCallback;
  68597. this._progressCallback = progressCallback;
  68598. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68599. this._textureLoadingCallback = textureLoadingCallback;
  68600. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68601. this._onReloadCallback = onReloadCallback;
  68602. this._errorCallback = errorCallback;
  68603. }
  68604. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68605. var _this = this;
  68606. if (elementToMonitor) {
  68607. this._elementToMonitor = elementToMonitor;
  68608. this._dragEnterHandler = function (e) { _this.drag(e); };
  68609. this._dragOverHandler = function (e) { _this.drag(e); };
  68610. this._dropHandler = function (e) { _this.drop(e); };
  68611. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68612. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68613. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68614. }
  68615. };
  68616. FilesInput.prototype.dispose = function () {
  68617. if (!this._elementToMonitor) {
  68618. return;
  68619. }
  68620. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68621. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68622. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68623. };
  68624. FilesInput.prototype.renderFunction = function () {
  68625. if (this._additionalRenderLoopLogicCallback) {
  68626. this._additionalRenderLoopLogicCallback();
  68627. }
  68628. if (this._currentScene) {
  68629. if (this._textureLoadingCallback) {
  68630. var remaining = this._currentScene.getWaitingItemsCount();
  68631. if (remaining > 0) {
  68632. this._textureLoadingCallback(remaining);
  68633. }
  68634. }
  68635. this._currentScene.render();
  68636. }
  68637. };
  68638. FilesInput.prototype.drag = function (e) {
  68639. e.stopPropagation();
  68640. e.preventDefault();
  68641. };
  68642. FilesInput.prototype.drop = function (eventDrop) {
  68643. eventDrop.stopPropagation();
  68644. eventDrop.preventDefault();
  68645. this.loadFiles(eventDrop);
  68646. };
  68647. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68648. var _this = this;
  68649. var reader = folder.createReader();
  68650. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68651. reader.readEntries(function (entries) {
  68652. remaining.count += entries.length;
  68653. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68654. var entry = entries_1[_i];
  68655. if (entry.isFile) {
  68656. entry.file(function (file) {
  68657. file.correctName = relativePath + file.name;
  68658. files.push(file);
  68659. if (--remaining.count === 0) {
  68660. callback();
  68661. }
  68662. });
  68663. }
  68664. else if (entry.isDirectory) {
  68665. _this._traverseFolder(entry, files, remaining, callback);
  68666. }
  68667. }
  68668. if (--remaining.count) {
  68669. callback();
  68670. }
  68671. });
  68672. };
  68673. FilesInput.prototype._processFiles = function (files) {
  68674. for (var i = 0; i < files.length; i++) {
  68675. var name = files[i].correctName.toLowerCase();
  68676. var extension = name.split('.').pop();
  68677. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68678. continue;
  68679. }
  68680. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68681. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68682. this._sceneFileToLoad = files[i];
  68683. }
  68684. else {
  68685. FilesInput.FilesToLoad[name] = files[i];
  68686. }
  68687. }
  68688. };
  68689. FilesInput.prototype.loadFiles = function (event) {
  68690. var _this = this;
  68691. if (this._startingProcessingFilesCallback)
  68692. this._startingProcessingFilesCallback();
  68693. // Handling data transfer via drag'n'drop
  68694. if (event && event.dataTransfer && event.dataTransfer.files) {
  68695. this._filesToLoad = event.dataTransfer.files;
  68696. }
  68697. // Handling files from input files
  68698. if (event && event.target && event.target.files) {
  68699. this._filesToLoad = event.target.files;
  68700. }
  68701. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68702. var files_1 = new Array();
  68703. var folders = [];
  68704. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68705. for (var i = 0; i < this._filesToLoad.length; i++) {
  68706. var fileToLoad = this._filesToLoad[i];
  68707. var name_1 = fileToLoad.name.toLowerCase();
  68708. var entry = void 0;
  68709. fileToLoad.correctName = name_1;
  68710. if (items) {
  68711. var item = items[i];
  68712. if (item.getAsEntry) {
  68713. entry = item.getAsEntry();
  68714. }
  68715. else if (item.webkitGetAsEntry) {
  68716. entry = item.webkitGetAsEntry();
  68717. }
  68718. }
  68719. if (!entry) {
  68720. files_1.push(fileToLoad);
  68721. }
  68722. else {
  68723. if (entry.isDirectory) {
  68724. folders.push(entry);
  68725. }
  68726. else {
  68727. files_1.push(fileToLoad);
  68728. }
  68729. }
  68730. }
  68731. if (folders.length === 0) {
  68732. this._processFiles(files_1);
  68733. this._processReload();
  68734. }
  68735. else {
  68736. var remaining = { count: folders.length };
  68737. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68738. var folder = folders_1[_i];
  68739. this._traverseFolder(folder, files_1, remaining, function () {
  68740. _this._processFiles(files_1);
  68741. if (remaining.count === 0) {
  68742. _this._processReload();
  68743. }
  68744. });
  68745. }
  68746. }
  68747. }
  68748. };
  68749. FilesInput.prototype._processReload = function () {
  68750. if (this._onReloadCallback) {
  68751. this._onReloadCallback(this._sceneFileToLoad);
  68752. }
  68753. else {
  68754. this.reload();
  68755. }
  68756. };
  68757. FilesInput.prototype.reload = function () {
  68758. var _this = this;
  68759. // If a scene file has been provided
  68760. if (this._sceneFileToLoad) {
  68761. if (this._currentScene) {
  68762. if (BABYLON.Tools.errorsCount > 0) {
  68763. BABYLON.Tools.ClearLogCache();
  68764. }
  68765. this._engine.stopRenderLoop();
  68766. }
  68767. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68768. if (_this._progressCallback) {
  68769. _this._progressCallback(progress);
  68770. }
  68771. }).then(function (scene) {
  68772. if (_this._currentScene) {
  68773. _this._currentScene.dispose();
  68774. }
  68775. _this._currentScene = scene;
  68776. if (_this._sceneLoadedCallback) {
  68777. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68778. }
  68779. // Wait for textures and shaders to be ready
  68780. _this._currentScene.executeWhenReady(function () {
  68781. _this._engine.runRenderLoop(function () {
  68782. _this.renderFunction();
  68783. });
  68784. });
  68785. }).catch(function (error) {
  68786. if (_this._errorCallback) {
  68787. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68788. }
  68789. });
  68790. }
  68791. else {
  68792. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68793. }
  68794. };
  68795. FilesInput.FilesToLoad = {};
  68796. return FilesInput;
  68797. }());
  68798. BABYLON.FilesInput = FilesInput;
  68799. })(BABYLON || (BABYLON = {}));
  68800. //# sourceMappingURL=babylon.filesInput.js.map
  68801. var BABYLON;
  68802. (function (BABYLON) {
  68803. /**
  68804. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68805. * The underlying implementation relies on an associative array to ensure the best performances.
  68806. * The value can be anything including 'null' but except 'undefined'
  68807. */
  68808. var StringDictionary = /** @class */ (function () {
  68809. function StringDictionary() {
  68810. this._count = 0;
  68811. this._data = {};
  68812. }
  68813. /**
  68814. * This will clear this dictionary and copy the content from the 'source' one.
  68815. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68816. * @param source the dictionary to take the content from and copy to this dictionary
  68817. */
  68818. StringDictionary.prototype.copyFrom = function (source) {
  68819. var _this = this;
  68820. this.clear();
  68821. source.forEach(function (t, v) { return _this.add(t, v); });
  68822. };
  68823. /**
  68824. * Get a value based from its key
  68825. * @param key the given key to get the matching value from
  68826. * @return the value if found, otherwise undefined is returned
  68827. */
  68828. StringDictionary.prototype.get = function (key) {
  68829. var val = this._data[key];
  68830. if (val !== undefined) {
  68831. return val;
  68832. }
  68833. return undefined;
  68834. };
  68835. /**
  68836. * Get a value from its key or add it if it doesn't exist.
  68837. * This method will ensure you that a given key/data will be present in the dictionary.
  68838. * @param key the given key to get the matching value from
  68839. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68840. * The factory will only be invoked if there's no data for the given key.
  68841. * @return the value corresponding to the key.
  68842. */
  68843. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68844. var val = this.get(key);
  68845. if (val !== undefined) {
  68846. return val;
  68847. }
  68848. val = factory(key);
  68849. if (val) {
  68850. this.add(key, val);
  68851. }
  68852. return val;
  68853. };
  68854. /**
  68855. * Get a value from its key if present in the dictionary otherwise add it
  68856. * @param key the key to get the value from
  68857. * @param val if there's no such key/value pair in the dictionary add it with this value
  68858. * @return the value corresponding to the key
  68859. */
  68860. StringDictionary.prototype.getOrAdd = function (key, val) {
  68861. var curVal = this.get(key);
  68862. if (curVal !== undefined) {
  68863. return curVal;
  68864. }
  68865. this.add(key, val);
  68866. return val;
  68867. };
  68868. /**
  68869. * Check if there's a given key in the dictionary
  68870. * @param key the key to check for
  68871. * @return true if the key is present, false otherwise
  68872. */
  68873. StringDictionary.prototype.contains = function (key) {
  68874. return this._data[key] !== undefined;
  68875. };
  68876. /**
  68877. * Add a new key and its corresponding value
  68878. * @param key the key to add
  68879. * @param value the value corresponding to the key
  68880. * @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
  68881. */
  68882. StringDictionary.prototype.add = function (key, value) {
  68883. if (this._data[key] !== undefined) {
  68884. return false;
  68885. }
  68886. this._data[key] = value;
  68887. ++this._count;
  68888. return true;
  68889. };
  68890. StringDictionary.prototype.set = function (key, value) {
  68891. if (this._data[key] === undefined) {
  68892. return false;
  68893. }
  68894. this._data[key] = value;
  68895. return true;
  68896. };
  68897. /**
  68898. * Get the element of the given key and remove it from the dictionary
  68899. * @param key
  68900. */
  68901. StringDictionary.prototype.getAndRemove = function (key) {
  68902. var val = this.get(key);
  68903. if (val !== undefined) {
  68904. delete this._data[key];
  68905. --this._count;
  68906. return val;
  68907. }
  68908. return null;
  68909. };
  68910. /**
  68911. * Remove a key/value from the dictionary.
  68912. * @param key the key to remove
  68913. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68914. */
  68915. StringDictionary.prototype.remove = function (key) {
  68916. if (this.contains(key)) {
  68917. delete this._data[key];
  68918. --this._count;
  68919. return true;
  68920. }
  68921. return false;
  68922. };
  68923. /**
  68924. * Clear the whole content of the dictionary
  68925. */
  68926. StringDictionary.prototype.clear = function () {
  68927. this._data = {};
  68928. this._count = 0;
  68929. };
  68930. Object.defineProperty(StringDictionary.prototype, "count", {
  68931. get: function () {
  68932. return this._count;
  68933. },
  68934. enumerable: true,
  68935. configurable: true
  68936. });
  68937. /**
  68938. * Execute a callback on each key/val of the dictionary.
  68939. * Note that you can remove any element in this dictionary in the callback implementation
  68940. * @param callback the callback to execute on a given key/value pair
  68941. */
  68942. StringDictionary.prototype.forEach = function (callback) {
  68943. for (var cur in this._data) {
  68944. var val = this._data[cur];
  68945. callback(cur, val);
  68946. }
  68947. };
  68948. /**
  68949. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68950. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68951. * Note that you can remove any element in this dictionary in the callback implementation
  68952. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68953. */
  68954. StringDictionary.prototype.first = function (callback) {
  68955. for (var cur in this._data) {
  68956. var val = this._data[cur];
  68957. var res = callback(cur, val);
  68958. if (res) {
  68959. return res;
  68960. }
  68961. }
  68962. return null;
  68963. };
  68964. return StringDictionary;
  68965. }());
  68966. BABYLON.StringDictionary = StringDictionary;
  68967. })(BABYLON || (BABYLON = {}));
  68968. //# sourceMappingURL=babylon.stringDictionary.js.map
  68969. var BABYLON;
  68970. (function (BABYLON) {
  68971. var Tags = /** @class */ (function () {
  68972. function Tags() {
  68973. }
  68974. Tags.EnableFor = function (obj) {
  68975. obj._tags = obj._tags || {};
  68976. obj.hasTags = function () {
  68977. return Tags.HasTags(obj);
  68978. };
  68979. obj.addTags = function (tagsString) {
  68980. return Tags.AddTagsTo(obj, tagsString);
  68981. };
  68982. obj.removeTags = function (tagsString) {
  68983. return Tags.RemoveTagsFrom(obj, tagsString);
  68984. };
  68985. obj.matchesTagsQuery = function (tagsQuery) {
  68986. return Tags.MatchesQuery(obj, tagsQuery);
  68987. };
  68988. };
  68989. Tags.DisableFor = function (obj) {
  68990. delete obj._tags;
  68991. delete obj.hasTags;
  68992. delete obj.addTags;
  68993. delete obj.removeTags;
  68994. delete obj.matchesTagsQuery;
  68995. };
  68996. Tags.HasTags = function (obj) {
  68997. if (!obj._tags) {
  68998. return false;
  68999. }
  69000. return !BABYLON.Tools.IsEmpty(obj._tags);
  69001. };
  69002. Tags.GetTags = function (obj, asString) {
  69003. if (asString === void 0) { asString = true; }
  69004. if (!obj._tags) {
  69005. return null;
  69006. }
  69007. if (asString) {
  69008. var tagsArray = [];
  69009. for (var tag in obj._tags) {
  69010. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69011. tagsArray.push(tag);
  69012. }
  69013. }
  69014. return tagsArray.join(" ");
  69015. }
  69016. else {
  69017. return obj._tags;
  69018. }
  69019. };
  69020. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69021. // a tag cannot start with '||', '&&', and '!'
  69022. // it cannot contain whitespaces
  69023. Tags.AddTagsTo = function (obj, tagsString) {
  69024. if (!tagsString) {
  69025. return;
  69026. }
  69027. if (typeof tagsString !== "string") {
  69028. return;
  69029. }
  69030. var tags = tagsString.split(" ");
  69031. tags.forEach(function (tag, index, array) {
  69032. Tags._AddTagTo(obj, tag);
  69033. });
  69034. };
  69035. Tags._AddTagTo = function (obj, tag) {
  69036. tag = tag.trim();
  69037. if (tag === "" || tag === "true" || tag === "false") {
  69038. return;
  69039. }
  69040. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69041. return;
  69042. }
  69043. Tags.EnableFor(obj);
  69044. obj._tags[tag] = true;
  69045. };
  69046. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69047. if (!Tags.HasTags(obj)) {
  69048. return;
  69049. }
  69050. var tags = tagsString.split(" ");
  69051. for (var t in tags) {
  69052. Tags._RemoveTagFrom(obj, tags[t]);
  69053. }
  69054. };
  69055. Tags._RemoveTagFrom = function (obj, tag) {
  69056. delete obj._tags[tag];
  69057. };
  69058. Tags.MatchesQuery = function (obj, tagsQuery) {
  69059. if (tagsQuery === undefined) {
  69060. return true;
  69061. }
  69062. if (tagsQuery === "") {
  69063. return Tags.HasTags(obj);
  69064. }
  69065. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69066. };
  69067. return Tags;
  69068. }());
  69069. BABYLON.Tags = Tags;
  69070. })(BABYLON || (BABYLON = {}));
  69071. //# sourceMappingURL=babylon.tags.js.map
  69072. var BABYLON;
  69073. (function (BABYLON) {
  69074. /**
  69075. * Class used to evalaute queries containing `and` and `or` operators
  69076. */
  69077. var AndOrNotEvaluator = /** @class */ (function () {
  69078. function AndOrNotEvaluator() {
  69079. }
  69080. /**
  69081. * Evaluate a query
  69082. * @param query defines the query to evaluate
  69083. * @param evaluateCallback defines the callback used to filter result
  69084. * @returns true if the query matches
  69085. */
  69086. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69087. if (!query.match(/\([^\(\)]*\)/g)) {
  69088. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69089. }
  69090. else {
  69091. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69092. // remove parenthesis
  69093. r = r.slice(1, r.length - 1);
  69094. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69095. });
  69096. }
  69097. if (query === "true") {
  69098. return true;
  69099. }
  69100. if (query === "false") {
  69101. return false;
  69102. }
  69103. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69104. };
  69105. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69106. evaluateCallback = evaluateCallback || (function (r) {
  69107. return r === "true" ? true : false;
  69108. });
  69109. var result;
  69110. var or = parenthesisContent.split("||");
  69111. for (var i in or) {
  69112. if (or.hasOwnProperty(i)) {
  69113. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69114. var and = ori.split("&&");
  69115. if (and.length > 1) {
  69116. for (var j = 0; j < and.length; ++j) {
  69117. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69118. if (andj !== "true" && andj !== "false") {
  69119. if (andj[0] === "!") {
  69120. result = !evaluateCallback(andj.substring(1));
  69121. }
  69122. else {
  69123. result = evaluateCallback(andj);
  69124. }
  69125. }
  69126. else {
  69127. result = andj === "true" ? true : false;
  69128. }
  69129. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69130. ori = "false";
  69131. break;
  69132. }
  69133. }
  69134. }
  69135. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69136. result = true;
  69137. break;
  69138. }
  69139. // result equals false (or undefined)
  69140. if (ori !== "true" && ori !== "false") {
  69141. if (ori[0] === "!") {
  69142. result = !evaluateCallback(ori.substring(1));
  69143. }
  69144. else {
  69145. result = evaluateCallback(ori);
  69146. }
  69147. }
  69148. else {
  69149. result = ori === "true" ? true : false;
  69150. }
  69151. }
  69152. }
  69153. // the whole parenthesis scope is replaced by 'true' or 'false'
  69154. return result ? "true" : "false";
  69155. };
  69156. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69157. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69158. // remove whitespaces
  69159. r = r.replace(/[\s]/g, function () { return ""; });
  69160. return r.length % 2 ? "!" : "";
  69161. });
  69162. booleanString = booleanString.trim();
  69163. if (booleanString === "!true") {
  69164. booleanString = "false";
  69165. }
  69166. else if (booleanString === "!false") {
  69167. booleanString = "true";
  69168. }
  69169. return booleanString;
  69170. };
  69171. return AndOrNotEvaluator;
  69172. }());
  69173. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69174. })(BABYLON || (BABYLON = {}));
  69175. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69176. var BABYLON;
  69177. (function (BABYLON) {
  69178. /**
  69179. * Class used to enable access to IndexedDB
  69180. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69181. */
  69182. var Database = /** @class */ (function () {
  69183. /**
  69184. * Creates a new Database
  69185. * @param urlToScene defines the url to load the scene
  69186. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69187. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69188. */
  69189. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69190. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69191. var _this = this;
  69192. // Handling various flavors of prefixed version of IndexedDB
  69193. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69194. this.callbackManifestChecked = callbackManifestChecked;
  69195. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69196. this.db = null;
  69197. this._enableSceneOffline = false;
  69198. this._enableTexturesOffline = false;
  69199. this.manifestVersionFound = 0;
  69200. this.mustUpdateRessources = false;
  69201. this.hasReachedQuota = false;
  69202. if (!Database.IDBStorageEnabled) {
  69203. this.callbackManifestChecked(true);
  69204. }
  69205. else {
  69206. if (disableManifestCheck) {
  69207. this._enableSceneOffline = true;
  69208. this._enableTexturesOffline = true;
  69209. this.manifestVersionFound = 1;
  69210. BABYLON.Tools.SetImmediate(function () {
  69211. _this.callbackManifestChecked(true);
  69212. });
  69213. }
  69214. else {
  69215. this._checkManifestFile();
  69216. }
  69217. }
  69218. }
  69219. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69220. /**
  69221. * Gets a boolean indicating if scene must be saved in the database
  69222. */
  69223. get: function () {
  69224. return this._enableSceneOffline;
  69225. },
  69226. enumerable: true,
  69227. configurable: true
  69228. });
  69229. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69230. /**
  69231. * Gets a boolean indicating if textures must be saved in the database
  69232. */
  69233. get: function () {
  69234. return this._enableTexturesOffline;
  69235. },
  69236. enumerable: true,
  69237. configurable: true
  69238. });
  69239. Database.prototype._checkManifestFile = function () {
  69240. var _this = this;
  69241. var noManifestFile = function () {
  69242. _this._enableSceneOffline = false;
  69243. _this._enableTexturesOffline = false;
  69244. _this.callbackManifestChecked(false);
  69245. };
  69246. var timeStampUsed = false;
  69247. var manifestURL = this.currentSceneUrl + ".manifest";
  69248. var xhr = new XMLHttpRequest();
  69249. if (navigator.onLine) {
  69250. // Adding a timestamp to by-pass browsers' cache
  69251. timeStampUsed = true;
  69252. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69253. }
  69254. xhr.open("GET", manifestURL, true);
  69255. xhr.addEventListener("load", function () {
  69256. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69257. try {
  69258. var manifestFile = JSON.parse(xhr.response);
  69259. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69260. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69261. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69262. _this.manifestVersionFound = manifestFile.version;
  69263. }
  69264. if (_this.callbackManifestChecked) {
  69265. _this.callbackManifestChecked(true);
  69266. }
  69267. }
  69268. catch (ex) {
  69269. noManifestFile();
  69270. }
  69271. }
  69272. else {
  69273. noManifestFile();
  69274. }
  69275. }, false);
  69276. xhr.addEventListener("error", function (event) {
  69277. if (timeStampUsed) {
  69278. timeStampUsed = false;
  69279. // Let's retry without the timeStamp
  69280. // It could fail when coupled with HTML5 Offline API
  69281. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69282. xhr.open("GET", retryManifestURL, true);
  69283. xhr.send();
  69284. }
  69285. else {
  69286. noManifestFile();
  69287. }
  69288. }, false);
  69289. try {
  69290. xhr.send();
  69291. }
  69292. catch (ex) {
  69293. BABYLON.Tools.Error("Error on XHR send request.");
  69294. this.callbackManifestChecked(false);
  69295. }
  69296. };
  69297. /**
  69298. * Open the database and make it available
  69299. * @param successCallback defines the callback to call on success
  69300. * @param errorCallback defines the callback to call on error
  69301. */
  69302. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69303. var _this = this;
  69304. var handleError = function () {
  69305. _this.isSupported = false;
  69306. if (errorCallback)
  69307. errorCallback();
  69308. };
  69309. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69310. // Your browser doesn't support IndexedDB
  69311. this.isSupported = false;
  69312. if (errorCallback)
  69313. errorCallback();
  69314. }
  69315. else {
  69316. // If the DB hasn't been opened or created yet
  69317. if (!this.db) {
  69318. this.hasReachedQuota = false;
  69319. this.isSupported = true;
  69320. var request = this.idbFactory.open("babylonjs", 1);
  69321. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69322. request.onerror = function (event) {
  69323. handleError();
  69324. };
  69325. // executes when a version change transaction cannot complete due to other active transactions
  69326. request.onblocked = function (event) {
  69327. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69328. handleError();
  69329. };
  69330. // DB has been opened successfully
  69331. request.onsuccess = function (event) {
  69332. _this.db = request.result;
  69333. successCallback();
  69334. };
  69335. // Initialization of the DB. Creating Scenes & Textures stores
  69336. request.onupgradeneeded = function (event) {
  69337. _this.db = (event.target).result;
  69338. if (_this.db) {
  69339. try {
  69340. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69341. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69342. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69343. }
  69344. catch (ex) {
  69345. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69346. handleError();
  69347. }
  69348. }
  69349. };
  69350. }
  69351. // DB has already been created and opened
  69352. else {
  69353. if (successCallback)
  69354. successCallback();
  69355. }
  69356. }
  69357. };
  69358. /**
  69359. * Loads an image from the database
  69360. * @param url defines the url to load from
  69361. * @param image defines the target DOM image
  69362. */
  69363. Database.prototype.loadImageFromDB = function (url, image) {
  69364. var _this = this;
  69365. var completeURL = Database._ReturnFullUrlLocation(url);
  69366. var saveAndLoadImage = function () {
  69367. if (!_this.hasReachedQuota && _this.db !== null) {
  69368. // the texture is not yet in the DB, let's try to save it
  69369. _this._saveImageIntoDBAsync(completeURL, image);
  69370. }
  69371. // If the texture is not in the DB and we've reached the DB quota limit
  69372. // let's load it directly from the web
  69373. else {
  69374. image.src = url;
  69375. }
  69376. };
  69377. if (!this.mustUpdateRessources) {
  69378. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69379. }
  69380. // First time we're download the images or update requested in the manifest file by a version change
  69381. else {
  69382. saveAndLoadImage();
  69383. }
  69384. };
  69385. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69386. if (this.isSupported && this.db !== null) {
  69387. var texture;
  69388. var transaction = this.db.transaction(["textures"]);
  69389. transaction.onabort = function (event) {
  69390. image.src = url;
  69391. };
  69392. transaction.oncomplete = function (event) {
  69393. var blobTextureURL;
  69394. if (texture) {
  69395. var URL = window.URL || window.webkitURL;
  69396. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69397. image.onerror = function () {
  69398. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69399. image.src = url;
  69400. };
  69401. image.src = blobTextureURL;
  69402. }
  69403. else {
  69404. notInDBCallback();
  69405. }
  69406. };
  69407. var getRequest = transaction.objectStore("textures").get(url);
  69408. getRequest.onsuccess = function (event) {
  69409. texture = (event.target).result;
  69410. };
  69411. getRequest.onerror = function (event) {
  69412. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69413. image.src = url;
  69414. };
  69415. }
  69416. else {
  69417. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69418. image.src = url;
  69419. }
  69420. };
  69421. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69422. var _this = this;
  69423. if (this.isSupported) {
  69424. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69425. var generateBlobUrl = function () {
  69426. var blobTextureURL;
  69427. if (blob) {
  69428. var URL = window.URL || window.webkitURL;
  69429. try {
  69430. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69431. }
  69432. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69433. catch (ex) {
  69434. blobTextureURL = URL.createObjectURL(blob);
  69435. }
  69436. }
  69437. if (blobTextureURL) {
  69438. image.src = blobTextureURL;
  69439. }
  69440. };
  69441. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69442. var xhr = new XMLHttpRequest(), blob;
  69443. xhr.open("GET", url, true);
  69444. xhr.responseType = "blob";
  69445. xhr.addEventListener("load", function () {
  69446. if (xhr.status === 200 && _this.db) {
  69447. // Blob as response (XHR2)
  69448. blob = xhr.response;
  69449. var transaction = _this.db.transaction(["textures"], "readwrite");
  69450. // the transaction could abort because of a QuotaExceededError error
  69451. transaction.onabort = function (event) {
  69452. try {
  69453. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69454. var srcElement = (event.srcElement || event.target);
  69455. var error = srcElement.error;
  69456. if (error && error.name === "QuotaExceededError") {
  69457. _this.hasReachedQuota = true;
  69458. }
  69459. }
  69460. catch (ex) { }
  69461. generateBlobUrl();
  69462. };
  69463. transaction.oncomplete = function (event) {
  69464. generateBlobUrl();
  69465. };
  69466. var newTexture = { textureUrl: url, data: blob };
  69467. try {
  69468. // Put the blob into the dabase
  69469. var addRequest = transaction.objectStore("textures").put(newTexture);
  69470. addRequest.onsuccess = function (event) {
  69471. };
  69472. addRequest.onerror = function (event) {
  69473. generateBlobUrl();
  69474. };
  69475. }
  69476. catch (ex) {
  69477. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69478. if (ex.code === 25) {
  69479. Database.IsUASupportingBlobStorage = false;
  69480. }
  69481. image.src = url;
  69482. }
  69483. }
  69484. else {
  69485. image.src = url;
  69486. }
  69487. }, false);
  69488. xhr.addEventListener("error", function (event) {
  69489. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69490. image.src = url;
  69491. }, false);
  69492. xhr.send();
  69493. }
  69494. else {
  69495. image.src = url;
  69496. }
  69497. }
  69498. else {
  69499. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69500. image.src = url;
  69501. }
  69502. };
  69503. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69504. var _this = this;
  69505. var updateVersion = function () {
  69506. // the version is not yet in the DB or we need to update it
  69507. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69508. };
  69509. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69510. };
  69511. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69512. var _this = this;
  69513. if (this.isSupported && this.db) {
  69514. var version;
  69515. try {
  69516. var transaction = this.db.transaction(["versions"]);
  69517. transaction.oncomplete = function (event) {
  69518. if (version) {
  69519. // If the version in the JSON file is different from the version in DB
  69520. if (_this.manifestVersionFound !== version.data) {
  69521. _this.mustUpdateRessources = true;
  69522. updateInDBCallback();
  69523. }
  69524. else {
  69525. callback(version.data);
  69526. }
  69527. }
  69528. // version was not found in DB
  69529. else {
  69530. _this.mustUpdateRessources = true;
  69531. updateInDBCallback();
  69532. }
  69533. };
  69534. transaction.onabort = function (event) {
  69535. callback(-1);
  69536. };
  69537. var getRequest = transaction.objectStore("versions").get(url);
  69538. getRequest.onsuccess = function (event) {
  69539. version = (event.target).result;
  69540. };
  69541. getRequest.onerror = function (event) {
  69542. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69543. callback(-1);
  69544. };
  69545. }
  69546. catch (ex) {
  69547. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69548. callback(-1);
  69549. }
  69550. }
  69551. else {
  69552. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69553. callback(-1);
  69554. }
  69555. };
  69556. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69557. var _this = this;
  69558. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69559. try {
  69560. // Open a transaction to the database
  69561. var transaction = this.db.transaction(["versions"], "readwrite");
  69562. // the transaction could abort because of a QuotaExceededError error
  69563. transaction.onabort = function (event) {
  69564. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69565. var error = event.srcElement['error'];
  69566. if (error && error.name === "QuotaExceededError") {
  69567. _this.hasReachedQuota = true;
  69568. }
  69569. }
  69570. catch (ex) { }
  69571. callback(-1);
  69572. };
  69573. transaction.oncomplete = function (event) {
  69574. callback(_this.manifestVersionFound);
  69575. };
  69576. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69577. // Put the scene into the database
  69578. var addRequest = transaction.objectStore("versions").put(newVersion);
  69579. addRequest.onsuccess = function (event) {
  69580. };
  69581. addRequest.onerror = function (event) {
  69582. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69583. };
  69584. }
  69585. catch (ex) {
  69586. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69587. callback(-1);
  69588. }
  69589. }
  69590. else {
  69591. callback(-1);
  69592. }
  69593. };
  69594. /**
  69595. * Loads a file from database
  69596. * @param url defines the URL to load from
  69597. * @param sceneLoaded defines a callback to call on success
  69598. * @param progressCallBack defines a callback to call when progress changed
  69599. * @param errorCallback defines a callback to call on error
  69600. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69601. */
  69602. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69603. var _this = this;
  69604. var completeUrl = Database._ReturnFullUrlLocation(url);
  69605. var saveAndLoadFile = function () {
  69606. // the scene is not yet in the DB, let's try to save it
  69607. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69608. };
  69609. this._checkVersionFromDB(completeUrl, function (version) {
  69610. if (version !== -1) {
  69611. if (!_this.mustUpdateRessources) {
  69612. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69613. }
  69614. else {
  69615. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69616. }
  69617. }
  69618. else {
  69619. if (errorCallback) {
  69620. errorCallback();
  69621. }
  69622. }
  69623. });
  69624. };
  69625. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69626. if (this.isSupported && this.db) {
  69627. var targetStore;
  69628. if (url.indexOf(".babylon") !== -1) {
  69629. targetStore = "scenes";
  69630. }
  69631. else {
  69632. targetStore = "textures";
  69633. }
  69634. var file;
  69635. var transaction = this.db.transaction([targetStore]);
  69636. transaction.oncomplete = function (event) {
  69637. if (file) {
  69638. callback(file.data);
  69639. }
  69640. // file was not found in DB
  69641. else {
  69642. notInDBCallback();
  69643. }
  69644. };
  69645. transaction.onabort = function (event) {
  69646. notInDBCallback();
  69647. };
  69648. var getRequest = transaction.objectStore(targetStore).get(url);
  69649. getRequest.onsuccess = function (event) {
  69650. file = (event.target).result;
  69651. };
  69652. getRequest.onerror = function (event) {
  69653. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69654. notInDBCallback();
  69655. };
  69656. }
  69657. else {
  69658. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69659. callback();
  69660. }
  69661. };
  69662. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69663. var _this = this;
  69664. if (this.isSupported) {
  69665. var targetStore;
  69666. if (url.indexOf(".babylon") !== -1) {
  69667. targetStore = "scenes";
  69668. }
  69669. else {
  69670. targetStore = "textures";
  69671. }
  69672. // Create XHR
  69673. var xhr = new XMLHttpRequest();
  69674. var fileData;
  69675. xhr.open("GET", url, true);
  69676. if (useArrayBuffer) {
  69677. xhr.responseType = "arraybuffer";
  69678. }
  69679. if (progressCallback) {
  69680. xhr.onprogress = progressCallback;
  69681. }
  69682. xhr.addEventListener("load", function () {
  69683. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69684. // Blob as response (XHR2)
  69685. //fileData = xhr.responseText;
  69686. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69687. if (!_this.hasReachedQuota && _this.db) {
  69688. // Open a transaction to the database
  69689. var transaction = _this.db.transaction([targetStore], "readwrite");
  69690. // the transaction could abort because of a QuotaExceededError error
  69691. transaction.onabort = function (event) {
  69692. try {
  69693. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69694. var error = event.srcElement['error'];
  69695. if (error && error.name === "QuotaExceededError") {
  69696. _this.hasReachedQuota = true;
  69697. }
  69698. }
  69699. catch (ex) { }
  69700. callback(fileData);
  69701. };
  69702. transaction.oncomplete = function (event) {
  69703. callback(fileData);
  69704. };
  69705. var newFile;
  69706. if (targetStore === "scenes") {
  69707. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69708. }
  69709. else {
  69710. newFile = { textureUrl: url, data: fileData };
  69711. }
  69712. try {
  69713. // Put the scene into the database
  69714. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69715. addRequest.onsuccess = function (event) {
  69716. };
  69717. addRequest.onerror = function (event) {
  69718. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69719. };
  69720. }
  69721. catch (ex) {
  69722. callback(fileData);
  69723. }
  69724. }
  69725. else {
  69726. callback(fileData);
  69727. }
  69728. }
  69729. else {
  69730. callback();
  69731. }
  69732. }, false);
  69733. xhr.addEventListener("error", function (event) {
  69734. BABYLON.Tools.Error("error on XHR request.");
  69735. callback();
  69736. }, false);
  69737. xhr.send();
  69738. }
  69739. else {
  69740. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69741. callback();
  69742. }
  69743. };
  69744. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69745. Database.IsUASupportingBlobStorage = true;
  69746. /** Gets a boolean indicating if Database storate is enabled */
  69747. Database.IDBStorageEnabled = true;
  69748. Database._ParseURL = function (url) {
  69749. var a = document.createElement('a');
  69750. a.href = url;
  69751. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69752. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69753. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69754. return absLocation;
  69755. };
  69756. Database._ReturnFullUrlLocation = function (url) {
  69757. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69758. return (Database._ParseURL(window.location.href) + url);
  69759. }
  69760. else {
  69761. return url;
  69762. }
  69763. };
  69764. return Database;
  69765. }());
  69766. BABYLON.Database = Database;
  69767. })(BABYLON || (BABYLON = {}));
  69768. //# sourceMappingURL=babylon.database.js.map
  69769. var BABYLON;
  69770. (function (BABYLON) {
  69771. var FresnelParameters = /** @class */ (function () {
  69772. function FresnelParameters() {
  69773. this._isEnabled = true;
  69774. this.leftColor = BABYLON.Color3.White();
  69775. this.rightColor = BABYLON.Color3.Black();
  69776. this.bias = 0;
  69777. this.power = 1;
  69778. }
  69779. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69780. get: function () {
  69781. return this._isEnabled;
  69782. },
  69783. set: function (value) {
  69784. if (this._isEnabled === value) {
  69785. return;
  69786. }
  69787. this._isEnabled = value;
  69788. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69789. },
  69790. enumerable: true,
  69791. configurable: true
  69792. });
  69793. FresnelParameters.prototype.clone = function () {
  69794. var newFresnelParameters = new FresnelParameters();
  69795. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69796. return newFresnelParameters;
  69797. };
  69798. FresnelParameters.prototype.serialize = function () {
  69799. var serializationObject = {};
  69800. serializationObject.isEnabled = this.isEnabled;
  69801. serializationObject.leftColor = this.leftColor.asArray();
  69802. serializationObject.rightColor = this.rightColor.asArray();
  69803. serializationObject.bias = this.bias;
  69804. serializationObject.power = this.power;
  69805. return serializationObject;
  69806. };
  69807. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69808. var fresnelParameters = new FresnelParameters();
  69809. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69810. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69811. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69812. fresnelParameters.bias = parsedFresnelParameters.bias;
  69813. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69814. return fresnelParameters;
  69815. };
  69816. return FresnelParameters;
  69817. }());
  69818. BABYLON.FresnelParameters = FresnelParameters;
  69819. })(BABYLON || (BABYLON = {}));
  69820. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69821. var BABYLON;
  69822. (function (BABYLON) {
  69823. var MultiMaterial = /** @class */ (function (_super) {
  69824. __extends(MultiMaterial, _super);
  69825. function MultiMaterial(name, scene) {
  69826. var _this = _super.call(this, name, scene, true) || this;
  69827. scene.multiMaterials.push(_this);
  69828. _this.subMaterials = new Array();
  69829. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69830. return _this;
  69831. }
  69832. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69833. get: function () {
  69834. return this._subMaterials;
  69835. },
  69836. set: function (value) {
  69837. this._subMaterials = value;
  69838. this._hookArray(value);
  69839. },
  69840. enumerable: true,
  69841. configurable: true
  69842. });
  69843. MultiMaterial.prototype._hookArray = function (array) {
  69844. var _this = this;
  69845. var oldPush = array.push;
  69846. array.push = function () {
  69847. var items = [];
  69848. for (var _i = 0; _i < arguments.length; _i++) {
  69849. items[_i] = arguments[_i];
  69850. }
  69851. var result = oldPush.apply(array, items);
  69852. _this._markAllSubMeshesAsTexturesDirty();
  69853. return result;
  69854. };
  69855. var oldSplice = array.splice;
  69856. array.splice = function (index, deleteCount) {
  69857. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69858. _this._markAllSubMeshesAsTexturesDirty();
  69859. return deleted;
  69860. };
  69861. };
  69862. // Properties
  69863. MultiMaterial.prototype.getSubMaterial = function (index) {
  69864. if (index < 0 || index >= this.subMaterials.length) {
  69865. return this.getScene().defaultMaterial;
  69866. }
  69867. return this.subMaterials[index];
  69868. };
  69869. MultiMaterial.prototype.getActiveTextures = function () {
  69870. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69871. if (subMaterial) {
  69872. return subMaterial.getActiveTextures();
  69873. }
  69874. else {
  69875. return [];
  69876. }
  69877. }));
  69878. var _a;
  69879. };
  69880. // Methods
  69881. MultiMaterial.prototype.getClassName = function () {
  69882. return "MultiMaterial";
  69883. };
  69884. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69885. for (var index = 0; index < this.subMaterials.length; index++) {
  69886. var subMaterial = this.subMaterials[index];
  69887. if (subMaterial) {
  69888. if (subMaterial.storeEffectOnSubMeshes) {
  69889. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69890. return false;
  69891. }
  69892. continue;
  69893. }
  69894. if (!subMaterial.isReady(mesh)) {
  69895. return false;
  69896. }
  69897. }
  69898. }
  69899. return true;
  69900. };
  69901. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69902. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69903. for (var index = 0; index < this.subMaterials.length; index++) {
  69904. var subMaterial = null;
  69905. var current = this.subMaterials[index];
  69906. if (cloneChildren && current) {
  69907. subMaterial = current.clone(name + "-" + current.name);
  69908. }
  69909. else {
  69910. subMaterial = this.subMaterials[index];
  69911. }
  69912. newMultiMaterial.subMaterials.push(subMaterial);
  69913. }
  69914. return newMultiMaterial;
  69915. };
  69916. MultiMaterial.prototype.serialize = function () {
  69917. var serializationObject = {};
  69918. serializationObject.name = this.name;
  69919. serializationObject.id = this.id;
  69920. if (BABYLON.Tags) {
  69921. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69922. }
  69923. serializationObject.materials = [];
  69924. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69925. var subMat = this.subMaterials[matIndex];
  69926. if (subMat) {
  69927. serializationObject.materials.push(subMat.id);
  69928. }
  69929. else {
  69930. serializationObject.materials.push(null);
  69931. }
  69932. }
  69933. return serializationObject;
  69934. };
  69935. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69936. var scene = this.getScene();
  69937. if (!scene) {
  69938. return;
  69939. }
  69940. var index = scene.multiMaterials.indexOf(this);
  69941. if (index >= 0) {
  69942. scene.multiMaterials.splice(index, 1);
  69943. }
  69944. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69945. };
  69946. return MultiMaterial;
  69947. }(BABYLON.Material));
  69948. BABYLON.MultiMaterial = MultiMaterial;
  69949. })(BABYLON || (BABYLON = {}));
  69950. //# sourceMappingURL=babylon.multiMaterial.js.map
  69951. var BABYLON;
  69952. (function (BABYLON) {
  69953. var FreeCameraTouchInput = /** @class */ (function () {
  69954. function FreeCameraTouchInput() {
  69955. this._offsetX = null;
  69956. this._offsetY = null;
  69957. this._pointerPressed = new Array();
  69958. this.touchAngularSensibility = 200000.0;
  69959. this.touchMoveSensibility = 250.0;
  69960. }
  69961. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69962. var _this = this;
  69963. var previousPosition = null;
  69964. if (this._pointerInput === undefined) {
  69965. this._onLostFocus = function (evt) {
  69966. _this._offsetX = null;
  69967. _this._offsetY = null;
  69968. };
  69969. this._pointerInput = function (p, s) {
  69970. var evt = p.event;
  69971. if (evt.pointerType === "mouse") {
  69972. return;
  69973. }
  69974. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69975. if (!noPreventDefault) {
  69976. evt.preventDefault();
  69977. }
  69978. _this._pointerPressed.push(evt.pointerId);
  69979. if (_this._pointerPressed.length !== 1) {
  69980. return;
  69981. }
  69982. previousPosition = {
  69983. x: evt.clientX,
  69984. y: evt.clientY
  69985. };
  69986. }
  69987. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69988. if (!noPreventDefault) {
  69989. evt.preventDefault();
  69990. }
  69991. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69992. if (index === -1) {
  69993. return;
  69994. }
  69995. _this._pointerPressed.splice(index, 1);
  69996. if (index != 0) {
  69997. return;
  69998. }
  69999. previousPosition = null;
  70000. _this._offsetX = null;
  70001. _this._offsetY = null;
  70002. }
  70003. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70004. if (!noPreventDefault) {
  70005. evt.preventDefault();
  70006. }
  70007. if (!previousPosition) {
  70008. return;
  70009. }
  70010. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70011. if (index != 0) {
  70012. return;
  70013. }
  70014. _this._offsetX = evt.clientX - previousPosition.x;
  70015. _this._offsetY = -(evt.clientY - previousPosition.y);
  70016. }
  70017. };
  70018. }
  70019. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70020. if (this._onLostFocus) {
  70021. element.addEventListener("blur", this._onLostFocus);
  70022. }
  70023. };
  70024. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70025. if (this._pointerInput && element) {
  70026. if (this._observer) {
  70027. this.camera.getScene().onPointerObservable.remove(this._observer);
  70028. this._observer = null;
  70029. }
  70030. if (this._onLostFocus) {
  70031. element.removeEventListener("blur", this._onLostFocus);
  70032. this._onLostFocus = null;
  70033. }
  70034. this._pointerPressed = [];
  70035. this._offsetX = null;
  70036. this._offsetY = null;
  70037. }
  70038. };
  70039. FreeCameraTouchInput.prototype.checkInputs = function () {
  70040. if (this._offsetX && this._offsetY) {
  70041. var camera = this.camera;
  70042. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70043. if (this._pointerPressed.length > 1) {
  70044. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70045. }
  70046. else {
  70047. var speed = camera._computeLocalCameraSpeed();
  70048. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70049. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70050. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70051. }
  70052. }
  70053. };
  70054. FreeCameraTouchInput.prototype.getClassName = function () {
  70055. return "FreeCameraTouchInput";
  70056. };
  70057. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70058. return "touch";
  70059. };
  70060. __decorate([
  70061. BABYLON.serialize()
  70062. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70063. __decorate([
  70064. BABYLON.serialize()
  70065. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70066. return FreeCameraTouchInput;
  70067. }());
  70068. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70069. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70070. })(BABYLON || (BABYLON = {}));
  70071. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70072. var BABYLON;
  70073. (function (BABYLON) {
  70074. // We're mainly based on the logic defined into the FreeCamera code
  70075. var TouchCamera = /** @class */ (function (_super) {
  70076. __extends(TouchCamera, _super);
  70077. //-- end properties for backward compatibility for inputs
  70078. function TouchCamera(name, position, scene) {
  70079. var _this = _super.call(this, name, position, scene) || this;
  70080. _this.inputs.addTouch();
  70081. _this._setupInputs();
  70082. return _this;
  70083. }
  70084. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70085. //-- Begin properties for backward compatibility for inputs
  70086. get: function () {
  70087. var touch = this.inputs.attached["touch"];
  70088. if (touch)
  70089. return touch.touchAngularSensibility;
  70090. return 0;
  70091. },
  70092. set: function (value) {
  70093. var touch = this.inputs.attached["touch"];
  70094. if (touch)
  70095. touch.touchAngularSensibility = value;
  70096. },
  70097. enumerable: true,
  70098. configurable: true
  70099. });
  70100. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70101. get: function () {
  70102. var touch = this.inputs.attached["touch"];
  70103. if (touch)
  70104. return touch.touchMoveSensibility;
  70105. return 0;
  70106. },
  70107. set: function (value) {
  70108. var touch = this.inputs.attached["touch"];
  70109. if (touch)
  70110. touch.touchMoveSensibility = value;
  70111. },
  70112. enumerable: true,
  70113. configurable: true
  70114. });
  70115. TouchCamera.prototype.getClassName = function () {
  70116. return "TouchCamera";
  70117. };
  70118. TouchCamera.prototype._setupInputs = function () {
  70119. var mouse = this.inputs.attached["mouse"];
  70120. if (mouse) {
  70121. mouse.touchEnabled = false;
  70122. }
  70123. };
  70124. return TouchCamera;
  70125. }(BABYLON.FreeCamera));
  70126. BABYLON.TouchCamera = TouchCamera;
  70127. })(BABYLON || (BABYLON = {}));
  70128. //# sourceMappingURL=babylon.touchCamera.js.map
  70129. var BABYLON;
  70130. (function (BABYLON) {
  70131. var ProceduralTexture = /** @class */ (function (_super) {
  70132. __extends(ProceduralTexture, _super);
  70133. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70134. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70135. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70136. if (isCube === void 0) { isCube = false; }
  70137. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70138. _this.isCube = isCube;
  70139. _this.isEnabled = true;
  70140. _this._currentRefreshId = -1;
  70141. _this._refreshRate = 1;
  70142. _this._vertexBuffers = {};
  70143. _this._uniforms = new Array();
  70144. _this._samplers = new Array();
  70145. _this._textures = {};
  70146. _this._floats = {};
  70147. _this._floatsArrays = {};
  70148. _this._colors3 = {};
  70149. _this._colors4 = {};
  70150. _this._vectors2 = {};
  70151. _this._vectors3 = {};
  70152. _this._matrices = {};
  70153. _this._fallbackTextureUsed = false;
  70154. scene.proceduralTextures.push(_this);
  70155. _this._engine = scene.getEngine();
  70156. _this.name = name;
  70157. _this.isRenderTarget = true;
  70158. _this._size = size;
  70159. _this._generateMipMaps = generateMipMaps;
  70160. _this.setFragment(fragment);
  70161. _this._fallbackTexture = fallbackTexture;
  70162. if (isCube) {
  70163. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70164. _this.setFloat("face", 0);
  70165. }
  70166. else {
  70167. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70168. }
  70169. // VBO
  70170. var vertices = [];
  70171. vertices.push(1, 1);
  70172. vertices.push(-1, 1);
  70173. vertices.push(-1, -1);
  70174. vertices.push(1, -1);
  70175. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70176. _this._createIndexBuffer();
  70177. return _this;
  70178. }
  70179. ProceduralTexture.prototype._createIndexBuffer = function () {
  70180. var engine = this._engine;
  70181. // Indices
  70182. var indices = [];
  70183. indices.push(0);
  70184. indices.push(1);
  70185. indices.push(2);
  70186. indices.push(0);
  70187. indices.push(2);
  70188. indices.push(3);
  70189. this._indexBuffer = engine.createIndexBuffer(indices);
  70190. };
  70191. ProceduralTexture.prototype._rebuild = function () {
  70192. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70193. if (vb) {
  70194. vb._rebuild();
  70195. }
  70196. this._createIndexBuffer();
  70197. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70198. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70199. }
  70200. };
  70201. ProceduralTexture.prototype.reset = function () {
  70202. if (this._effect === undefined) {
  70203. return;
  70204. }
  70205. var engine = this._engine;
  70206. engine._releaseEffect(this._effect);
  70207. };
  70208. ProceduralTexture.prototype.isReady = function () {
  70209. var _this = this;
  70210. var engine = this._engine;
  70211. var shaders;
  70212. if (!this._fragment) {
  70213. return false;
  70214. }
  70215. if (this._fallbackTextureUsed) {
  70216. return true;
  70217. }
  70218. if (this._fragment.fragmentElement !== undefined) {
  70219. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70220. }
  70221. else {
  70222. shaders = { vertex: "procedural", fragment: this._fragment };
  70223. }
  70224. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70225. _this.releaseInternalTexture();
  70226. if (_this._fallbackTexture) {
  70227. _this._texture = _this._fallbackTexture._texture;
  70228. if (_this._texture) {
  70229. _this._texture.incrementReferences();
  70230. }
  70231. }
  70232. _this._fallbackTextureUsed = true;
  70233. });
  70234. return this._effect.isReady();
  70235. };
  70236. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70237. this._currentRefreshId = -1;
  70238. };
  70239. ProceduralTexture.prototype.setFragment = function (fragment) {
  70240. this._fragment = fragment;
  70241. };
  70242. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70243. get: function () {
  70244. return this._refreshRate;
  70245. },
  70246. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70247. set: function (value) {
  70248. this._refreshRate = value;
  70249. this.resetRefreshCounter();
  70250. },
  70251. enumerable: true,
  70252. configurable: true
  70253. });
  70254. ProceduralTexture.prototype._shouldRender = function () {
  70255. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70256. return false;
  70257. }
  70258. if (this._fallbackTextureUsed) {
  70259. return false;
  70260. }
  70261. if (this._currentRefreshId === -1) { // At least render once
  70262. this._currentRefreshId = 1;
  70263. return true;
  70264. }
  70265. if (this.refreshRate === this._currentRefreshId) {
  70266. this._currentRefreshId = 1;
  70267. return true;
  70268. }
  70269. this._currentRefreshId++;
  70270. return false;
  70271. };
  70272. ProceduralTexture.prototype.getRenderSize = function () {
  70273. return this._size;
  70274. };
  70275. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70276. if (this._fallbackTextureUsed) {
  70277. return;
  70278. }
  70279. this.releaseInternalTexture();
  70280. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70281. // Update properties
  70282. this._size = size;
  70283. this._generateMipMaps = generateMipMaps;
  70284. };
  70285. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70286. if (this._uniforms.indexOf(uniformName) === -1) {
  70287. this._uniforms.push(uniformName);
  70288. }
  70289. };
  70290. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70291. if (this._samplers.indexOf(name) === -1) {
  70292. this._samplers.push(name);
  70293. }
  70294. this._textures[name] = texture;
  70295. return this;
  70296. };
  70297. ProceduralTexture.prototype.setFloat = function (name, value) {
  70298. this._checkUniform(name);
  70299. this._floats[name] = value;
  70300. return this;
  70301. };
  70302. ProceduralTexture.prototype.setFloats = function (name, value) {
  70303. this._checkUniform(name);
  70304. this._floatsArrays[name] = value;
  70305. return this;
  70306. };
  70307. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70308. this._checkUniform(name);
  70309. this._colors3[name] = value;
  70310. return this;
  70311. };
  70312. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70313. this._checkUniform(name);
  70314. this._colors4[name] = value;
  70315. return this;
  70316. };
  70317. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70318. this._checkUniform(name);
  70319. this._vectors2[name] = value;
  70320. return this;
  70321. };
  70322. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70323. this._checkUniform(name);
  70324. this._vectors3[name] = value;
  70325. return this;
  70326. };
  70327. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70328. this._checkUniform(name);
  70329. this._matrices[name] = value;
  70330. return this;
  70331. };
  70332. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70333. var scene = this.getScene();
  70334. if (!scene) {
  70335. return;
  70336. }
  70337. var engine = this._engine;
  70338. // Render
  70339. engine.enableEffect(this._effect);
  70340. engine.setState(false);
  70341. // Texture
  70342. for (var name in this._textures) {
  70343. this._effect.setTexture(name, this._textures[name]);
  70344. }
  70345. // Float
  70346. for (name in this._floats) {
  70347. this._effect.setFloat(name, this._floats[name]);
  70348. }
  70349. // Floats
  70350. for (name in this._floatsArrays) {
  70351. this._effect.setArray(name, this._floatsArrays[name]);
  70352. }
  70353. // Color3
  70354. for (name in this._colors3) {
  70355. this._effect.setColor3(name, this._colors3[name]);
  70356. }
  70357. // Color4
  70358. for (name in this._colors4) {
  70359. var color = this._colors4[name];
  70360. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70361. }
  70362. // Vector2
  70363. for (name in this._vectors2) {
  70364. this._effect.setVector2(name, this._vectors2[name]);
  70365. }
  70366. // Vector3
  70367. for (name in this._vectors3) {
  70368. this._effect.setVector3(name, this._vectors3[name]);
  70369. }
  70370. // Matrix
  70371. for (name in this._matrices) {
  70372. this._effect.setMatrix(name, this._matrices[name]);
  70373. }
  70374. if (!this._texture) {
  70375. return;
  70376. }
  70377. if (this.isCube) {
  70378. for (var face = 0; face < 6; face++) {
  70379. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70380. // VBOs
  70381. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70382. this._effect.setFloat("face", face);
  70383. // Clear
  70384. engine.clear(scene.clearColor, true, true, true);
  70385. // Draw order
  70386. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70387. // Mipmaps
  70388. if (face === 5) {
  70389. engine.generateMipMapsForCubemap(this._texture);
  70390. }
  70391. }
  70392. }
  70393. else {
  70394. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70395. // VBOs
  70396. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70397. // Clear
  70398. engine.clear(scene.clearColor, true, true, true);
  70399. // Draw order
  70400. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70401. }
  70402. // Unbind
  70403. engine.unBindFramebuffer(this._texture, this.isCube);
  70404. if (this.onGenerated) {
  70405. this.onGenerated();
  70406. }
  70407. };
  70408. ProceduralTexture.prototype.clone = function () {
  70409. var textureSize = this.getSize();
  70410. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70411. // Base texture
  70412. newTexture.hasAlpha = this.hasAlpha;
  70413. newTexture.level = this.level;
  70414. // RenderTarget Texture
  70415. newTexture.coordinatesMode = this.coordinatesMode;
  70416. return newTexture;
  70417. };
  70418. ProceduralTexture.prototype.dispose = function () {
  70419. var scene = this.getScene();
  70420. if (!scene) {
  70421. return;
  70422. }
  70423. var index = scene.proceduralTextures.indexOf(this);
  70424. if (index >= 0) {
  70425. scene.proceduralTextures.splice(index, 1);
  70426. }
  70427. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70428. if (vertexBuffer) {
  70429. vertexBuffer.dispose();
  70430. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70431. }
  70432. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70433. this._indexBuffer = null;
  70434. }
  70435. _super.prototype.dispose.call(this);
  70436. };
  70437. __decorate([
  70438. BABYLON.serialize()
  70439. ], ProceduralTexture.prototype, "_size", void 0);
  70440. __decorate([
  70441. BABYLON.serialize()
  70442. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70443. __decorate([
  70444. BABYLON.serialize()
  70445. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70446. __decorate([
  70447. BABYLON.serialize()
  70448. ], ProceduralTexture.prototype, "refreshRate", null);
  70449. return ProceduralTexture;
  70450. }(BABYLON.Texture));
  70451. BABYLON.ProceduralTexture = ProceduralTexture;
  70452. })(BABYLON || (BABYLON = {}));
  70453. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70454. var BABYLON;
  70455. (function (BABYLON) {
  70456. var CustomProceduralTexture = /** @class */ (function (_super) {
  70457. __extends(CustomProceduralTexture, _super);
  70458. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70459. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70460. _this._animate = true;
  70461. _this._time = 0;
  70462. _this._texturePath = texturePath;
  70463. //Try to load json
  70464. _this.loadJson(texturePath);
  70465. _this.refreshRate = 1;
  70466. return _this;
  70467. }
  70468. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70469. var _this = this;
  70470. var noConfigFile = function () {
  70471. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70472. try {
  70473. _this.setFragment(_this._texturePath);
  70474. }
  70475. catch (ex) {
  70476. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70477. }
  70478. };
  70479. var configFileUrl = jsonUrl + "/config.json";
  70480. var xhr = new XMLHttpRequest();
  70481. xhr.open("GET", configFileUrl, true);
  70482. xhr.addEventListener("load", function () {
  70483. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70484. try {
  70485. _this._config = JSON.parse(xhr.response);
  70486. _this.updateShaderUniforms();
  70487. _this.updateTextures();
  70488. _this.setFragment(_this._texturePath + "/custom");
  70489. _this._animate = _this._config.animate;
  70490. _this.refreshRate = _this._config.refreshrate;
  70491. }
  70492. catch (ex) {
  70493. noConfigFile();
  70494. }
  70495. }
  70496. else {
  70497. noConfigFile();
  70498. }
  70499. }, false);
  70500. xhr.addEventListener("error", function () {
  70501. noConfigFile();
  70502. }, false);
  70503. try {
  70504. xhr.send();
  70505. }
  70506. catch (ex) {
  70507. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70508. }
  70509. };
  70510. CustomProceduralTexture.prototype.isReady = function () {
  70511. if (!_super.prototype.isReady.call(this)) {
  70512. return false;
  70513. }
  70514. for (var name in this._textures) {
  70515. var texture = this._textures[name];
  70516. if (!texture.isReady()) {
  70517. return false;
  70518. }
  70519. }
  70520. return true;
  70521. };
  70522. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70523. var scene = this.getScene();
  70524. if (this._animate && scene) {
  70525. this._time += scene.getAnimationRatio() * 0.03;
  70526. this.updateShaderUniforms();
  70527. }
  70528. _super.prototype.render.call(this, useCameraPostProcess);
  70529. };
  70530. CustomProceduralTexture.prototype.updateTextures = function () {
  70531. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70532. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70533. }
  70534. };
  70535. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70536. if (this._config) {
  70537. for (var j = 0; j < this._config.uniforms.length; j++) {
  70538. var uniform = this._config.uniforms[j];
  70539. switch (uniform.type) {
  70540. case "float":
  70541. this.setFloat(uniform.name, uniform.value);
  70542. break;
  70543. case "color3":
  70544. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70545. break;
  70546. case "color4":
  70547. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70548. break;
  70549. case "vector2":
  70550. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70551. break;
  70552. case "vector3":
  70553. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70554. break;
  70555. }
  70556. }
  70557. }
  70558. this.setFloat("time", this._time);
  70559. };
  70560. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70561. get: function () {
  70562. return this._animate;
  70563. },
  70564. set: function (value) {
  70565. this._animate = value;
  70566. },
  70567. enumerable: true,
  70568. configurable: true
  70569. });
  70570. return CustomProceduralTexture;
  70571. }(BABYLON.ProceduralTexture));
  70572. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70573. })(BABYLON || (BABYLON = {}));
  70574. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70575. var BABYLON;
  70576. (function (BABYLON) {
  70577. var FreeCameraGamepadInput = /** @class */ (function () {
  70578. function FreeCameraGamepadInput() {
  70579. this.gamepadAngularSensibility = 200;
  70580. this.gamepadMoveSensibility = 40;
  70581. // private members
  70582. this._cameraTransform = BABYLON.Matrix.Identity();
  70583. this._deltaTransform = BABYLON.Vector3.Zero();
  70584. this._vector3 = BABYLON.Vector3.Zero();
  70585. this._vector2 = BABYLON.Vector2.Zero();
  70586. }
  70587. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70588. var _this = this;
  70589. var manager = this.camera.getScene().gamepadManager;
  70590. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70591. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70592. // prioritize XBOX gamepads.
  70593. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70594. _this.gamepad = gamepad;
  70595. }
  70596. }
  70597. });
  70598. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70599. if (_this.gamepad === gamepad) {
  70600. _this.gamepad = null;
  70601. }
  70602. });
  70603. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70604. };
  70605. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70606. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70607. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70608. this.gamepad = null;
  70609. };
  70610. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70611. if (this.gamepad && this.gamepad.leftStick) {
  70612. var camera = this.camera;
  70613. var LSValues = this.gamepad.leftStick;
  70614. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70615. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70616. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70617. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70618. var RSValues = this.gamepad.rightStick;
  70619. if (RSValues) {
  70620. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70621. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70622. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70623. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70624. }
  70625. else {
  70626. RSValues = { x: 0, y: 0 };
  70627. }
  70628. if (!camera.rotationQuaternion) {
  70629. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70630. }
  70631. else {
  70632. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70633. }
  70634. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70635. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70636. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70637. camera.cameraDirection.addInPlace(this._deltaTransform);
  70638. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70639. camera.cameraRotation.addInPlace(this._vector2);
  70640. }
  70641. };
  70642. FreeCameraGamepadInput.prototype.getClassName = function () {
  70643. return "FreeCameraGamepadInput";
  70644. };
  70645. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70646. return "gamepad";
  70647. };
  70648. __decorate([
  70649. BABYLON.serialize()
  70650. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70651. __decorate([
  70652. BABYLON.serialize()
  70653. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70654. return FreeCameraGamepadInput;
  70655. }());
  70656. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70657. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70658. })(BABYLON || (BABYLON = {}));
  70659. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70660. var BABYLON;
  70661. (function (BABYLON) {
  70662. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70663. function ArcRotateCameraGamepadInput() {
  70664. this.gamepadRotationSensibility = 80;
  70665. this.gamepadMoveSensibility = 40;
  70666. }
  70667. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70668. var _this = this;
  70669. var manager = this.camera.getScene().gamepadManager;
  70670. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70671. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70672. // prioritize XBOX gamepads.
  70673. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70674. _this.gamepad = gamepad;
  70675. }
  70676. }
  70677. });
  70678. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70679. if (_this.gamepad === gamepad) {
  70680. _this.gamepad = null;
  70681. }
  70682. });
  70683. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70684. };
  70685. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70686. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70687. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70688. this.gamepad = null;
  70689. };
  70690. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70691. if (this.gamepad) {
  70692. var camera = this.camera;
  70693. var RSValues = this.gamepad.rightStick;
  70694. if (RSValues) {
  70695. if (RSValues.x != 0) {
  70696. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70697. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70698. camera.inertialAlphaOffset += normalizedRX;
  70699. }
  70700. }
  70701. if (RSValues.y != 0) {
  70702. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70703. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70704. camera.inertialBetaOffset += normalizedRY;
  70705. }
  70706. }
  70707. }
  70708. var LSValues = this.gamepad.leftStick;
  70709. if (LSValues && LSValues.y != 0) {
  70710. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70711. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70712. this.camera.inertialRadiusOffset -= normalizedLY;
  70713. }
  70714. }
  70715. }
  70716. };
  70717. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70718. return "ArcRotateCameraGamepadInput";
  70719. };
  70720. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70721. return "gamepad";
  70722. };
  70723. __decorate([
  70724. BABYLON.serialize()
  70725. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70726. __decorate([
  70727. BABYLON.serialize()
  70728. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70729. return ArcRotateCameraGamepadInput;
  70730. }());
  70731. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70732. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70733. })(BABYLON || (BABYLON = {}));
  70734. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70735. var BABYLON;
  70736. (function (BABYLON) {
  70737. var GamepadManager = /** @class */ (function () {
  70738. function GamepadManager(_scene) {
  70739. var _this = this;
  70740. this._scene = _scene;
  70741. this._babylonGamepads = [];
  70742. this._oneGamepadConnected = false;
  70743. this._isMonitoring = false;
  70744. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70745. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70746. this._gamepadEventSupported = false;
  70747. }
  70748. else {
  70749. this._gamepadEventSupported = 'GamepadEvent' in window;
  70750. this._gamepadSupport = (navigator.getGamepads ||
  70751. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70752. }
  70753. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70754. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70755. for (var i in _this._babylonGamepads) {
  70756. var gamepad = _this._babylonGamepads[i];
  70757. if (gamepad && gamepad._isConnected) {
  70758. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70759. }
  70760. }
  70761. });
  70762. this._onGamepadConnectedEvent = function (evt) {
  70763. var gamepad = evt.gamepad;
  70764. if (gamepad.index in _this._babylonGamepads) {
  70765. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70766. return;
  70767. }
  70768. }
  70769. var newGamepad;
  70770. if (_this._babylonGamepads[gamepad.index]) {
  70771. newGamepad = _this._babylonGamepads[gamepad.index];
  70772. newGamepad.browserGamepad = gamepad;
  70773. newGamepad._isConnected = true;
  70774. }
  70775. else {
  70776. newGamepad = _this._addNewGamepad(gamepad);
  70777. }
  70778. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70779. _this._startMonitoringGamepads();
  70780. };
  70781. this._onGamepadDisconnectedEvent = function (evt) {
  70782. var gamepad = evt.gamepad;
  70783. // Remove the gamepad from the list of gamepads to monitor.
  70784. for (var i in _this._babylonGamepads) {
  70785. if (_this._babylonGamepads[i].index === gamepad.index) {
  70786. var disconnectedGamepad = _this._babylonGamepads[i];
  70787. disconnectedGamepad._isConnected = false;
  70788. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70789. break;
  70790. }
  70791. }
  70792. };
  70793. if (this._gamepadSupport) {
  70794. //first add already-connected gamepads
  70795. this._updateGamepadObjects();
  70796. if (this._babylonGamepads.length) {
  70797. this._startMonitoringGamepads();
  70798. }
  70799. // Checking if the gamepad connected event is supported (like in Firefox)
  70800. if (this._gamepadEventSupported) {
  70801. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70802. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70803. }
  70804. else {
  70805. this._startMonitoringGamepads();
  70806. }
  70807. }
  70808. }
  70809. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70810. get: function () {
  70811. return this._babylonGamepads;
  70812. },
  70813. enumerable: true,
  70814. configurable: true
  70815. });
  70816. GamepadManager.prototype.getGamepadByType = function (type) {
  70817. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70818. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70819. var gamepad = _a[_i];
  70820. if (gamepad && gamepad.type === type) {
  70821. return gamepad;
  70822. }
  70823. }
  70824. return null;
  70825. };
  70826. GamepadManager.prototype.dispose = function () {
  70827. if (this._gamepadEventSupported) {
  70828. if (this._onGamepadConnectedEvent) {
  70829. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70830. }
  70831. if (this._onGamepadDisconnectedEvent) {
  70832. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70833. }
  70834. this._onGamepadConnectedEvent = null;
  70835. this._onGamepadDisconnectedEvent = null;
  70836. }
  70837. this._babylonGamepads.forEach(function (gamepad) {
  70838. gamepad.dispose();
  70839. });
  70840. this.onGamepadConnectedObservable.clear();
  70841. this.onGamepadDisconnectedObservable.clear();
  70842. this._oneGamepadConnected = false;
  70843. this._stopMonitoringGamepads();
  70844. this._babylonGamepads = [];
  70845. };
  70846. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70847. if (!this._oneGamepadConnected) {
  70848. this._oneGamepadConnected = true;
  70849. }
  70850. var newGamepad;
  70851. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70852. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70853. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70854. }
  70855. // if pose is supported, use the (WebVR) pose enabled controller
  70856. else if (gamepad.pose) {
  70857. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70858. }
  70859. else {
  70860. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70861. }
  70862. this._babylonGamepads[newGamepad.index] = newGamepad;
  70863. return newGamepad;
  70864. };
  70865. GamepadManager.prototype._startMonitoringGamepads = function () {
  70866. if (!this._isMonitoring) {
  70867. this._isMonitoring = true;
  70868. //back-comp
  70869. if (!this._scene) {
  70870. this._checkGamepadsStatus();
  70871. }
  70872. }
  70873. };
  70874. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70875. this._isMonitoring = false;
  70876. };
  70877. GamepadManager.prototype._checkGamepadsStatus = function () {
  70878. var _this = this;
  70879. // Hack to be compatible Chrome
  70880. this._updateGamepadObjects();
  70881. for (var i in this._babylonGamepads) {
  70882. var gamepad = this._babylonGamepads[i];
  70883. if (!gamepad || !gamepad.isConnected) {
  70884. continue;
  70885. }
  70886. gamepad.update();
  70887. }
  70888. if (this._isMonitoring && !this._scene) {
  70889. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70890. }
  70891. };
  70892. // This function is called only on Chrome, which does not properly support
  70893. // connection/disconnection events and forces you to recopy again the gamepad object
  70894. GamepadManager.prototype._updateGamepadObjects = function () {
  70895. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70896. for (var i = 0; i < gamepads.length; i++) {
  70897. var gamepad = gamepads[i];
  70898. if (gamepad) {
  70899. if (!this._babylonGamepads[gamepad.index]) {
  70900. var newGamepad = this._addNewGamepad(gamepad);
  70901. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70902. }
  70903. else {
  70904. // Forced to copy again this object for Chrome for unknown reason
  70905. this._babylonGamepads[i].browserGamepad = gamepad;
  70906. if (!this._babylonGamepads[i].isConnected) {
  70907. this._babylonGamepads[i]._isConnected = true;
  70908. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70909. }
  70910. }
  70911. }
  70912. }
  70913. };
  70914. return GamepadManager;
  70915. }());
  70916. BABYLON.GamepadManager = GamepadManager;
  70917. })(BABYLON || (BABYLON = {}));
  70918. //# sourceMappingURL=babylon.gamepadManager.js.map
  70919. var BABYLON;
  70920. (function (BABYLON) {
  70921. var StickValues = /** @class */ (function () {
  70922. function StickValues(x, y) {
  70923. this.x = x;
  70924. this.y = y;
  70925. }
  70926. return StickValues;
  70927. }());
  70928. BABYLON.StickValues = StickValues;
  70929. var Gamepad = /** @class */ (function () {
  70930. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70931. if (leftStickX === void 0) { leftStickX = 0; }
  70932. if (leftStickY === void 0) { leftStickY = 1; }
  70933. if (rightStickX === void 0) { rightStickX = 2; }
  70934. if (rightStickY === void 0) { rightStickY = 3; }
  70935. this.id = id;
  70936. this.index = index;
  70937. this.browserGamepad = browserGamepad;
  70938. this._isConnected = true;
  70939. this._invertLeftStickY = false;
  70940. this.type = Gamepad.GAMEPAD;
  70941. this._leftStickAxisX = leftStickX;
  70942. this._leftStickAxisY = leftStickY;
  70943. this._rightStickAxisX = rightStickX;
  70944. this._rightStickAxisY = rightStickY;
  70945. if (this.browserGamepad.axes.length >= 2) {
  70946. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70947. }
  70948. if (this.browserGamepad.axes.length >= 4) {
  70949. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70950. }
  70951. }
  70952. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70953. get: function () {
  70954. return this._isConnected;
  70955. },
  70956. enumerable: true,
  70957. configurable: true
  70958. });
  70959. Gamepad.prototype.onleftstickchanged = function (callback) {
  70960. this._onleftstickchanged = callback;
  70961. };
  70962. Gamepad.prototype.onrightstickchanged = function (callback) {
  70963. this._onrightstickchanged = callback;
  70964. };
  70965. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70966. get: function () {
  70967. return this._leftStick;
  70968. },
  70969. set: function (newValues) {
  70970. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70971. this._onleftstickchanged(newValues);
  70972. }
  70973. this._leftStick = newValues;
  70974. },
  70975. enumerable: true,
  70976. configurable: true
  70977. });
  70978. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70979. get: function () {
  70980. return this._rightStick;
  70981. },
  70982. set: function (newValues) {
  70983. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70984. this._onrightstickchanged(newValues);
  70985. }
  70986. this._rightStick = newValues;
  70987. },
  70988. enumerable: true,
  70989. configurable: true
  70990. });
  70991. Gamepad.prototype.update = function () {
  70992. if (this._leftStick) {
  70993. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70994. if (this._invertLeftStickY) {
  70995. this.leftStick.y *= -1;
  70996. }
  70997. }
  70998. if (this._rightStick) {
  70999. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71000. }
  71001. };
  71002. Gamepad.prototype.dispose = function () {
  71003. };
  71004. Gamepad.GAMEPAD = 0;
  71005. Gamepad.GENERIC = 1;
  71006. Gamepad.XBOX = 2;
  71007. Gamepad.POSE_ENABLED = 3;
  71008. return Gamepad;
  71009. }());
  71010. BABYLON.Gamepad = Gamepad;
  71011. var GenericPad = /** @class */ (function (_super) {
  71012. __extends(GenericPad, _super);
  71013. function GenericPad(id, index, browserGamepad) {
  71014. var _this = _super.call(this, id, index, browserGamepad) || this;
  71015. _this.onButtonDownObservable = new BABYLON.Observable();
  71016. _this.onButtonUpObservable = new BABYLON.Observable();
  71017. _this.type = Gamepad.GENERIC;
  71018. _this._buttons = new Array(browserGamepad.buttons.length);
  71019. return _this;
  71020. }
  71021. GenericPad.prototype.onbuttondown = function (callback) {
  71022. this._onbuttondown = callback;
  71023. };
  71024. GenericPad.prototype.onbuttonup = function (callback) {
  71025. this._onbuttonup = callback;
  71026. };
  71027. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71028. if (newValue !== currentValue) {
  71029. if (newValue === 1) {
  71030. if (this._onbuttondown) {
  71031. this._onbuttondown(buttonIndex);
  71032. }
  71033. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71034. }
  71035. if (newValue === 0) {
  71036. if (this._onbuttonup) {
  71037. this._onbuttonup(buttonIndex);
  71038. }
  71039. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71040. }
  71041. }
  71042. return newValue;
  71043. };
  71044. GenericPad.prototype.update = function () {
  71045. _super.prototype.update.call(this);
  71046. for (var index = 0; index < this._buttons.length; index++) {
  71047. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71048. }
  71049. };
  71050. GenericPad.prototype.dispose = function () {
  71051. _super.prototype.dispose.call(this);
  71052. this.onButtonDownObservable.clear();
  71053. this.onButtonUpObservable.clear();
  71054. };
  71055. return GenericPad;
  71056. }(Gamepad));
  71057. BABYLON.GenericPad = GenericPad;
  71058. })(BABYLON || (BABYLON = {}));
  71059. //# sourceMappingURL=babylon.gamepad.js.map
  71060. var BABYLON;
  71061. (function (BABYLON) {
  71062. /**
  71063. * Defines supported buttons for XBox360 compatible gamepads
  71064. */
  71065. var Xbox360Button;
  71066. (function (Xbox360Button) {
  71067. /** A */
  71068. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71069. /** B */
  71070. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71071. /** X */
  71072. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71073. /** Y */
  71074. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71075. /** Start */
  71076. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71077. /** Back */
  71078. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71079. /** Left button */
  71080. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71081. /** Right button */
  71082. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71083. /** Left stick */
  71084. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71085. /** Right stick */
  71086. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71087. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71088. /** Defines values for XBox360 DPad */
  71089. var Xbox360Dpad;
  71090. (function (Xbox360Dpad) {
  71091. /** Up */
  71092. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71093. /** Down */
  71094. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71095. /** Left */
  71096. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71097. /** Right */
  71098. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71099. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71100. /**
  71101. * Defines a XBox360 gamepad
  71102. */
  71103. var Xbox360Pad = /** @class */ (function (_super) {
  71104. __extends(Xbox360Pad, _super);
  71105. /**
  71106. * Creates a new XBox360 gamepad object
  71107. * @param id defines the id of this gamepad
  71108. * @param index defines its index
  71109. * @param gamepad defines the internal HTML gamepad object
  71110. * @param xboxOne defines if it is a XBox One gamepad
  71111. */
  71112. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71113. if (xboxOne === void 0) { xboxOne = false; }
  71114. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71115. _this._leftTrigger = 0;
  71116. _this._rightTrigger = 0;
  71117. /** Observable raised when a button is pressed */
  71118. _this.onButtonDownObservable = new BABYLON.Observable();
  71119. /** Observable raised when a button is released */
  71120. _this.onButtonUpObservable = new BABYLON.Observable();
  71121. /** Observable raised when a pad is pressed */
  71122. _this.onPadDownObservable = new BABYLON.Observable();
  71123. /** Observable raised when a pad is released */
  71124. _this.onPadUpObservable = new BABYLON.Observable();
  71125. _this._buttonA = 0;
  71126. _this._buttonB = 0;
  71127. _this._buttonX = 0;
  71128. _this._buttonY = 0;
  71129. _this._buttonBack = 0;
  71130. _this._buttonStart = 0;
  71131. _this._buttonLB = 0;
  71132. _this._buttonRB = 0;
  71133. _this._buttonLeftStick = 0;
  71134. _this._buttonRightStick = 0;
  71135. _this._dPadUp = 0;
  71136. _this._dPadDown = 0;
  71137. _this._dPadLeft = 0;
  71138. _this._dPadRight = 0;
  71139. _this._isXboxOnePad = false;
  71140. _this.type = BABYLON.Gamepad.XBOX;
  71141. _this._isXboxOnePad = xboxOne;
  71142. return _this;
  71143. }
  71144. /**
  71145. * Defines the callback to call when left trigger is pressed
  71146. * @param callback defines the callback to use
  71147. */
  71148. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71149. this._onlefttriggerchanged = callback;
  71150. };
  71151. /**
  71152. * Defines the callback to call when right trigger is pressed
  71153. * @param callback defines the callback to use
  71154. */
  71155. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71156. this._onrighttriggerchanged = callback;
  71157. };
  71158. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71159. /**
  71160. * Gets or sets left trigger value
  71161. */
  71162. get: function () {
  71163. return this._leftTrigger;
  71164. },
  71165. set: function (newValue) {
  71166. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71167. this._onlefttriggerchanged(newValue);
  71168. }
  71169. this._leftTrigger = newValue;
  71170. },
  71171. enumerable: true,
  71172. configurable: true
  71173. });
  71174. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71175. /**
  71176. * Gets or sets right trigger value
  71177. */
  71178. get: function () {
  71179. return this._rightTrigger;
  71180. },
  71181. set: function (newValue) {
  71182. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71183. this._onrighttriggerchanged(newValue);
  71184. }
  71185. this._rightTrigger = newValue;
  71186. },
  71187. enumerable: true,
  71188. configurable: true
  71189. });
  71190. /**
  71191. * Defines the callback to call when a button is pressed
  71192. * @param callback defines the callback to use
  71193. */
  71194. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71195. this._onbuttondown = callback;
  71196. };
  71197. /**
  71198. * Defines the callback to call when a button is released
  71199. * @param callback defines the callback to use
  71200. */
  71201. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71202. this._onbuttonup = callback;
  71203. };
  71204. /**
  71205. * Defines the callback to call when a pad is pressed
  71206. * @param callback defines the callback to use
  71207. */
  71208. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71209. this._ondpaddown = callback;
  71210. };
  71211. /**
  71212. * Defines the callback to call when a pad is released
  71213. * @param callback defines the callback to use
  71214. */
  71215. Xbox360Pad.prototype.ondpadup = function (callback) {
  71216. this._ondpadup = callback;
  71217. };
  71218. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71219. if (newValue !== currentValue) {
  71220. if (newValue === 1) {
  71221. if (this._onbuttondown) {
  71222. this._onbuttondown(buttonType);
  71223. }
  71224. this.onButtonDownObservable.notifyObservers(buttonType);
  71225. }
  71226. if (newValue === 0) {
  71227. if (this._onbuttonup) {
  71228. this._onbuttonup(buttonType);
  71229. }
  71230. this.onButtonUpObservable.notifyObservers(buttonType);
  71231. }
  71232. }
  71233. return newValue;
  71234. };
  71235. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71236. if (newValue !== currentValue) {
  71237. if (newValue === 1) {
  71238. if (this._ondpaddown) {
  71239. this._ondpaddown(buttonType);
  71240. }
  71241. this.onPadDownObservable.notifyObservers(buttonType);
  71242. }
  71243. if (newValue === 0) {
  71244. if (this._ondpadup) {
  71245. this._ondpadup(buttonType);
  71246. }
  71247. this.onPadUpObservable.notifyObservers(buttonType);
  71248. }
  71249. }
  71250. return newValue;
  71251. };
  71252. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71253. /** Gets or sets value of A button */
  71254. get: function () {
  71255. return this._buttonA;
  71256. },
  71257. set: function (value) {
  71258. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71259. },
  71260. enumerable: true,
  71261. configurable: true
  71262. });
  71263. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71264. /** Gets or sets value of B button */
  71265. get: function () {
  71266. return this._buttonB;
  71267. },
  71268. set: function (value) {
  71269. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71270. },
  71271. enumerable: true,
  71272. configurable: true
  71273. });
  71274. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71275. /** Gets or sets value of X button */
  71276. get: function () {
  71277. return this._buttonX;
  71278. },
  71279. set: function (value) {
  71280. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71281. },
  71282. enumerable: true,
  71283. configurable: true
  71284. });
  71285. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71286. /** Gets or sets value of Y button */
  71287. get: function () {
  71288. return this._buttonY;
  71289. },
  71290. set: function (value) {
  71291. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71292. },
  71293. enumerable: true,
  71294. configurable: true
  71295. });
  71296. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71297. /** Gets or sets value of Start button */
  71298. get: function () {
  71299. return this._buttonStart;
  71300. },
  71301. set: function (value) {
  71302. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71303. },
  71304. enumerable: true,
  71305. configurable: true
  71306. });
  71307. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71308. /** Gets or sets value of Back button */
  71309. get: function () {
  71310. return this._buttonBack;
  71311. },
  71312. set: function (value) {
  71313. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71314. },
  71315. enumerable: true,
  71316. configurable: true
  71317. });
  71318. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71319. /** Gets or sets value of Left button */
  71320. get: function () {
  71321. return this._buttonLB;
  71322. },
  71323. set: function (value) {
  71324. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71325. },
  71326. enumerable: true,
  71327. configurable: true
  71328. });
  71329. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71330. /** Gets or sets value of Right button */
  71331. get: function () {
  71332. return this._buttonRB;
  71333. },
  71334. set: function (value) {
  71335. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71336. },
  71337. enumerable: true,
  71338. configurable: true
  71339. });
  71340. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71341. /** Gets or sets value of left stick */
  71342. get: function () {
  71343. return this._buttonLeftStick;
  71344. },
  71345. set: function (value) {
  71346. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71347. },
  71348. enumerable: true,
  71349. configurable: true
  71350. });
  71351. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71352. /** Gets or sets value of right stick */
  71353. get: function () {
  71354. return this._buttonRightStick;
  71355. },
  71356. set: function (value) {
  71357. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71358. },
  71359. enumerable: true,
  71360. configurable: true
  71361. });
  71362. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71363. /** Gets or sets value of DPad up */
  71364. get: function () {
  71365. return this._dPadUp;
  71366. },
  71367. set: function (value) {
  71368. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71369. },
  71370. enumerable: true,
  71371. configurable: true
  71372. });
  71373. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71374. /** Gets or sets value of DPad down */
  71375. get: function () {
  71376. return this._dPadDown;
  71377. },
  71378. set: function (value) {
  71379. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71380. },
  71381. enumerable: true,
  71382. configurable: true
  71383. });
  71384. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71385. /** Gets or sets value of DPad left */
  71386. get: function () {
  71387. return this._dPadLeft;
  71388. },
  71389. set: function (value) {
  71390. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71391. },
  71392. enumerable: true,
  71393. configurable: true
  71394. });
  71395. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71396. /** Gets or sets value of DPad right */
  71397. get: function () {
  71398. return this._dPadRight;
  71399. },
  71400. set: function (value) {
  71401. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71402. },
  71403. enumerable: true,
  71404. configurable: true
  71405. });
  71406. /**
  71407. * Force the gamepad to synchronize with device values
  71408. */
  71409. Xbox360Pad.prototype.update = function () {
  71410. _super.prototype.update.call(this);
  71411. if (this._isXboxOnePad) {
  71412. this.buttonA = this.browserGamepad.buttons[0].value;
  71413. this.buttonB = this.browserGamepad.buttons[1].value;
  71414. this.buttonX = this.browserGamepad.buttons[2].value;
  71415. this.buttonY = this.browserGamepad.buttons[3].value;
  71416. this.buttonLB = this.browserGamepad.buttons[4].value;
  71417. this.buttonRB = this.browserGamepad.buttons[5].value;
  71418. this.leftTrigger = this.browserGamepad.axes[2];
  71419. this.rightTrigger = this.browserGamepad.axes[5];
  71420. this.buttonBack = this.browserGamepad.buttons[9].value;
  71421. this.buttonStart = this.browserGamepad.buttons[8].value;
  71422. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71423. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71424. this.dPadUp = this.browserGamepad.buttons[11].value;
  71425. this.dPadDown = this.browserGamepad.buttons[12].value;
  71426. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71427. this.dPadRight = this.browserGamepad.buttons[14].value;
  71428. }
  71429. else {
  71430. this.buttonA = this.browserGamepad.buttons[0].value;
  71431. this.buttonB = this.browserGamepad.buttons[1].value;
  71432. this.buttonX = this.browserGamepad.buttons[2].value;
  71433. this.buttonY = this.browserGamepad.buttons[3].value;
  71434. this.buttonLB = this.browserGamepad.buttons[4].value;
  71435. this.buttonRB = this.browserGamepad.buttons[5].value;
  71436. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71437. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71438. this.buttonBack = this.browserGamepad.buttons[8].value;
  71439. this.buttonStart = this.browserGamepad.buttons[9].value;
  71440. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71441. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71442. this.dPadUp = this.browserGamepad.buttons[12].value;
  71443. this.dPadDown = this.browserGamepad.buttons[13].value;
  71444. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71445. this.dPadRight = this.browserGamepad.buttons[15].value;
  71446. }
  71447. };
  71448. Xbox360Pad.prototype.dispose = function () {
  71449. _super.prototype.dispose.call(this);
  71450. this.onButtonDownObservable.clear();
  71451. this.onButtonUpObservable.clear();
  71452. this.onPadDownObservable.clear();
  71453. this.onPadUpObservable.clear();
  71454. };
  71455. return Xbox360Pad;
  71456. }(BABYLON.Gamepad));
  71457. BABYLON.Xbox360Pad = Xbox360Pad;
  71458. })(BABYLON || (BABYLON = {}));
  71459. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71460. var BABYLON;
  71461. (function (BABYLON) {
  71462. /**
  71463. * Defines the types of pose enabled controllers that are supported
  71464. */
  71465. var PoseEnabledControllerType;
  71466. (function (PoseEnabledControllerType) {
  71467. /**
  71468. * HTC Vive
  71469. */
  71470. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71471. /**
  71472. * Oculus Rift
  71473. */
  71474. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71475. /**
  71476. * Windows mixed reality
  71477. */
  71478. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71479. /**
  71480. * Samsung gear VR
  71481. */
  71482. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71483. /**
  71484. * Google Daydream
  71485. */
  71486. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71487. /**
  71488. * Generic
  71489. */
  71490. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71491. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71492. /**
  71493. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71494. */
  71495. var PoseEnabledControllerHelper = /** @class */ (function () {
  71496. function PoseEnabledControllerHelper() {
  71497. }
  71498. /**
  71499. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71500. * @param vrGamepad the gamepad to initialized
  71501. * @returns a vr controller of the type the gamepad identified as
  71502. */
  71503. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71504. // Oculus Touch
  71505. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71506. return new BABYLON.OculusTouchController(vrGamepad);
  71507. }
  71508. // Windows Mixed Reality controllers
  71509. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71510. return new BABYLON.WindowsMotionController(vrGamepad);
  71511. }
  71512. // HTC Vive
  71513. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71514. return new BABYLON.ViveController(vrGamepad);
  71515. }
  71516. // Samsung/Oculus Gear VR or Oculus Go
  71517. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71518. return new BABYLON.GearVRController(vrGamepad);
  71519. }
  71520. // Google Daydream
  71521. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71522. return new BABYLON.DaydreamController(vrGamepad);
  71523. }
  71524. // Generic
  71525. else {
  71526. return new BABYLON.GenericController(vrGamepad);
  71527. }
  71528. };
  71529. return PoseEnabledControllerHelper;
  71530. }());
  71531. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71532. /**
  71533. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71534. */
  71535. var PoseEnabledController = /** @class */ (function (_super) {
  71536. __extends(PoseEnabledController, _super);
  71537. /**
  71538. * Creates a new PoseEnabledController from a gamepad
  71539. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71540. */
  71541. function PoseEnabledController(browserGamepad) {
  71542. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71543. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71544. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71545. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71546. /**
  71547. * The device position in babylon space
  71548. */
  71549. _this.devicePosition = BABYLON.Vector3.Zero();
  71550. /**
  71551. * The device rotation in babylon space
  71552. */
  71553. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71554. /**
  71555. * The scale factor of the device in babylon space
  71556. */
  71557. _this.deviceScaleFactor = 1;
  71558. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71559. /**
  71560. * Internal, matrix used to convert room space to babylon space
  71561. */
  71562. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71563. /**
  71564. * Node to be used when casting a ray from the controller
  71565. */
  71566. _this._pointingPoseNode = null;
  71567. _this._workingMatrix = BABYLON.Matrix.Identity();
  71568. /**
  71569. * @hidden
  71570. */
  71571. _this._meshAttachedObservable = new BABYLON.Observable();
  71572. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71573. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71574. _this.position = BABYLON.Vector3.Zero();
  71575. _this.rotationQuaternion = new BABYLON.Quaternion();
  71576. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71577. _this._calculatedRotation = new BABYLON.Quaternion();
  71578. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71579. return _this;
  71580. }
  71581. /**
  71582. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71583. */
  71584. PoseEnabledController.prototype.update = function () {
  71585. _super.prototype.update.call(this);
  71586. this._updatePoseAndMesh();
  71587. };
  71588. /**
  71589. * Updates only the pose device and mesh without doing any button event checking
  71590. */
  71591. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71592. var pose = this.browserGamepad.pose;
  71593. this.updateFromDevice(pose);
  71594. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71595. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71596. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71597. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71598. if (this._mesh) {
  71599. this._mesh.position.copyFrom(this.devicePosition);
  71600. if (this._mesh.rotationQuaternion) {
  71601. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71602. }
  71603. }
  71604. };
  71605. /**
  71606. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71607. * @param poseData raw pose fromthe device
  71608. */
  71609. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71610. if (poseData) {
  71611. this.rawPose = poseData;
  71612. if (poseData.position) {
  71613. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71614. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71615. this._deviceRoomPosition.z *= -1;
  71616. }
  71617. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71618. this._calculatedPosition.addInPlace(this.position);
  71619. }
  71620. var pose = this.rawPose;
  71621. if (poseData.orientation && pose.orientation) {
  71622. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71623. if (this._mesh) {
  71624. if (this._mesh.getScene().useRightHandedSystem) {
  71625. this._deviceRoomRotationQuaternion.z *= -1;
  71626. this._deviceRoomRotationQuaternion.w *= -1;
  71627. }
  71628. else {
  71629. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71630. }
  71631. }
  71632. // if the camera is set, rotate to the camera's rotation
  71633. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71634. }
  71635. }
  71636. };
  71637. /**
  71638. * Attaches a mesh to the controller
  71639. * @param mesh the mesh to be attached
  71640. */
  71641. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71642. if (this._mesh) {
  71643. this._mesh.parent = null;
  71644. }
  71645. this._mesh = mesh;
  71646. if (this._poseControlledCamera) {
  71647. this._mesh.parent = this._poseControlledCamera;
  71648. }
  71649. if (!this._mesh.rotationQuaternion) {
  71650. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71651. }
  71652. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  71653. this._updatePoseAndMesh();
  71654. if (this._pointingPoseNode) {
  71655. var parents = [];
  71656. var obj = this._pointingPoseNode;
  71657. while (obj.parent) {
  71658. parents.push(obj.parent);
  71659. obj = obj.parent;
  71660. }
  71661. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71662. }
  71663. this._meshAttachedObservable.notifyObservers(mesh);
  71664. };
  71665. /**
  71666. * Attaches the controllers mesh to a camera
  71667. * @param camera the camera the mesh should be attached to
  71668. */
  71669. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71670. this._poseControlledCamera = camera;
  71671. if (this._mesh) {
  71672. this._mesh.parent = this._poseControlledCamera;
  71673. }
  71674. };
  71675. /**
  71676. * Disposes of the controller
  71677. */
  71678. PoseEnabledController.prototype.dispose = function () {
  71679. if (this._mesh) {
  71680. this._mesh.dispose();
  71681. }
  71682. this._mesh = null;
  71683. _super.prototype.dispose.call(this);
  71684. };
  71685. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71686. /**
  71687. * The mesh that is attached to the controller
  71688. */
  71689. get: function () {
  71690. return this._mesh;
  71691. },
  71692. enumerable: true,
  71693. configurable: true
  71694. });
  71695. /**
  71696. * Gets the ray of the controller in the direction the controller is pointing
  71697. * @param length the length the resulting ray should be
  71698. * @returns a ray in the direction the controller is pointing
  71699. */
  71700. PoseEnabledController.prototype.getForwardRay = function (length) {
  71701. if (length === void 0) { length = 100; }
  71702. if (!this.mesh) {
  71703. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71704. }
  71705. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71706. var origin = m.getTranslation();
  71707. var forward = new BABYLON.Vector3(0, 0, -1);
  71708. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71709. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71710. return new BABYLON.Ray(origin, direction, length);
  71711. };
  71712. /**
  71713. * Name of the child mesh that can be used to cast a ray from the controller
  71714. */
  71715. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71716. return PoseEnabledController;
  71717. }(BABYLON.Gamepad));
  71718. BABYLON.PoseEnabledController = PoseEnabledController;
  71719. })(BABYLON || (BABYLON = {}));
  71720. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71721. var BABYLON;
  71722. (function (BABYLON) {
  71723. /**
  71724. * Defines the WebVRController object that represents controllers tracked in 3D space
  71725. */
  71726. var WebVRController = /** @class */ (function (_super) {
  71727. __extends(WebVRController, _super);
  71728. /**
  71729. * Creates a new WebVRController from a gamepad
  71730. * @param vrGamepad the gamepad that the WebVRController should be created from
  71731. */
  71732. function WebVRController(vrGamepad) {
  71733. var _this = _super.call(this, vrGamepad) || this;
  71734. // Observables
  71735. /**
  71736. * Fired when the trigger state has changed
  71737. */
  71738. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71739. /**
  71740. * Fired when the main button state has changed
  71741. */
  71742. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71743. /**
  71744. * Fired when the secondary button state has changed
  71745. */
  71746. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71747. /**
  71748. * Fired when the pad state has changed
  71749. */
  71750. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71751. /**
  71752. * Fired when controllers stick values have changed
  71753. */
  71754. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71755. /**
  71756. * X and Y axis corrisponding to the controllers joystick
  71757. */
  71758. _this.pad = { x: 0, y: 0 };
  71759. // avoid GC, store state in a tmp object
  71760. _this._changes = {
  71761. pressChanged: false,
  71762. touchChanged: false,
  71763. valueChanged: false,
  71764. changed: false
  71765. };
  71766. _this._buttons = new Array(vrGamepad.buttons.length);
  71767. _this.hand = vrGamepad.hand;
  71768. return _this;
  71769. }
  71770. /**
  71771. * Fired when a controller button's state has changed
  71772. * @param callback the callback containing the button that was modified
  71773. */
  71774. WebVRController.prototype.onButtonStateChange = function (callback) {
  71775. this._onButtonStateChange = callback;
  71776. };
  71777. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71778. /**
  71779. * The default controller model for the controller
  71780. */
  71781. get: function () {
  71782. return this._defaultModel;
  71783. },
  71784. enumerable: true,
  71785. configurable: true
  71786. });
  71787. /**
  71788. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71789. */
  71790. WebVRController.prototype.update = function () {
  71791. _super.prototype.update.call(this);
  71792. for (var index = 0; index < this._buttons.length; index++) {
  71793. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71794. }
  71795. ;
  71796. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71797. this.pad.x = this.leftStick.x;
  71798. this.pad.y = this.leftStick.y;
  71799. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71800. }
  71801. };
  71802. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71803. if (!newState) {
  71804. newState = {
  71805. pressed: false,
  71806. touched: false,
  71807. value: 0
  71808. };
  71809. }
  71810. if (!currentState) {
  71811. this._buttons[buttonIndex] = {
  71812. pressed: newState.pressed,
  71813. touched: newState.touched,
  71814. value: newState.value
  71815. };
  71816. return;
  71817. }
  71818. this._checkChanges(newState, currentState);
  71819. if (this._changes.changed) {
  71820. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71821. this._handleButtonChange(buttonIndex, newState, this._changes);
  71822. }
  71823. this._buttons[buttonIndex].pressed = newState.pressed;
  71824. this._buttons[buttonIndex].touched = newState.touched;
  71825. // oculus triggers are never 0, thou not touched.
  71826. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71827. };
  71828. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71829. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71830. this._changes.touchChanged = newState.touched !== currentState.touched;
  71831. this._changes.valueChanged = newState.value !== currentState.value;
  71832. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71833. return this._changes;
  71834. };
  71835. /**
  71836. * Disposes of th webVRCOntroller
  71837. */
  71838. WebVRController.prototype.dispose = function () {
  71839. _super.prototype.dispose.call(this);
  71840. this.onTriggerStateChangedObservable.clear();
  71841. this.onMainButtonStateChangedObservable.clear();
  71842. this.onSecondaryButtonStateChangedObservable.clear();
  71843. this.onPadStateChangedObservable.clear();
  71844. this.onPadValuesChangedObservable.clear();
  71845. };
  71846. return WebVRController;
  71847. }(BABYLON.PoseEnabledController));
  71848. BABYLON.WebVRController = WebVRController;
  71849. })(BABYLON || (BABYLON = {}));
  71850. //# sourceMappingURL=babylon.webVRController.js.map
  71851. var BABYLON;
  71852. (function (BABYLON) {
  71853. /**
  71854. * Oculus Touch Controller
  71855. */
  71856. var OculusTouchController = /** @class */ (function (_super) {
  71857. __extends(OculusTouchController, _super);
  71858. /**
  71859. * Creates a new OculusTouchController from a gamepad
  71860. * @param vrGamepad the gamepad that the controller should be created from
  71861. */
  71862. function OculusTouchController(vrGamepad) {
  71863. var _this = _super.call(this, vrGamepad) || this;
  71864. /**
  71865. * Fired when the secondary trigger on this controller is modified
  71866. */
  71867. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71868. /**
  71869. * Fired when the thumb rest on this controller is modified
  71870. */
  71871. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71872. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71873. return _this;
  71874. }
  71875. /**
  71876. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71877. * @param scene scene in which to add meshes
  71878. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71879. */
  71880. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71881. var _this = this;
  71882. var meshName;
  71883. // Hand
  71884. if (this.hand === 'left') {
  71885. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71886. }
  71887. else { // Right is the default if no hand is specified
  71888. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71889. }
  71890. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71891. /*
  71892. Parent Mesh name: oculus_touch_left
  71893. - body
  71894. - trigger
  71895. - thumbstick
  71896. - grip
  71897. - button_y
  71898. - button_x
  71899. - button_enter
  71900. */
  71901. _this._defaultModel = newMeshes[1];
  71902. _this.attachToMesh(_this._defaultModel);
  71903. if (meshLoaded) {
  71904. meshLoaded(_this._defaultModel);
  71905. }
  71906. });
  71907. };
  71908. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71909. /**
  71910. * Fired when the A button on this controller is modified
  71911. */
  71912. get: function () {
  71913. if (this.hand === 'right') {
  71914. return this.onMainButtonStateChangedObservable;
  71915. }
  71916. else {
  71917. throw new Error('No A button on left hand');
  71918. }
  71919. },
  71920. enumerable: true,
  71921. configurable: true
  71922. });
  71923. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71924. /**
  71925. * Fired when the B button on this controller is modified
  71926. */
  71927. get: function () {
  71928. if (this.hand === 'right') {
  71929. return this.onSecondaryButtonStateChangedObservable;
  71930. }
  71931. else {
  71932. throw new Error('No B button on left hand');
  71933. }
  71934. },
  71935. enumerable: true,
  71936. configurable: true
  71937. });
  71938. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71939. /**
  71940. * Fired when the X button on this controller is modified
  71941. */
  71942. get: function () {
  71943. if (this.hand === 'left') {
  71944. return this.onMainButtonStateChangedObservable;
  71945. }
  71946. else {
  71947. throw new Error('No X button on right hand');
  71948. }
  71949. },
  71950. enumerable: true,
  71951. configurable: true
  71952. });
  71953. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71954. /**
  71955. * Fired when the Y button on this controller is modified
  71956. */
  71957. get: function () {
  71958. if (this.hand === 'left') {
  71959. return this.onSecondaryButtonStateChangedObservable;
  71960. }
  71961. else {
  71962. throw new Error('No Y button on right hand');
  71963. }
  71964. },
  71965. enumerable: true,
  71966. configurable: true
  71967. });
  71968. /**
  71969. * Called once for each button that changed state since the last frame
  71970. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71971. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71972. * 2) secondary trigger (same)
  71973. * 3) A (right) X (left), touch, pressed = value
  71974. * 4) B / Y
  71975. * 5) thumb rest
  71976. * @param buttonIdx Which button index changed
  71977. * @param state New state of the button
  71978. * @param changes Which properties on the state changed since last frame
  71979. */
  71980. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71981. var notifyObject = state; //{ state: state, changes: changes };
  71982. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71983. switch (buttonIdx) {
  71984. case 0:
  71985. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71986. return;
  71987. case 1: // index trigger
  71988. if (this._defaultModel) {
  71989. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71990. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71991. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71992. }
  71993. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71994. return;
  71995. case 2: // secondary trigger
  71996. if (this._defaultModel) {
  71997. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71998. }
  71999. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72000. return;
  72001. case 3:
  72002. if (this._defaultModel) {
  72003. if (notifyObject.pressed) {
  72004. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72005. }
  72006. else {
  72007. (this._defaultModel.getChildren()[1]).position.y = 0;
  72008. }
  72009. }
  72010. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72011. return;
  72012. case 4:
  72013. if (this._defaultModel) {
  72014. if (notifyObject.pressed) {
  72015. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72016. }
  72017. else {
  72018. (this._defaultModel.getChildren()[2]).position.y = 0;
  72019. }
  72020. }
  72021. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72022. return;
  72023. case 5:
  72024. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72025. return;
  72026. }
  72027. };
  72028. /**
  72029. * Base Url for the controller model.
  72030. */
  72031. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72032. /**
  72033. * File name for the left controller model.
  72034. */
  72035. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72036. /**
  72037. * File name for the right controller model.
  72038. */
  72039. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72040. return OculusTouchController;
  72041. }(BABYLON.WebVRController));
  72042. BABYLON.OculusTouchController = OculusTouchController;
  72043. })(BABYLON || (BABYLON = {}));
  72044. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72045. var BABYLON;
  72046. (function (BABYLON) {
  72047. /**
  72048. * Vive Controller
  72049. */
  72050. var ViveController = /** @class */ (function (_super) {
  72051. __extends(ViveController, _super);
  72052. /**
  72053. * Creates a new ViveController from a gamepad
  72054. * @param vrGamepad the gamepad that the controller should be created from
  72055. */
  72056. function ViveController(vrGamepad) {
  72057. var _this = _super.call(this, vrGamepad) || this;
  72058. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72059. _this._invertLeftStickY = true;
  72060. return _this;
  72061. }
  72062. /**
  72063. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72064. * @param scene scene in which to add meshes
  72065. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72066. */
  72067. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72068. var _this = this;
  72069. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72070. /*
  72071. Parent Mesh name: ViveWand
  72072. - body
  72073. - r_gripper
  72074. - l_gripper
  72075. - menu_button
  72076. - system_button
  72077. - trackpad
  72078. - trigger
  72079. - LED
  72080. */
  72081. _this._defaultModel = newMeshes[1];
  72082. _this.attachToMesh(_this._defaultModel);
  72083. if (meshLoaded) {
  72084. meshLoaded(_this._defaultModel);
  72085. }
  72086. });
  72087. };
  72088. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72089. /**
  72090. * Fired when the left button on this controller is modified
  72091. */
  72092. get: function () {
  72093. return this.onMainButtonStateChangedObservable;
  72094. },
  72095. enumerable: true,
  72096. configurable: true
  72097. });
  72098. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72099. /**
  72100. * Fired when the right button on this controller is modified
  72101. */
  72102. get: function () {
  72103. return this.onMainButtonStateChangedObservable;
  72104. },
  72105. enumerable: true,
  72106. configurable: true
  72107. });
  72108. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72109. /**
  72110. * Fired when the menu button on this controller is modified
  72111. */
  72112. get: function () {
  72113. return this.onSecondaryButtonStateChangedObservable;
  72114. },
  72115. enumerable: true,
  72116. configurable: true
  72117. });
  72118. /**
  72119. * Called once for each button that changed state since the last frame
  72120. * Vive mapping:
  72121. * 0: touchpad
  72122. * 1: trigger
  72123. * 2: left AND right buttons
  72124. * 3: menu button
  72125. * @param buttonIdx Which button index changed
  72126. * @param state New state of the button
  72127. * @param changes Which properties on the state changed since last frame
  72128. */
  72129. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72130. var notifyObject = state; //{ state: state, changes: changes };
  72131. switch (buttonIdx) {
  72132. case 0:
  72133. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72134. return;
  72135. case 1: // index trigger
  72136. if (this._defaultModel) {
  72137. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72138. }
  72139. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72140. return;
  72141. case 2: // left AND right button
  72142. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72143. return;
  72144. case 3:
  72145. if (this._defaultModel) {
  72146. if (notifyObject.pressed) {
  72147. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72148. }
  72149. else {
  72150. (this._defaultModel.getChildren()[2]).position.y = 0;
  72151. }
  72152. }
  72153. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72154. return;
  72155. }
  72156. };
  72157. /**
  72158. * Base Url for the controller model.
  72159. */
  72160. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72161. /**
  72162. * File name for the controller model.
  72163. */
  72164. ViveController.MODEL_FILENAME = 'wand.babylon';
  72165. return ViveController;
  72166. }(BABYLON.WebVRController));
  72167. BABYLON.ViveController = ViveController;
  72168. })(BABYLON || (BABYLON = {}));
  72169. //# sourceMappingURL=babylon.viveController.js.map
  72170. var BABYLON;
  72171. (function (BABYLON) {
  72172. /**
  72173. * Generic Controller
  72174. */
  72175. var GenericController = /** @class */ (function (_super) {
  72176. __extends(GenericController, _super);
  72177. /**
  72178. * Creates a new GenericController from a gamepad
  72179. * @param vrGamepad the gamepad that the controller should be created from
  72180. */
  72181. function GenericController(vrGamepad) {
  72182. return _super.call(this, vrGamepad) || this;
  72183. }
  72184. /**
  72185. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72186. * @param scene scene in which to add meshes
  72187. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72188. */
  72189. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72190. var _this = this;
  72191. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72192. _this._defaultModel = newMeshes[1];
  72193. _this.attachToMesh(_this._defaultModel);
  72194. if (meshLoaded) {
  72195. meshLoaded(_this._defaultModel);
  72196. }
  72197. });
  72198. };
  72199. /**
  72200. * Called once for each button that changed state since the last frame
  72201. * @param buttonIdx Which button index changed
  72202. * @param state New state of the button
  72203. * @param changes Which properties on the state changed since last frame
  72204. */
  72205. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72206. console.log("Button id: " + buttonIdx + "state: ");
  72207. console.dir(state);
  72208. };
  72209. /**
  72210. * Base Url for the controller model.
  72211. */
  72212. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72213. /**
  72214. * File name for the controller model.
  72215. */
  72216. GenericController.MODEL_FILENAME = 'generic.babylon';
  72217. return GenericController;
  72218. }(BABYLON.WebVRController));
  72219. BABYLON.GenericController = GenericController;
  72220. })(BABYLON || (BABYLON = {}));
  72221. //# sourceMappingURL=babylon.genericController.js.map
  72222. var BABYLON;
  72223. (function (BABYLON) {
  72224. /**
  72225. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72226. */
  72227. var LoadedMeshInfo = /** @class */ (function () {
  72228. function LoadedMeshInfo() {
  72229. /**
  72230. * Map of the button meshes contained in the controller
  72231. */
  72232. this.buttonMeshes = {};
  72233. /**
  72234. * Map of the axis meshes contained in the controller
  72235. */
  72236. this.axisMeshes = {};
  72237. }
  72238. return LoadedMeshInfo;
  72239. }());
  72240. /**
  72241. * Defines the WindowsMotionController object that the state of the windows motion controller
  72242. */
  72243. var WindowsMotionController = /** @class */ (function (_super) {
  72244. __extends(WindowsMotionController, _super);
  72245. /**
  72246. * Creates a new WindowsMotionController from a gamepad
  72247. * @param vrGamepad the gamepad that the controller should be created from
  72248. */
  72249. function WindowsMotionController(vrGamepad) {
  72250. var _this = _super.call(this, vrGamepad) || this;
  72251. _this._mapping = {
  72252. // Semantic button names
  72253. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72254. // A mapping of the button name to glTF model node name
  72255. // that should be transformed by button value.
  72256. buttonMeshNames: {
  72257. 'trigger': 'SELECT',
  72258. 'menu': 'MENU',
  72259. 'grip': 'GRASP',
  72260. 'thumbstick': 'THUMBSTICK_PRESS',
  72261. 'trackpad': 'TOUCHPAD_PRESS'
  72262. },
  72263. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72264. buttonObservableNames: {
  72265. 'trigger': 'onTriggerStateChangedObservable',
  72266. 'menu': 'onSecondaryButtonStateChangedObservable',
  72267. 'grip': 'onMainButtonStateChangedObservable',
  72268. 'thumbstick': 'onPadStateChangedObservable',
  72269. 'trackpad': 'onTrackpadChangedObservable'
  72270. },
  72271. // A mapping of the axis name to glTF model node name
  72272. // that should be transformed by axis value.
  72273. // This array mirrors the browserGamepad.axes array, such that
  72274. // the mesh corresponding to axis 0 is in this array index 0.
  72275. axisMeshNames: [
  72276. 'THUMBSTICK_X',
  72277. 'THUMBSTICK_Y',
  72278. 'TOUCHPAD_TOUCH_X',
  72279. 'TOUCHPAD_TOUCH_Y'
  72280. ],
  72281. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72282. };
  72283. /**
  72284. * Fired when the trackpad on this controller is clicked
  72285. */
  72286. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72287. /**
  72288. * Fired when the trackpad on this controller is modified
  72289. */
  72290. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72291. /**
  72292. * The current x and y values of this controller's trackpad
  72293. */
  72294. _this.trackpad = { x: 0, y: 0 };
  72295. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72296. _this._loadedMeshInfo = null;
  72297. return _this;
  72298. }
  72299. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72300. /**
  72301. * Fired when the trigger on this controller is modified
  72302. */
  72303. get: function () {
  72304. return this.onTriggerStateChangedObservable;
  72305. },
  72306. enumerable: true,
  72307. configurable: true
  72308. });
  72309. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72310. /**
  72311. * Fired when the menu button on this controller is modified
  72312. */
  72313. get: function () {
  72314. return this.onSecondaryButtonStateChangedObservable;
  72315. },
  72316. enumerable: true,
  72317. configurable: true
  72318. });
  72319. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72320. /**
  72321. * Fired when the grip button on this controller is modified
  72322. */
  72323. get: function () {
  72324. return this.onMainButtonStateChangedObservable;
  72325. },
  72326. enumerable: true,
  72327. configurable: true
  72328. });
  72329. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72330. /**
  72331. * Fired when the thumbstick button on this controller is modified
  72332. */
  72333. get: function () {
  72334. return this.onPadStateChangedObservable;
  72335. },
  72336. enumerable: true,
  72337. configurable: true
  72338. });
  72339. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72340. /**
  72341. * Fired when the touchpad button on this controller is modified
  72342. */
  72343. get: function () {
  72344. return this.onTrackpadChangedObservable;
  72345. },
  72346. enumerable: true,
  72347. configurable: true
  72348. });
  72349. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72350. /**
  72351. * Fired when the touchpad values on this controller are modified
  72352. */
  72353. get: function () {
  72354. return this.onTrackpadValuesChangedObservable;
  72355. },
  72356. enumerable: true,
  72357. configurable: true
  72358. });
  72359. WindowsMotionController.prototype._updateTrackpad = function () {
  72360. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72361. this.trackpad.x = this.browserGamepad["axes"][2];
  72362. this.trackpad.y = this.browserGamepad["axes"][3];
  72363. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72364. }
  72365. };
  72366. /**
  72367. * Called once per frame by the engine.
  72368. */
  72369. WindowsMotionController.prototype.update = function () {
  72370. _super.prototype.update.call(this);
  72371. if (this.browserGamepad.axes) {
  72372. this._updateTrackpad();
  72373. // Only need to animate axes if there is a loaded mesh
  72374. if (this._loadedMeshInfo) {
  72375. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72376. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72377. }
  72378. }
  72379. }
  72380. };
  72381. /**
  72382. * Called once for each button that changed state since the last frame
  72383. * @param buttonIdx Which button index changed
  72384. * @param state New state of the button
  72385. * @param changes Which properties on the state changed since last frame
  72386. */
  72387. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72388. var buttonName = this._mapping.buttons[buttonIdx];
  72389. if (!buttonName) {
  72390. return;
  72391. }
  72392. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72393. this._updateTrackpad();
  72394. // Only emit events for buttons that we know how to map from index to name
  72395. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72396. if (observable) {
  72397. observable.notifyObservers(state);
  72398. }
  72399. this._lerpButtonTransform(buttonName, state.value);
  72400. };
  72401. /**
  72402. * Moves the buttons on the controller mesh based on their current state
  72403. * @param buttonName the name of the button to move
  72404. * @param buttonValue the value of the button which determines the buttons new position
  72405. */
  72406. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72407. // If there is no loaded mesh, there is nothing to transform.
  72408. if (!this._loadedMeshInfo) {
  72409. return;
  72410. }
  72411. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72412. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72413. return;
  72414. }
  72415. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72416. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72417. };
  72418. /**
  72419. * Moves the axis on the controller mesh based on its current state
  72420. * @param axis the index of the axis
  72421. * @param axisValue the value of the axis which determines the meshes new position
  72422. * @hidden
  72423. */
  72424. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72425. if (!this._loadedMeshInfo) {
  72426. return;
  72427. }
  72428. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72429. if (!meshInfo) {
  72430. return;
  72431. }
  72432. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72433. return;
  72434. }
  72435. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72436. var lerpValue = axisValue * 0.5 + 0.5;
  72437. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72438. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72439. };
  72440. /**
  72441. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72442. * @param scene scene in which to add meshes
  72443. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72444. */
  72445. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72446. var _this = this;
  72447. if (forceDefault === void 0) { forceDefault = false; }
  72448. var path;
  72449. var filename;
  72450. // Checking if GLB loader is present
  72451. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72452. // Determine the device specific folder based on the ID suffix
  72453. var device = 'default';
  72454. if (this.id && !forceDefault) {
  72455. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72456. device = ((match && match[0]) || device);
  72457. }
  72458. // Hand
  72459. if (this.hand === 'left') {
  72460. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72461. }
  72462. else { // Right is the default if no hand is specified
  72463. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72464. }
  72465. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72466. }
  72467. else {
  72468. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72469. path = BABYLON.GenericController.MODEL_BASE_URL;
  72470. filename = BABYLON.GenericController.MODEL_FILENAME;
  72471. }
  72472. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72473. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72474. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72475. if (!_this._loadedMeshInfo) {
  72476. return;
  72477. }
  72478. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72479. _this.attachToMesh(_this._defaultModel);
  72480. if (meshLoaded) {
  72481. meshLoaded(_this._defaultModel);
  72482. }
  72483. }, null, function (scene, message) {
  72484. BABYLON.Tools.Log(message);
  72485. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72486. if (!forceDefault) {
  72487. _this.initControllerMesh(scene, meshLoaded, true);
  72488. }
  72489. });
  72490. };
  72491. /**
  72492. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72493. * can be transformed by button presses and axes values, based on this._mapping.
  72494. *
  72495. * @param scene scene in which the meshes exist
  72496. * @param meshes list of meshes that make up the controller model to process
  72497. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72498. */
  72499. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72500. var loadedMeshInfo = null;
  72501. // Create a new mesh to contain the glTF hierarchy
  72502. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72503. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72504. var childMesh = null;
  72505. for (var i = 0; i < meshes.length; i++) {
  72506. var mesh = meshes[i];
  72507. if (!mesh.parent) {
  72508. // Exclude controller meshes from picking results
  72509. mesh.isPickable = false;
  72510. // Handle root node, attach to the new parentMesh
  72511. childMesh = mesh;
  72512. break;
  72513. }
  72514. }
  72515. if (childMesh) {
  72516. childMesh.setParent(parentMesh);
  72517. // Create our mesh info. Note that this method will always return non-null.
  72518. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72519. }
  72520. else {
  72521. BABYLON.Tools.Warn('Could not find root node in model file.');
  72522. }
  72523. return loadedMeshInfo;
  72524. };
  72525. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72526. var loadedMeshInfo = new LoadedMeshInfo();
  72527. var i;
  72528. loadedMeshInfo.rootNode = rootNode;
  72529. // Reset the caches
  72530. loadedMeshInfo.buttonMeshes = {};
  72531. loadedMeshInfo.axisMeshes = {};
  72532. // Button Meshes
  72533. for (i = 0; i < this._mapping.buttons.length; i++) {
  72534. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72535. if (!buttonMeshName) {
  72536. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72537. continue;
  72538. }
  72539. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72540. if (!buttonMesh) {
  72541. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72542. continue;
  72543. }
  72544. var buttonMeshInfo = {
  72545. index: i,
  72546. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72547. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72548. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72549. };
  72550. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72551. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72552. }
  72553. else {
  72554. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72555. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72556. '(VALUE: ' + !!buttonMeshInfo.value +
  72557. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72558. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72559. ')');
  72560. }
  72561. }
  72562. // Axis Meshes
  72563. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72564. var axisMeshName = this._mapping.axisMeshNames[i];
  72565. if (!axisMeshName) {
  72566. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72567. continue;
  72568. }
  72569. var axisMesh = getChildByName(rootNode, axisMeshName);
  72570. if (!axisMesh) {
  72571. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72572. continue;
  72573. }
  72574. var axisMeshInfo = {
  72575. index: i,
  72576. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72577. min: getImmediateChildByName(axisMesh, 'MIN'),
  72578. max: getImmediateChildByName(axisMesh, 'MAX')
  72579. };
  72580. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72581. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72582. }
  72583. else {
  72584. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72585. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72586. '(VALUE: ' + !!axisMeshInfo.value +
  72587. ', MIN: ' + !!axisMeshInfo.min +
  72588. ', MAX:' + !!axisMeshInfo.max +
  72589. ')');
  72590. }
  72591. }
  72592. // Pointing Ray
  72593. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72594. if (!loadedMeshInfo.pointingPoseNode) {
  72595. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72596. }
  72597. else {
  72598. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72599. }
  72600. return loadedMeshInfo;
  72601. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72602. function getChildByName(node, name) {
  72603. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72604. }
  72605. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72606. function getImmediateChildByName(node, name) {
  72607. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72608. }
  72609. };
  72610. /**
  72611. * Gets the ray of the controller in the direction the controller is pointing
  72612. * @param length the length the resulting ray should be
  72613. * @returns a ray in the direction the controller is pointing
  72614. */
  72615. WindowsMotionController.prototype.getForwardRay = function (length) {
  72616. if (length === void 0) { length = 100; }
  72617. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72618. return _super.prototype.getForwardRay.call(this, length);
  72619. }
  72620. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72621. var origin = m.getTranslation();
  72622. var forward = new BABYLON.Vector3(0, 0, -1);
  72623. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72624. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72625. return new BABYLON.Ray(origin, direction, length);
  72626. };
  72627. /**
  72628. * Disposes of the controller
  72629. */
  72630. WindowsMotionController.prototype.dispose = function () {
  72631. _super.prototype.dispose.call(this);
  72632. this.onTrackpadChangedObservable.clear();
  72633. };
  72634. /**
  72635. * The base url used to load the left and right controller models
  72636. */
  72637. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72638. /**
  72639. * The name of the left controller model file
  72640. */
  72641. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72642. /**
  72643. * The name of the right controller model file
  72644. */
  72645. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72646. /**
  72647. * The controller name prefix for this controller type
  72648. */
  72649. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72650. /**
  72651. * The controller id pattern for this controller type
  72652. */
  72653. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72654. return WindowsMotionController;
  72655. }(BABYLON.WebVRController));
  72656. BABYLON.WindowsMotionController = WindowsMotionController;
  72657. })(BABYLON || (BABYLON = {}));
  72658. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72659. var BABYLON;
  72660. (function (BABYLON) {
  72661. /**
  72662. * Gear VR Controller
  72663. */
  72664. var GearVRController = /** @class */ (function (_super) {
  72665. __extends(GearVRController, _super);
  72666. /**
  72667. * Creates a new GearVRController from a gamepad
  72668. * @param vrGamepad the gamepad that the controller should be created from
  72669. */
  72670. function GearVRController(vrGamepad) {
  72671. var _this = _super.call(this, vrGamepad) || this;
  72672. _this._buttonIndexToObservableNameMap = [
  72673. 'onTrackpadChangedObservable',
  72674. 'onTriggerStateChangedObservable' // Trigger
  72675. ];
  72676. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72677. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72678. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72679. return _this;
  72680. }
  72681. /**
  72682. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72683. * @param scene scene in which to add meshes
  72684. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72685. */
  72686. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72687. var _this = this;
  72688. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72689. _this._defaultModel = newMeshes[1];
  72690. _this.attachToMesh(_this._defaultModel);
  72691. if (meshLoaded) {
  72692. meshLoaded(_this._defaultModel);
  72693. }
  72694. });
  72695. };
  72696. /**
  72697. * Called once for each button that changed state since the last frame
  72698. * @param buttonIdx Which button index changed
  72699. * @param state New state of the button
  72700. * @param changes Which properties on the state changed since last frame
  72701. */
  72702. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72703. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72704. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72705. // Only emit events for buttons that we know how to map from index to observable
  72706. var observable = this[observableName];
  72707. if (observable) {
  72708. observable.notifyObservers(state);
  72709. }
  72710. }
  72711. };
  72712. /**
  72713. * Base Url for the controller model.
  72714. */
  72715. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72716. /**
  72717. * File name for the controller model.
  72718. */
  72719. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72720. /**
  72721. * Gamepad Id prefix used to identify this controller.
  72722. */
  72723. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72724. return GearVRController;
  72725. }(BABYLON.WebVRController));
  72726. BABYLON.GearVRController = GearVRController;
  72727. })(BABYLON || (BABYLON = {}));
  72728. //# sourceMappingURL=babylon.gearVRController.js.map
  72729. var BABYLON;
  72730. (function (BABYLON) {
  72731. /**
  72732. * Google Daydream controller
  72733. */
  72734. var DaydreamController = /** @class */ (function (_super) {
  72735. __extends(DaydreamController, _super);
  72736. /**
  72737. * Creates a new DaydreamController from a gamepad
  72738. * @param vrGamepad the gamepad that the controller should be created from
  72739. */
  72740. function DaydreamController(vrGamepad) {
  72741. var _this = _super.call(this, vrGamepad) || this;
  72742. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72743. return _this;
  72744. }
  72745. /**
  72746. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72747. * @param scene scene in which to add meshes
  72748. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72749. */
  72750. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72751. var _this = this;
  72752. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72753. _this._defaultModel = newMeshes[1];
  72754. _this.attachToMesh(_this._defaultModel);
  72755. if (meshLoaded) {
  72756. meshLoaded(_this._defaultModel);
  72757. }
  72758. });
  72759. };
  72760. /**
  72761. * Called once for each button that changed state since the last frame
  72762. * @param buttonIdx Which button index changed
  72763. * @param state New state of the button
  72764. * @param changes Which properties on the state changed since last frame
  72765. */
  72766. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72767. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72768. if (buttonIdx === 0) {
  72769. var observable = this.onTriggerStateChangedObservable;
  72770. if (observable) {
  72771. observable.notifyObservers(state);
  72772. }
  72773. }
  72774. else {
  72775. // If the app or home buttons are ever made available
  72776. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72777. }
  72778. };
  72779. /**
  72780. * Base Url for the controller model.
  72781. */
  72782. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72783. /**
  72784. * File name for the controller model.
  72785. */
  72786. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72787. /**
  72788. * Gamepad Id prefix used to identify Daydream Controller.
  72789. */
  72790. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72791. return DaydreamController;
  72792. }(BABYLON.WebVRController));
  72793. BABYLON.DaydreamController = DaydreamController;
  72794. })(BABYLON || (BABYLON = {}));
  72795. //# sourceMappingURL=babylon.daydreamController.js.map
  72796. var BABYLON;
  72797. (function (BABYLON) {
  72798. var FollowCamera = /** @class */ (function (_super) {
  72799. __extends(FollowCamera, _super);
  72800. function FollowCamera(name, position, scene, lockedTarget) {
  72801. if (lockedTarget === void 0) { lockedTarget = null; }
  72802. var _this = _super.call(this, name, position, scene) || this;
  72803. _this.radius = 12;
  72804. _this.rotationOffset = 0;
  72805. _this.heightOffset = 4;
  72806. _this.cameraAcceleration = 0.05;
  72807. _this.maxCameraSpeed = 20;
  72808. _this.lockedTarget = lockedTarget;
  72809. return _this;
  72810. }
  72811. FollowCamera.prototype.getRadians = function (degrees) {
  72812. return degrees * Math.PI / 180;
  72813. };
  72814. FollowCamera.prototype.follow = function (cameraTarget) {
  72815. if (!cameraTarget)
  72816. return;
  72817. var yRotation;
  72818. if (cameraTarget.rotationQuaternion) {
  72819. var rotMatrix = new BABYLON.Matrix();
  72820. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72821. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72822. }
  72823. else {
  72824. yRotation = cameraTarget.rotation.y;
  72825. }
  72826. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72827. var targetPosition = cameraTarget.getAbsolutePosition();
  72828. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72829. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72830. var dx = targetX - this.position.x;
  72831. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72832. var dz = (targetZ) - this.position.z;
  72833. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72834. var vy = dy * this.cameraAcceleration;
  72835. var vz = dz * this.cameraAcceleration * 2;
  72836. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72837. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72838. }
  72839. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72840. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72841. }
  72842. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72843. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72844. }
  72845. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72846. this.setTarget(targetPosition);
  72847. };
  72848. FollowCamera.prototype._checkInputs = function () {
  72849. _super.prototype._checkInputs.call(this);
  72850. if (this.lockedTarget) {
  72851. this.follow(this.lockedTarget);
  72852. }
  72853. };
  72854. FollowCamera.prototype.getClassName = function () {
  72855. return "FollowCamera";
  72856. };
  72857. __decorate([
  72858. BABYLON.serialize()
  72859. ], FollowCamera.prototype, "radius", void 0);
  72860. __decorate([
  72861. BABYLON.serialize()
  72862. ], FollowCamera.prototype, "rotationOffset", void 0);
  72863. __decorate([
  72864. BABYLON.serialize()
  72865. ], FollowCamera.prototype, "heightOffset", void 0);
  72866. __decorate([
  72867. BABYLON.serialize()
  72868. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72869. __decorate([
  72870. BABYLON.serialize()
  72871. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72872. __decorate([
  72873. BABYLON.serializeAsMeshReference("lockedTargetId")
  72874. ], FollowCamera.prototype, "lockedTarget", void 0);
  72875. return FollowCamera;
  72876. }(BABYLON.TargetCamera));
  72877. BABYLON.FollowCamera = FollowCamera;
  72878. var ArcFollowCamera = /** @class */ (function (_super) {
  72879. __extends(ArcFollowCamera, _super);
  72880. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72881. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72882. _this.alpha = alpha;
  72883. _this.beta = beta;
  72884. _this.radius = radius;
  72885. _this.target = target;
  72886. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72887. _this.follow();
  72888. return _this;
  72889. }
  72890. ArcFollowCamera.prototype.follow = function () {
  72891. if (!this.target) {
  72892. return;
  72893. }
  72894. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72895. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72896. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72897. var targetPosition = this.target.getAbsolutePosition();
  72898. this.position = targetPosition.add(this._cartesianCoordinates);
  72899. this.setTarget(targetPosition);
  72900. };
  72901. ArcFollowCamera.prototype._checkInputs = function () {
  72902. _super.prototype._checkInputs.call(this);
  72903. this.follow();
  72904. };
  72905. ArcFollowCamera.prototype.getClassName = function () {
  72906. return "ArcFollowCamera";
  72907. };
  72908. return ArcFollowCamera;
  72909. }(BABYLON.TargetCamera));
  72910. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72911. })(BABYLON || (BABYLON = {}));
  72912. //# sourceMappingURL=babylon.followCamera.js.map
  72913. var BABYLON;
  72914. (function (BABYLON) {
  72915. // We're mainly based on the logic defined into the FreeCamera code
  72916. var UniversalCamera = /** @class */ (function (_super) {
  72917. __extends(UniversalCamera, _super);
  72918. //-- end properties for backward compatibility for inputs
  72919. function UniversalCamera(name, position, scene) {
  72920. var _this = _super.call(this, name, position, scene) || this;
  72921. _this.inputs.addGamepad();
  72922. return _this;
  72923. }
  72924. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72925. //-- Begin properties for backward compatibility for inputs
  72926. get: function () {
  72927. var gamepad = this.inputs.attached["gamepad"];
  72928. if (gamepad)
  72929. return gamepad.gamepadAngularSensibility;
  72930. return 0;
  72931. },
  72932. set: function (value) {
  72933. var gamepad = this.inputs.attached["gamepad"];
  72934. if (gamepad)
  72935. gamepad.gamepadAngularSensibility = value;
  72936. },
  72937. enumerable: true,
  72938. configurable: true
  72939. });
  72940. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72941. get: function () {
  72942. var gamepad = this.inputs.attached["gamepad"];
  72943. if (gamepad)
  72944. return gamepad.gamepadMoveSensibility;
  72945. return 0;
  72946. },
  72947. set: function (value) {
  72948. var gamepad = this.inputs.attached["gamepad"];
  72949. if (gamepad)
  72950. gamepad.gamepadMoveSensibility = value;
  72951. },
  72952. enumerable: true,
  72953. configurable: true
  72954. });
  72955. UniversalCamera.prototype.getClassName = function () {
  72956. return "UniversalCamera";
  72957. };
  72958. return UniversalCamera;
  72959. }(BABYLON.TouchCamera));
  72960. BABYLON.UniversalCamera = UniversalCamera;
  72961. })(BABYLON || (BABYLON = {}));
  72962. //# sourceMappingURL=babylon.universalCamera.js.map
  72963. var BABYLON;
  72964. (function (BABYLON) {
  72965. // We're mainly based on the logic defined into the FreeCamera code
  72966. var GamepadCamera = /** @class */ (function (_super) {
  72967. __extends(GamepadCamera, _super);
  72968. //-- end properties for backward compatibility for inputs
  72969. function GamepadCamera(name, position, scene) {
  72970. return _super.call(this, name, position, scene) || this;
  72971. }
  72972. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72973. //-- Begin properties for backward compatibility for inputs
  72974. get: function () {
  72975. var gamepad = this.inputs.attached["gamepad"];
  72976. if (gamepad)
  72977. return gamepad.gamepadAngularSensibility;
  72978. return 0;
  72979. },
  72980. set: function (value) {
  72981. var gamepad = this.inputs.attached["gamepad"];
  72982. if (gamepad)
  72983. gamepad.gamepadAngularSensibility = value;
  72984. },
  72985. enumerable: true,
  72986. configurable: true
  72987. });
  72988. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72989. get: function () {
  72990. var gamepad = this.inputs.attached["gamepad"];
  72991. if (gamepad)
  72992. return gamepad.gamepadMoveSensibility;
  72993. return 0;
  72994. },
  72995. set: function (value) {
  72996. var gamepad = this.inputs.attached["gamepad"];
  72997. if (gamepad)
  72998. gamepad.gamepadMoveSensibility = value;
  72999. },
  73000. enumerable: true,
  73001. configurable: true
  73002. });
  73003. GamepadCamera.prototype.getClassName = function () {
  73004. return "GamepadCamera";
  73005. };
  73006. return GamepadCamera;
  73007. }(BABYLON.UniversalCamera));
  73008. BABYLON.GamepadCamera = GamepadCamera;
  73009. })(BABYLON || (BABYLON = {}));
  73010. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73011. var BABYLON;
  73012. (function (BABYLON) {
  73013. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73014. function PostProcessRenderPipelineManager() {
  73015. this._renderPipelines = {};
  73016. }
  73017. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73018. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73019. };
  73020. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73021. if (unique === void 0) { unique = false; }
  73022. var renderPipeline = this._renderPipelines[renderPipelineName];
  73023. if (!renderPipeline) {
  73024. return;
  73025. }
  73026. renderPipeline._attachCameras(cameras, unique);
  73027. };
  73028. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73029. var renderPipeline = this._renderPipelines[renderPipelineName];
  73030. if (!renderPipeline) {
  73031. return;
  73032. }
  73033. renderPipeline._detachCameras(cameras);
  73034. };
  73035. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73036. var renderPipeline = this._renderPipelines[renderPipelineName];
  73037. if (!renderPipeline) {
  73038. return;
  73039. }
  73040. renderPipeline._enableEffect(renderEffectName, cameras);
  73041. };
  73042. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73043. var renderPipeline = this._renderPipelines[renderPipelineName];
  73044. if (!renderPipeline) {
  73045. return;
  73046. }
  73047. renderPipeline._disableEffect(renderEffectName, cameras);
  73048. };
  73049. PostProcessRenderPipelineManager.prototype.update = function () {
  73050. for (var renderPipelineName in this._renderPipelines) {
  73051. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73052. var pipeline = this._renderPipelines[renderPipelineName];
  73053. if (!pipeline.isSupported) {
  73054. pipeline.dispose();
  73055. delete this._renderPipelines[renderPipelineName];
  73056. }
  73057. else {
  73058. pipeline._update();
  73059. }
  73060. }
  73061. }
  73062. };
  73063. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73064. for (var renderPipelineName in this._renderPipelines) {
  73065. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73066. var pipeline = this._renderPipelines[renderPipelineName];
  73067. pipeline._rebuild();
  73068. }
  73069. }
  73070. };
  73071. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73072. for (var renderPipelineName in this._renderPipelines) {
  73073. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73074. var pipeline = this._renderPipelines[renderPipelineName];
  73075. pipeline.dispose();
  73076. }
  73077. }
  73078. };
  73079. return PostProcessRenderPipelineManager;
  73080. }());
  73081. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73082. })(BABYLON || (BABYLON = {}));
  73083. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73084. var BABYLON;
  73085. (function (BABYLON) {
  73086. /**
  73087. * This represents a set of one or more post processes in Babylon.
  73088. * A post process can be used to apply a shader to a texture after it is rendered.
  73089. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73090. */
  73091. var PostProcessRenderEffect = /** @class */ (function () {
  73092. /**
  73093. * Instantiates a post process render effect.
  73094. * A post process can be used to apply a shader to a texture after it is rendered.
  73095. * @param engine The engine the effect is tied to
  73096. * @param name The name of the effect
  73097. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73098. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73099. */
  73100. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73101. this._name = name;
  73102. this._singleInstance = singleInstance || true;
  73103. this._getPostProcesses = getPostProcesses;
  73104. this._cameras = {};
  73105. this._indicesForCamera = {};
  73106. this._postProcesses = {};
  73107. }
  73108. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73109. /**
  73110. * Checks if all the post processes in the effect are supported.
  73111. */
  73112. get: function () {
  73113. for (var index in this._postProcesses) {
  73114. if (this._postProcesses.hasOwnProperty(index)) {
  73115. var pps = this._postProcesses[index];
  73116. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73117. if (!pps[ppIndex].isSupported) {
  73118. return false;
  73119. }
  73120. }
  73121. }
  73122. }
  73123. return true;
  73124. },
  73125. enumerable: true,
  73126. configurable: true
  73127. });
  73128. /**
  73129. * Updates the current state of the effect
  73130. */
  73131. PostProcessRenderEffect.prototype._update = function () {
  73132. };
  73133. /**
  73134. * Attaches the effect on cameras
  73135. * @param cameras The camera to attach to.
  73136. */
  73137. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73138. var _this = this;
  73139. var cameraKey;
  73140. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73141. if (!cams) {
  73142. return;
  73143. }
  73144. for (var i = 0; i < cams.length; i++) {
  73145. var camera = cams[i];
  73146. var cameraName = camera.name;
  73147. if (this._singleInstance) {
  73148. cameraKey = 0;
  73149. }
  73150. else {
  73151. cameraKey = cameraName;
  73152. }
  73153. if (!this._postProcesses[cameraKey]) {
  73154. var postProcess = this._getPostProcesses();
  73155. if (postProcess) {
  73156. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73157. }
  73158. }
  73159. if (!this._indicesForCamera[cameraName]) {
  73160. this._indicesForCamera[cameraName] = [];
  73161. }
  73162. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73163. var index = camera.attachPostProcess(postProcess);
  73164. _this._indicesForCamera[cameraName].push(index);
  73165. });
  73166. if (!this._cameras[cameraName]) {
  73167. this._cameras[cameraName] = camera;
  73168. }
  73169. }
  73170. };
  73171. /**
  73172. * Detatches the effect on cameras
  73173. * @param cameras The camera to detatch from.
  73174. */
  73175. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73176. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73177. if (!cams) {
  73178. return;
  73179. }
  73180. for (var i = 0; i < cams.length; i++) {
  73181. var camera = cams[i];
  73182. var cameraName = camera.name;
  73183. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73184. camera.detachPostProcess(postProcess);
  73185. });
  73186. if (this._cameras[cameraName]) {
  73187. //this._indicesForCamera.splice(index, 1);
  73188. this._cameras[cameraName] = null;
  73189. }
  73190. }
  73191. };
  73192. /**
  73193. * Enables the effect on given cameras
  73194. * @param cameras The camera to enable.
  73195. */
  73196. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73197. var _this = this;
  73198. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73199. if (!cams) {
  73200. return;
  73201. }
  73202. for (var i = 0; i < cams.length; i++) {
  73203. var camera = cams[i];
  73204. var cameraName = camera.name;
  73205. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73206. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73207. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73208. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73209. });
  73210. }
  73211. }
  73212. }
  73213. };
  73214. /**
  73215. * Disables the effect on the given cameras
  73216. * @param cameras The camera to disable.
  73217. */
  73218. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73219. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73220. if (!cams) {
  73221. return;
  73222. }
  73223. for (var i = 0; i < cams.length; i++) {
  73224. var camera = cams[i];
  73225. var cameraName = camera.name;
  73226. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73227. camera.detachPostProcess(postProcess);
  73228. });
  73229. }
  73230. };
  73231. /**
  73232. * Gets a list of the post processes contained in the effect.
  73233. * @param camera The camera to get the post processes on.
  73234. * @returns The list of the post processes in the effect.
  73235. */
  73236. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73237. if (this._singleInstance) {
  73238. return this._postProcesses[0];
  73239. }
  73240. else {
  73241. if (!camera) {
  73242. return null;
  73243. }
  73244. return this._postProcesses[camera.name];
  73245. }
  73246. };
  73247. return PostProcessRenderEffect;
  73248. }());
  73249. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73250. })(BABYLON || (BABYLON = {}));
  73251. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73252. var BABYLON;
  73253. (function (BABYLON) {
  73254. var PostProcessRenderPipeline = /** @class */ (function () {
  73255. function PostProcessRenderPipeline(engine, name) {
  73256. this.engine = engine;
  73257. this._name = name;
  73258. this._renderEffects = {};
  73259. this._renderEffectsForIsolatedPass = new Array();
  73260. this._cameras = [];
  73261. }
  73262. PostProcessRenderPipeline.prototype.getClassName = function () {
  73263. return "PostProcessRenderPipeline";
  73264. };
  73265. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73266. get: function () {
  73267. for (var renderEffectName in this._renderEffects) {
  73268. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73269. if (!this._renderEffects[renderEffectName].isSupported) {
  73270. return false;
  73271. }
  73272. }
  73273. }
  73274. return true;
  73275. },
  73276. enumerable: true,
  73277. configurable: true
  73278. });
  73279. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73280. this._renderEffects[renderEffect._name] = renderEffect;
  73281. };
  73282. // private
  73283. PostProcessRenderPipeline.prototype._rebuild = function () {
  73284. };
  73285. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73286. var renderEffects = this._renderEffects[renderEffectName];
  73287. if (!renderEffects) {
  73288. return;
  73289. }
  73290. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73291. };
  73292. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73293. var renderEffects = this._renderEffects[renderEffectName];
  73294. if (!renderEffects) {
  73295. return;
  73296. }
  73297. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73298. };
  73299. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73300. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73301. if (!cams) {
  73302. return;
  73303. }
  73304. var indicesToDelete = [];
  73305. var i;
  73306. for (i = 0; i < cams.length; i++) {
  73307. var camera = cams[i];
  73308. var cameraName = camera.name;
  73309. if (this._cameras.indexOf(camera) === -1) {
  73310. this._cameras[cameraName] = camera;
  73311. }
  73312. else if (unique) {
  73313. indicesToDelete.push(i);
  73314. }
  73315. }
  73316. for (i = 0; i < indicesToDelete.length; i++) {
  73317. cameras.splice(indicesToDelete[i], 1);
  73318. }
  73319. for (var renderEffectName in this._renderEffects) {
  73320. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73321. this._renderEffects[renderEffectName]._attachCameras(cams);
  73322. }
  73323. }
  73324. };
  73325. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73326. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73327. if (!cams) {
  73328. return;
  73329. }
  73330. for (var renderEffectName in this._renderEffects) {
  73331. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73332. this._renderEffects[renderEffectName]._detachCameras(cams);
  73333. }
  73334. }
  73335. for (var i = 0; i < cams.length; i++) {
  73336. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73337. }
  73338. };
  73339. PostProcessRenderPipeline.prototype._update = function () {
  73340. for (var renderEffectName in this._renderEffects) {
  73341. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73342. this._renderEffects[renderEffectName]._update();
  73343. }
  73344. }
  73345. for (var i = 0; i < this._cameras.length; i++) {
  73346. var cameraName = this._cameras[i].name;
  73347. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73348. this._renderEffectsForIsolatedPass[cameraName]._update();
  73349. }
  73350. }
  73351. };
  73352. PostProcessRenderPipeline.prototype._reset = function () {
  73353. this._renderEffects = {};
  73354. this._renderEffectsForIsolatedPass = new Array();
  73355. };
  73356. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73357. // 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)
  73358. var effectKeys = Object.keys(this._renderEffects);
  73359. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73360. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73361. if (postProcesses) {
  73362. postProcesses[0].samples = sampleCount;
  73363. return true;
  73364. }
  73365. }
  73366. return false;
  73367. };
  73368. PostProcessRenderPipeline.prototype.dispose = function () {
  73369. // Must be implemented by children
  73370. };
  73371. __decorate([
  73372. BABYLON.serialize()
  73373. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73374. return PostProcessRenderPipeline;
  73375. }());
  73376. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73377. })(BABYLON || (BABYLON = {}));
  73378. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73379. var BABYLON;
  73380. (function (BABYLON) {
  73381. /**
  73382. * This represents a depth renderer in Babylon.
  73383. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73384. */
  73385. var DepthRenderer = /** @class */ (function () {
  73386. /**
  73387. * Instantiates a depth renderer
  73388. * @param scene The scene the renderer belongs to
  73389. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73390. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73391. */
  73392. function DepthRenderer(scene, type, camera) {
  73393. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73394. if (camera === void 0) { camera = null; }
  73395. var _this = this;
  73396. this._scene = scene;
  73397. this._camera = camera;
  73398. var engine = scene.getEngine();
  73399. // Render target
  73400. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73401. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73402. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73403. this._depthMap.refreshRate = 1;
  73404. this._depthMap.renderParticles = false;
  73405. this._depthMap.renderList = null;
  73406. // Camera to get depth map from to support multiple concurrent cameras
  73407. this._depthMap.activeCamera = this._camera;
  73408. this._depthMap.ignoreCameraViewport = true;
  73409. this._depthMap.useCameraPostProcesses = false;
  73410. // set default depth value to 1.0 (far away)
  73411. this._depthMap.onClearObservable.add(function (engine) {
  73412. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73413. });
  73414. // Custom render function
  73415. var renderSubMesh = function (subMesh) {
  73416. var mesh = subMesh.getRenderingMesh();
  73417. var scene = _this._scene;
  73418. var engine = scene.getEngine();
  73419. var material = subMesh.getMaterial();
  73420. if (!material) {
  73421. return;
  73422. }
  73423. // Culling and reverse (right handed system)
  73424. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73425. // Managing instances
  73426. var batch = mesh._getInstancesRenderList(subMesh._id);
  73427. if (batch.mustReturn) {
  73428. return;
  73429. }
  73430. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73431. var camera = _this._camera || scene.activeCamera;
  73432. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73433. engine.enableEffect(_this._effect);
  73434. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73435. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73436. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73437. // Alpha test
  73438. if (material && material.needAlphaTesting()) {
  73439. var alphaTexture = material.getAlphaTestTexture();
  73440. if (alphaTexture) {
  73441. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73442. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73443. }
  73444. }
  73445. // Bones
  73446. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73447. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73448. }
  73449. // Draw
  73450. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73451. }
  73452. };
  73453. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73454. var index;
  73455. if (depthOnlySubMeshes.length) {
  73456. engine.setColorWrite(false);
  73457. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73458. renderSubMesh(depthOnlySubMeshes.data[index]);
  73459. }
  73460. engine.setColorWrite(true);
  73461. }
  73462. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73463. renderSubMesh(opaqueSubMeshes.data[index]);
  73464. }
  73465. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73466. renderSubMesh(alphaTestSubMeshes.data[index]);
  73467. }
  73468. };
  73469. }
  73470. /**
  73471. * Creates the depth rendering effect and checks if the effect is ready.
  73472. * @param subMesh The submesh to be used to render the depth map of
  73473. * @param useInstances If multiple world instances should be used
  73474. * @returns if the depth renderer is ready to render the depth map
  73475. */
  73476. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73477. var material = subMesh.getMaterial();
  73478. if (material.disableDepthWrite) {
  73479. return false;
  73480. }
  73481. var defines = [];
  73482. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73483. var mesh = subMesh.getMesh();
  73484. // Alpha test
  73485. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73486. defines.push("#define ALPHATEST");
  73487. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73488. attribs.push(BABYLON.VertexBuffer.UVKind);
  73489. defines.push("#define UV1");
  73490. }
  73491. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73492. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73493. defines.push("#define UV2");
  73494. }
  73495. }
  73496. // Bones
  73497. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73498. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73499. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73500. if (mesh.numBoneInfluencers > 4) {
  73501. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73502. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73503. }
  73504. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73505. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73506. }
  73507. else {
  73508. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73509. }
  73510. // Instances
  73511. if (useInstances) {
  73512. defines.push("#define INSTANCES");
  73513. attribs.push("world0");
  73514. attribs.push("world1");
  73515. attribs.push("world2");
  73516. attribs.push("world3");
  73517. }
  73518. // Get correct effect
  73519. var join = defines.join("\n");
  73520. if (this._cachedDefines !== join) {
  73521. this._cachedDefines = join;
  73522. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73523. }
  73524. return this._effect.isReady();
  73525. };
  73526. /**
  73527. * Gets the texture which the depth map will be written to.
  73528. * @returns The depth map texture
  73529. */
  73530. DepthRenderer.prototype.getDepthMap = function () {
  73531. return this._depthMap;
  73532. };
  73533. /**
  73534. * Disposes of the depth renderer.
  73535. */
  73536. DepthRenderer.prototype.dispose = function () {
  73537. this._depthMap.dispose();
  73538. };
  73539. return DepthRenderer;
  73540. }());
  73541. BABYLON.DepthRenderer = DepthRenderer;
  73542. })(BABYLON || (BABYLON = {}));
  73543. //# sourceMappingURL=babylon.depthRenderer.js.map
  73544. var BABYLON;
  73545. (function (BABYLON) {
  73546. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73547. __extends(SSAORenderingPipeline, _super);
  73548. /**
  73549. * @constructor
  73550. * @param {string} name - The rendering pipeline name
  73551. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73552. * @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 }
  73553. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73554. */
  73555. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73556. var _this = _super.call(this, scene.getEngine(), name) || this;
  73557. // Members
  73558. /**
  73559. * The PassPostProcess id in the pipeline that contains the original scene color
  73560. */
  73561. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73562. /**
  73563. * The SSAO PostProcess id in the pipeline
  73564. */
  73565. _this.SSAORenderEffect = "SSAORenderEffect";
  73566. /**
  73567. * The horizontal blur PostProcess id in the pipeline
  73568. */
  73569. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73570. /**
  73571. * The vertical blur PostProcess id in the pipeline
  73572. */
  73573. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73574. /**
  73575. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73576. */
  73577. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73578. /**
  73579. * The output strength of the SSAO post-process. Default value is 1.0.
  73580. */
  73581. _this.totalStrength = 1.0;
  73582. /**
  73583. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73584. */
  73585. _this.radius = 0.0001;
  73586. /**
  73587. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73588. * Must not be equal to fallOff and superior to fallOff.
  73589. * Default value is 0.975
  73590. */
  73591. _this.area = 0.0075;
  73592. /**
  73593. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73594. * Must not be equal to area and inferior to area.
  73595. * Default value is 0.0
  73596. */
  73597. _this.fallOff = 0.000001;
  73598. /**
  73599. * The base color of the SSAO post-process
  73600. * The final result is "base + ssao" between [0, 1]
  73601. */
  73602. _this.base = 0.5;
  73603. _this._firstUpdate = true;
  73604. _this._scene = scene;
  73605. // Set up assets
  73606. _this._createRandomTexture();
  73607. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73608. var ssaoRatio = ratio.ssaoRatio || ratio;
  73609. var combineRatio = ratio.combineRatio || ratio;
  73610. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73611. _this._createSSAOPostProcess(ssaoRatio);
  73612. _this._createBlurPostProcess(ssaoRatio);
  73613. _this._createSSAOCombinePostProcess(combineRatio);
  73614. // Set up pipeline
  73615. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73616. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73617. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73618. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73619. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73620. // Finish
  73621. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73622. if (cameras)
  73623. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73624. return _this;
  73625. }
  73626. // Public Methods
  73627. /**
  73628. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73629. */
  73630. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73631. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73632. for (var i = 0; i < this._scene.cameras.length; i++) {
  73633. var camera = this._scene.cameras[i];
  73634. this._originalColorPostProcess.dispose(camera);
  73635. this._ssaoPostProcess.dispose(camera);
  73636. this._blurHPostProcess.dispose(camera);
  73637. this._blurVPostProcess.dispose(camera);
  73638. this._ssaoCombinePostProcess.dispose(camera);
  73639. }
  73640. this._randomTexture.dispose();
  73641. if (disableDepthRender)
  73642. this._scene.disableDepthRenderer();
  73643. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73644. _super.prototype.dispose.call(this);
  73645. };
  73646. // Private Methods
  73647. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73648. var _this = this;
  73649. var size = 16;
  73650. 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);
  73651. 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);
  73652. this._blurHPostProcess.onActivateObservable.add(function () {
  73653. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73654. _this._blurHPostProcess.kernel = size * dw;
  73655. });
  73656. this._blurVPostProcess.onActivateObservable.add(function () {
  73657. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73658. _this._blurVPostProcess.kernel = size * dw;
  73659. });
  73660. };
  73661. SSAORenderingPipeline.prototype._rebuild = function () {
  73662. this._firstUpdate = true;
  73663. _super.prototype._rebuild.call(this);
  73664. };
  73665. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73666. var _this = this;
  73667. var numSamples = 16;
  73668. var sampleSphere = [
  73669. 0.5381, 0.1856, -0.4319,
  73670. 0.1379, 0.2486, 0.4430,
  73671. 0.3371, 0.5679, -0.0057,
  73672. -0.6999, -0.0451, -0.0019,
  73673. 0.0689, -0.1598, -0.8547,
  73674. 0.0560, 0.0069, -0.1843,
  73675. -0.0146, 0.1402, 0.0762,
  73676. 0.0100, -0.1924, -0.0344,
  73677. -0.3577, -0.5301, -0.4358,
  73678. -0.3169, 0.1063, 0.0158,
  73679. 0.0103, -0.5869, 0.0046,
  73680. -0.0897, -0.4940, 0.3287,
  73681. 0.7119, -0.0154, -0.0918,
  73682. -0.0533, 0.0596, -0.5411,
  73683. 0.0352, -0.0631, 0.5460,
  73684. -0.4776, 0.2847, -0.0271
  73685. ];
  73686. var samplesFactor = 1.0 / numSamples;
  73687. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73688. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73689. "area", "fallOff", "base", "range", "viewport"
  73690. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73691. this._ssaoPostProcess.onApply = function (effect) {
  73692. if (_this._firstUpdate) {
  73693. effect.setArray3("sampleSphere", sampleSphere);
  73694. effect.setFloat("samplesFactor", samplesFactor);
  73695. effect.setFloat("randTextureTiles", 4.0);
  73696. }
  73697. effect.setFloat("totalStrength", _this.totalStrength);
  73698. effect.setFloat("radius", _this.radius);
  73699. effect.setFloat("area", _this.area);
  73700. effect.setFloat("fallOff", _this.fallOff);
  73701. effect.setFloat("base", _this.base);
  73702. effect.setTexture("textureSampler", _this._depthTexture);
  73703. effect.setTexture("randomSampler", _this._randomTexture);
  73704. };
  73705. };
  73706. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73707. var _this = this;
  73708. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73709. this._ssaoCombinePostProcess.onApply = function (effect) {
  73710. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73711. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73712. };
  73713. };
  73714. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73715. var size = 512;
  73716. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73717. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73718. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73719. var context = this._randomTexture.getContext();
  73720. var rand = function (min, max) {
  73721. return Math.random() * (max - min) + min;
  73722. };
  73723. var randVector = BABYLON.Vector3.Zero();
  73724. for (var x = 0; x < size; x++) {
  73725. for (var y = 0; y < size; y++) {
  73726. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73727. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73728. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73729. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73730. context.fillRect(x, y, 1, 1);
  73731. }
  73732. }
  73733. this._randomTexture.update(false);
  73734. };
  73735. __decorate([
  73736. BABYLON.serialize()
  73737. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73738. __decorate([
  73739. BABYLON.serialize()
  73740. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73741. __decorate([
  73742. BABYLON.serialize()
  73743. ], SSAORenderingPipeline.prototype, "area", void 0);
  73744. __decorate([
  73745. BABYLON.serialize()
  73746. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73747. __decorate([
  73748. BABYLON.serialize()
  73749. ], SSAORenderingPipeline.prototype, "base", void 0);
  73750. return SSAORenderingPipeline;
  73751. }(BABYLON.PostProcessRenderPipeline));
  73752. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73753. })(BABYLON || (BABYLON = {}));
  73754. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73755. var BABYLON;
  73756. (function (BABYLON) {
  73757. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73758. __extends(SSAO2RenderingPipeline, _super);
  73759. /**
  73760. * @constructor
  73761. * @param {string} name - The rendering pipeline name
  73762. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73763. * @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 }
  73764. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73765. */
  73766. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73767. var _this = _super.call(this, scene.getEngine(), name) || this;
  73768. // Members
  73769. /**
  73770. * The PassPostProcess id in the pipeline that contains the original scene color
  73771. */
  73772. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73773. /**
  73774. * The SSAO PostProcess id in the pipeline
  73775. */
  73776. _this.SSAORenderEffect = "SSAORenderEffect";
  73777. /**
  73778. * The horizontal blur PostProcess id in the pipeline
  73779. */
  73780. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73781. /**
  73782. * The vertical blur PostProcess id in the pipeline
  73783. */
  73784. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73785. /**
  73786. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73787. */
  73788. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73789. /**
  73790. * The output strength of the SSAO post-process. Default value is 1.0.
  73791. */
  73792. _this.totalStrength = 1.0;
  73793. /**
  73794. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73795. */
  73796. _this.maxZ = 100.0;
  73797. /**
  73798. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73799. */
  73800. _this.minZAspect = 0.2;
  73801. /**
  73802. * Number of samples used for the SSAO calculations. Default value is 8
  73803. */
  73804. _this._samples = 8;
  73805. /**
  73806. * Are we using bilateral blur ?
  73807. */
  73808. _this._expensiveBlur = true;
  73809. /**
  73810. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73811. */
  73812. _this.radius = 2.0;
  73813. /**
  73814. * The base color of the SSAO post-process
  73815. * The final result is "base + ssao" between [0, 1]
  73816. */
  73817. _this.base = 0.1;
  73818. _this._firstUpdate = true;
  73819. _this._scene = scene;
  73820. _this._ratio = ratio;
  73821. if (!_this.isSupported) {
  73822. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73823. return _this;
  73824. }
  73825. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73826. var blurRatio = _this._ratio.blurRatio || ratio;
  73827. // Set up assets
  73828. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73829. _this._createRandomTexture();
  73830. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73831. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73832. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73833. _this._createSSAOPostProcess(1.0);
  73834. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73835. _this._createSSAOCombinePostProcess(blurRatio);
  73836. // Set up pipeline
  73837. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73838. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73839. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73840. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73841. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73842. // Finish
  73843. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73844. if (cameras)
  73845. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73846. return _this;
  73847. }
  73848. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73849. get: function () {
  73850. return this._samples;
  73851. },
  73852. set: function (n) {
  73853. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73854. this._samples = n;
  73855. this._sampleSphere = this._generateHemisphere();
  73856. this._firstUpdate = true;
  73857. },
  73858. enumerable: true,
  73859. configurable: true
  73860. });
  73861. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73862. get: function () {
  73863. return this._expensiveBlur;
  73864. },
  73865. set: function (b) {
  73866. 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"]);
  73867. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73868. this._expensiveBlur = b;
  73869. this._firstUpdate = true;
  73870. },
  73871. enumerable: true,
  73872. configurable: true
  73873. });
  73874. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73875. /**
  73876. * Support test.
  73877. */
  73878. get: function () {
  73879. var engine = BABYLON.Engine.LastCreatedEngine;
  73880. if (!engine) {
  73881. return false;
  73882. }
  73883. return engine.getCaps().drawBuffersExtension;
  73884. },
  73885. enumerable: true,
  73886. configurable: true
  73887. });
  73888. // Public Methods
  73889. /**
  73890. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73891. */
  73892. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73893. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73894. for (var i = 0; i < this._scene.cameras.length; i++) {
  73895. var camera = this._scene.cameras[i];
  73896. this._originalColorPostProcess.dispose(camera);
  73897. this._ssaoPostProcess.dispose(camera);
  73898. this._blurHPostProcess.dispose(camera);
  73899. this._blurVPostProcess.dispose(camera);
  73900. this._ssaoCombinePostProcess.dispose(camera);
  73901. }
  73902. this._randomTexture.dispose();
  73903. if (disableGeometryBufferRenderer)
  73904. this._scene.disableGeometryBufferRenderer();
  73905. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73906. _super.prototype.dispose.call(this);
  73907. };
  73908. // Private Methods
  73909. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73910. var _this = this;
  73911. this._samplerOffsets = [];
  73912. var expensive = this.expensiveBlur;
  73913. for (var i = -8; i < 8; i++) {
  73914. this._samplerOffsets.push(i * 2 + 0.5);
  73915. }
  73916. 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");
  73917. this._blurHPostProcess.onApply = function (effect) {
  73918. if (!_this._scene.activeCamera) {
  73919. return;
  73920. }
  73921. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73922. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73923. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73924. effect.setFloat("radius", _this.radius);
  73925. effect.setTexture("depthSampler", _this._depthTexture);
  73926. if (_this._firstUpdate) {
  73927. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73928. }
  73929. };
  73930. 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");
  73931. this._blurVPostProcess.onApply = function (effect) {
  73932. if (!_this._scene.activeCamera) {
  73933. return;
  73934. }
  73935. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73936. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73937. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73938. effect.setFloat("radius", _this.radius);
  73939. effect.setTexture("depthSampler", _this._depthTexture);
  73940. if (_this._firstUpdate) {
  73941. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73942. _this._firstUpdate = false;
  73943. }
  73944. };
  73945. };
  73946. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73947. this._firstUpdate = true;
  73948. _super.prototype._rebuild.call(this);
  73949. };
  73950. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73951. var numSamples = this.samples;
  73952. var result = [];
  73953. var vector, scale;
  73954. var rand = function (min, max) {
  73955. return Math.random() * (max - min) + min;
  73956. };
  73957. var i = 0;
  73958. while (i < numSamples) {
  73959. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73960. vector.normalize();
  73961. scale = i / numSamples;
  73962. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73963. vector.scaleInPlace(scale);
  73964. result.push(vector.x, vector.y, vector.z);
  73965. i++;
  73966. }
  73967. return result;
  73968. };
  73969. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73970. var _this = this;
  73971. var numSamples = this.samples;
  73972. this._sampleSphere = this._generateHemisphere();
  73973. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73974. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73975. "base", "range", "projection", "near", "far", "texelSize",
  73976. "xViewport", "yViewport", "maxZ", "minZAspect"
  73977. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73978. this._ssaoPostProcess.onApply = function (effect) {
  73979. if (_this._firstUpdate) {
  73980. effect.setArray3("sampleSphere", _this._sampleSphere);
  73981. effect.setFloat("randTextureTiles", 4.0);
  73982. }
  73983. if (!_this._scene.activeCamera) {
  73984. return;
  73985. }
  73986. effect.setFloat("samplesFactor", 1 / _this.samples);
  73987. effect.setFloat("totalStrength", _this.totalStrength);
  73988. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73989. effect.setFloat("radius", _this.radius);
  73990. effect.setFloat("maxZ", _this.maxZ);
  73991. effect.setFloat("minZAspect", _this.minZAspect);
  73992. effect.setFloat("base", _this.base);
  73993. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73994. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73995. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73996. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73997. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73998. effect.setTexture("textureSampler", _this._depthTexture);
  73999. effect.setTexture("normalSampler", _this._normalTexture);
  74000. effect.setTexture("randomSampler", _this._randomTexture);
  74001. };
  74002. };
  74003. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74004. var _this = this;
  74005. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74006. this._ssaoCombinePostProcess.onApply = function (effect) {
  74007. var viewport = _this._scene.activeCamera.viewport;
  74008. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74009. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74010. };
  74011. };
  74012. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74013. var size = 512;
  74014. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74015. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74016. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74017. var context = this._randomTexture.getContext();
  74018. var rand = function (min, max) {
  74019. return Math.random() * (max - min) + min;
  74020. };
  74021. var randVector = BABYLON.Vector3.Zero();
  74022. for (var x = 0; x < size; x++) {
  74023. for (var y = 0; y < size; y++) {
  74024. randVector.x = rand(0.0, 1.0);
  74025. randVector.y = rand(0.0, 1.0);
  74026. randVector.z = 0.0;
  74027. randVector.normalize();
  74028. randVector.scaleInPlace(255);
  74029. randVector.x = Math.floor(randVector.x);
  74030. randVector.y = Math.floor(randVector.y);
  74031. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74032. context.fillRect(x, y, 1, 1);
  74033. }
  74034. }
  74035. this._randomTexture.update(false);
  74036. };
  74037. /**
  74038. * Serialize the rendering pipeline (Used when exporting)
  74039. * @returns the serialized object
  74040. */
  74041. SSAO2RenderingPipeline.prototype.serialize = function () {
  74042. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74043. serializationObject.customType = "SSAO2RenderingPipeline";
  74044. return serializationObject;
  74045. };
  74046. /**
  74047. * Parse the serialized pipeline
  74048. * @param source Source pipeline.
  74049. * @param scene The scene to load the pipeline to.
  74050. * @param rootUrl The URL of the serialized pipeline.
  74051. * @returns An instantiated pipeline from the serialized object.
  74052. */
  74053. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74054. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74055. };
  74056. __decorate([
  74057. BABYLON.serialize()
  74058. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74059. __decorate([
  74060. BABYLON.serialize()
  74061. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74062. __decorate([
  74063. BABYLON.serialize()
  74064. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74065. __decorate([
  74066. BABYLON.serialize("samples")
  74067. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74068. __decorate([
  74069. BABYLON.serialize()
  74070. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74071. __decorate([
  74072. BABYLON.serialize("expensiveBlur")
  74073. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74074. __decorate([
  74075. BABYLON.serialize()
  74076. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74077. __decorate([
  74078. BABYLON.serialize()
  74079. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74080. return SSAO2RenderingPipeline;
  74081. }(BABYLON.PostProcessRenderPipeline));
  74082. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74083. })(BABYLON || (BABYLON = {}));
  74084. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74085. // BABYLON.JS Chromatic Aberration GLSL Shader
  74086. // Author: Olivier Guyot
  74087. // Separates very slightly R, G and B colors on the edges of the screen
  74088. // Inspired by Francois Tarlier & Martins Upitis
  74089. var BABYLON;
  74090. (function (BABYLON) {
  74091. var LensRenderingPipeline = /** @class */ (function (_super) {
  74092. __extends(LensRenderingPipeline, _super);
  74093. /**
  74094. * @constructor
  74095. *
  74096. * Effect parameters are as follow:
  74097. * {
  74098. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74099. * edge_blur: number; // from 0 to x (1 for realism)
  74100. * distortion: number; // from 0 to x (1 for realism)
  74101. * grain_amount: number; // from 0 to 1
  74102. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74103. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74104. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74105. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74106. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74107. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74108. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74109. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74110. * }
  74111. * Note: if an effect parameter is unset, effect is disabled
  74112. *
  74113. * @param {string} name - The rendering pipeline name
  74114. * @param {object} parameters - An object containing all parameters (see above)
  74115. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74116. * @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)
  74117. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74118. */
  74119. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74120. if (ratio === void 0) { ratio = 1.0; }
  74121. var _this = _super.call(this, scene.getEngine(), name) || this;
  74122. // Lens effects can be of the following:
  74123. // - chromatic aberration (slight shift of RGB colors)
  74124. // - blur on the edge of the lens
  74125. // - lens distortion
  74126. // - depth-of-field blur & highlights enhancing
  74127. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74128. // - grain effect (noise or custom texture)
  74129. // Two additional texture samplers are needed:
  74130. // - depth map (for depth-of-field)
  74131. // - grain texture
  74132. /**
  74133. * The chromatic aberration PostProcess id in the pipeline
  74134. */
  74135. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74136. /**
  74137. * The highlights enhancing PostProcess id in the pipeline
  74138. */
  74139. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74140. /**
  74141. * The depth-of-field PostProcess id in the pipeline
  74142. */
  74143. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74144. _this._scene = scene;
  74145. // Fetch texture samplers
  74146. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74147. if (parameters.grain_texture) {
  74148. _this._grainTexture = parameters.grain_texture;
  74149. }
  74150. else {
  74151. _this._createGrainTexture();
  74152. }
  74153. // save parameters
  74154. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74155. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74156. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74157. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74158. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74159. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74160. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74161. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74162. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74163. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74164. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74165. // Create effects
  74166. _this._createChromaticAberrationPostProcess(ratio);
  74167. _this._createHighlightsPostProcess(ratio);
  74168. _this._createDepthOfFieldPostProcess(ratio / 4);
  74169. // Set up pipeline
  74170. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74171. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74172. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74173. if (_this._highlightsGain === -1) {
  74174. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74175. }
  74176. // Finish
  74177. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74178. if (cameras) {
  74179. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74180. }
  74181. return _this;
  74182. }
  74183. // public methods (self explanatory)
  74184. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74185. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74186. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74187. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74188. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74189. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74190. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74191. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74192. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74193. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74194. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74195. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74196. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74197. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74198. };
  74199. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74200. this._highlightsPostProcess.updateEffect();
  74201. };
  74202. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74203. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74204. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74205. this._highlightsGain = amount;
  74206. };
  74207. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74208. if (this._highlightsGain === -1) {
  74209. this._highlightsGain = 1.0;
  74210. }
  74211. this._highlightsThreshold = amount;
  74212. };
  74213. LensRenderingPipeline.prototype.disableHighlights = function () {
  74214. this._highlightsGain = -1;
  74215. };
  74216. /**
  74217. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74218. */
  74219. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74220. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74221. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74222. this._chromaticAberrationPostProcess = null;
  74223. this._highlightsPostProcess = null;
  74224. this._depthOfFieldPostProcess = null;
  74225. this._grainTexture.dispose();
  74226. if (disableDepthRender)
  74227. this._scene.disableDepthRenderer();
  74228. };
  74229. // colors shifting and distortion
  74230. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74231. var _this = this;
  74232. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74233. [], // samplers
  74234. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74235. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74236. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74237. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74238. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74239. effect.setFloat('radialIntensity', 1);
  74240. effect.setFloat2('direction', 17, 17);
  74241. effect.setFloat2('centerPosition', 0.5, 0.5);
  74242. };
  74243. };
  74244. // highlights enhancing
  74245. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74246. var _this = this;
  74247. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74248. [], // samplers
  74249. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74250. this._highlightsPostProcess.onApply = function (effect) {
  74251. effect.setFloat('gain', _this._highlightsGain);
  74252. effect.setFloat('threshold', _this._highlightsThreshold);
  74253. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74254. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74255. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74256. };
  74257. };
  74258. // colors shifting and distortion
  74259. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74260. var _this = this;
  74261. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74262. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74263. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74264. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74265. this._depthOfFieldPostProcess.onApply = function (effect) {
  74266. effect.setTexture("depthSampler", _this._depthTexture);
  74267. effect.setTexture("grainSampler", _this._grainTexture);
  74268. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74269. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74270. effect.setFloat('grain_amount', _this._grainAmount);
  74271. effect.setBool('blur_noise', _this._blurNoise);
  74272. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74273. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74274. effect.setFloat('distortion', _this._distortion);
  74275. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74276. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74277. effect.setFloat('aperture', _this._dofAperture);
  74278. effect.setFloat('darken', _this._dofDarken);
  74279. effect.setFloat('edge_blur', _this._edgeBlur);
  74280. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74281. if (_this._scene.activeCamera) {
  74282. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74283. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74284. }
  74285. };
  74286. };
  74287. // creates a black and white random noise texture, 512x512
  74288. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74289. var size = 512;
  74290. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74291. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74292. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74293. var context = this._grainTexture.getContext();
  74294. var rand = function (min, max) {
  74295. return Math.random() * (max - min) + min;
  74296. };
  74297. var value;
  74298. for (var x = 0; x < size; x++) {
  74299. for (var y = 0; y < size; y++) {
  74300. value = Math.floor(rand(0.42, 0.58) * 255);
  74301. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74302. context.fillRect(x, y, 1, 1);
  74303. }
  74304. }
  74305. this._grainTexture.update(false);
  74306. };
  74307. return LensRenderingPipeline;
  74308. }(BABYLON.PostProcessRenderPipeline));
  74309. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74310. })(BABYLON || (BABYLON = {}));
  74311. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74312. var BABYLON;
  74313. (function (BABYLON) {
  74314. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74315. __extends(StandardRenderingPipeline, _super);
  74316. /**
  74317. * @constructor
  74318. * @param {string} name - The rendering pipeline name
  74319. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74320. * @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)
  74321. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74322. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74323. */
  74324. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74325. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74326. var _this = _super.call(this, scene.getEngine(), name) || this;
  74327. _this.downSampleX4PostProcess = null;
  74328. _this.brightPassPostProcess = null;
  74329. _this.blurHPostProcesses = [];
  74330. _this.blurVPostProcesses = [];
  74331. _this.textureAdderPostProcess = null;
  74332. _this.volumetricLightPostProcess = null;
  74333. _this.volumetricLightSmoothXPostProcess = null;
  74334. _this.volumetricLightSmoothYPostProcess = null;
  74335. _this.volumetricLightMergePostProces = null;
  74336. _this.volumetricLightFinalPostProcess = null;
  74337. _this.luminancePostProcess = null;
  74338. _this.luminanceDownSamplePostProcesses = [];
  74339. _this.hdrPostProcess = null;
  74340. _this.textureAdderFinalPostProcess = null;
  74341. _this.lensFlareFinalPostProcess = null;
  74342. _this.hdrFinalPostProcess = null;
  74343. _this.lensFlarePostProcess = null;
  74344. _this.lensFlareComposePostProcess = null;
  74345. _this.motionBlurPostProcess = null;
  74346. _this.depthOfFieldPostProcess = null;
  74347. // Values
  74348. _this.brightThreshold = 1.0;
  74349. _this.blurWidth = 512.0;
  74350. _this.horizontalBlur = false;
  74351. _this.exposure = 1.0;
  74352. _this.lensTexture = null;
  74353. _this.volumetricLightCoefficient = 0.2;
  74354. _this.volumetricLightPower = 4.0;
  74355. _this.volumetricLightBlurScale = 64.0;
  74356. _this.sourceLight = null;
  74357. _this.hdrMinimumLuminance = 1.0;
  74358. _this.hdrDecreaseRate = 0.5;
  74359. _this.hdrIncreaseRate = 0.5;
  74360. _this.lensColorTexture = null;
  74361. _this.lensFlareStrength = 20.0;
  74362. _this.lensFlareGhostDispersal = 1.4;
  74363. _this.lensFlareHaloWidth = 0.7;
  74364. _this.lensFlareDistortionStrength = 16.0;
  74365. _this.lensStarTexture = null;
  74366. _this.lensFlareDirtTexture = null;
  74367. _this.depthOfFieldDistance = 10.0;
  74368. _this.depthOfFieldBlurWidth = 64.0;
  74369. _this.motionStrength = 1.0;
  74370. // IAnimatable
  74371. _this.animations = [];
  74372. _this._currentDepthOfFieldSource = null;
  74373. _this._hdrCurrentLuminance = 1.0;
  74374. // Getters and setters
  74375. _this._bloomEnabled = true;
  74376. _this._depthOfFieldEnabled = false;
  74377. _this._vlsEnabled = false;
  74378. _this._lensFlareEnabled = false;
  74379. _this._hdrEnabled = false;
  74380. _this._motionBlurEnabled = false;
  74381. _this._motionBlurSamples = 64.0;
  74382. _this._volumetricLightStepsCount = 50.0;
  74383. _this._cameras = cameras || [];
  74384. // Initialize
  74385. _this._scene = scene;
  74386. _this._basePostProcess = originalPostProcess;
  74387. _this._ratio = ratio;
  74388. // Misc
  74389. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74390. // Finish
  74391. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74392. _this._buildPipeline();
  74393. return _this;
  74394. }
  74395. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74396. get: function () {
  74397. return this._bloomEnabled;
  74398. },
  74399. set: function (enabled) {
  74400. if (this._bloomEnabled === enabled) {
  74401. return;
  74402. }
  74403. this._bloomEnabled = enabled;
  74404. this._buildPipeline();
  74405. },
  74406. enumerable: true,
  74407. configurable: true
  74408. });
  74409. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74410. get: function () {
  74411. return this._depthOfFieldEnabled;
  74412. },
  74413. set: function (enabled) {
  74414. if (this._depthOfFieldEnabled === enabled) {
  74415. return;
  74416. }
  74417. this._depthOfFieldEnabled = enabled;
  74418. this._buildPipeline();
  74419. },
  74420. enumerable: true,
  74421. configurable: true
  74422. });
  74423. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74424. get: function () {
  74425. return this._lensFlareEnabled;
  74426. },
  74427. set: function (enabled) {
  74428. if (this._lensFlareEnabled === enabled) {
  74429. return;
  74430. }
  74431. this._lensFlareEnabled = enabled;
  74432. this._buildPipeline();
  74433. },
  74434. enumerable: true,
  74435. configurable: true
  74436. });
  74437. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74438. get: function () {
  74439. return this._hdrEnabled;
  74440. },
  74441. set: function (enabled) {
  74442. if (this._hdrEnabled === enabled) {
  74443. return;
  74444. }
  74445. this._hdrEnabled = enabled;
  74446. this._buildPipeline();
  74447. },
  74448. enumerable: true,
  74449. configurable: true
  74450. });
  74451. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74452. get: function () {
  74453. return this._vlsEnabled;
  74454. },
  74455. set: function (enabled) {
  74456. if (this._vlsEnabled === enabled) {
  74457. return;
  74458. }
  74459. if (enabled) {
  74460. var geometry = this._scene.enableGeometryBufferRenderer();
  74461. if (!geometry) {
  74462. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74463. return;
  74464. }
  74465. }
  74466. this._vlsEnabled = enabled;
  74467. this._buildPipeline();
  74468. },
  74469. enumerable: true,
  74470. configurable: true
  74471. });
  74472. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74473. get: function () {
  74474. return this._motionBlurEnabled;
  74475. },
  74476. set: function (enabled) {
  74477. if (this._motionBlurEnabled === enabled) {
  74478. return;
  74479. }
  74480. this._motionBlurEnabled = enabled;
  74481. this._buildPipeline();
  74482. },
  74483. enumerable: true,
  74484. configurable: true
  74485. });
  74486. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74487. get: function () {
  74488. return this._volumetricLightStepsCount;
  74489. },
  74490. set: function (count) {
  74491. if (this.volumetricLightPostProcess) {
  74492. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74493. }
  74494. this._volumetricLightStepsCount = count;
  74495. },
  74496. enumerable: true,
  74497. configurable: true
  74498. });
  74499. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74500. get: function () {
  74501. return this._motionBlurSamples;
  74502. },
  74503. set: function (samples) {
  74504. if (this.motionBlurPostProcess) {
  74505. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74506. }
  74507. this._motionBlurSamples = samples;
  74508. },
  74509. enumerable: true,
  74510. configurable: true
  74511. });
  74512. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74513. var _this = this;
  74514. var ratio = this._ratio;
  74515. var scene = this._scene;
  74516. this._disposePostProcesses();
  74517. this._reset();
  74518. // Create pass post-process
  74519. if (!this._basePostProcess) {
  74520. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74521. this.originalPostProcess.onApply = function (effect) {
  74522. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74523. };
  74524. }
  74525. else {
  74526. this.originalPostProcess = this._basePostProcess;
  74527. }
  74528. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74529. this._currentDepthOfFieldSource = this.originalPostProcess;
  74530. if (this._bloomEnabled) {
  74531. // Create down sample X4 post-process
  74532. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74533. // Create bright pass post-process
  74534. this._createBrightPassPostProcess(scene, ratio / 2);
  74535. // Create gaussian blur post-processes (down sampling blurs)
  74536. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74537. // Create texture adder post-process
  74538. this._createTextureAdderPostProcess(scene, ratio);
  74539. // Create depth-of-field source post-process
  74540. 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);
  74541. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74542. }
  74543. if (this._vlsEnabled) {
  74544. // Create volumetric light
  74545. this._createVolumetricLightPostProcess(scene, ratio);
  74546. // Create volumetric light final post-process
  74547. 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);
  74548. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74549. }
  74550. if (this._lensFlareEnabled) {
  74551. // Create lens flare post-process
  74552. this._createLensFlarePostProcess(scene, ratio);
  74553. // Create depth-of-field source post-process post lens-flare and disable it now
  74554. 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);
  74555. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74556. }
  74557. if (this._hdrEnabled) {
  74558. // Create luminance
  74559. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74560. // Create HDR
  74561. this._createHdrPostProcess(scene, ratio);
  74562. // Create depth-of-field source post-process post hdr and disable it now
  74563. 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);
  74564. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74565. }
  74566. if (this._depthOfFieldEnabled) {
  74567. // Create gaussian blur used by depth-of-field
  74568. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74569. // Create depth-of-field post-process
  74570. this._createDepthOfFieldPostProcess(scene, ratio);
  74571. }
  74572. if (this._motionBlurEnabled) {
  74573. // Create motion blur post-process
  74574. this._createMotionBlurPostProcess(scene, ratio);
  74575. }
  74576. if (this._cameras !== null) {
  74577. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74578. }
  74579. };
  74580. // Down Sample X4 Post-Processs
  74581. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74582. var _this = this;
  74583. var downSampleX4Offsets = new Array(32);
  74584. 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);
  74585. this.downSampleX4PostProcess.onApply = function (effect) {
  74586. var id = 0;
  74587. var width = _this.downSampleX4PostProcess.width;
  74588. var height = _this.downSampleX4PostProcess.height;
  74589. for (var i = -2; i < 2; i++) {
  74590. for (var j = -2; j < 2; j++) {
  74591. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74592. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74593. id += 2;
  74594. }
  74595. }
  74596. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74597. };
  74598. // Add to pipeline
  74599. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74600. };
  74601. // Brightpass Post-Process
  74602. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74603. var _this = this;
  74604. var brightOffsets = new Array(8);
  74605. 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);
  74606. this.brightPassPostProcess.onApply = function (effect) {
  74607. var sU = (1.0 / _this.brightPassPostProcess.width);
  74608. var sV = (1.0 / _this.brightPassPostProcess.height);
  74609. brightOffsets[0] = -0.5 * sU;
  74610. brightOffsets[1] = 0.5 * sV;
  74611. brightOffsets[2] = 0.5 * sU;
  74612. brightOffsets[3] = 0.5 * sV;
  74613. brightOffsets[4] = -0.5 * sU;
  74614. brightOffsets[5] = -0.5 * sV;
  74615. brightOffsets[6] = 0.5 * sU;
  74616. brightOffsets[7] = -0.5 * sV;
  74617. effect.setArray2("dsOffsets", brightOffsets);
  74618. effect.setFloat("brightThreshold", _this.brightThreshold);
  74619. };
  74620. // Add to pipeline
  74621. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74622. };
  74623. // Create blur H&V post-processes
  74624. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74625. var _this = this;
  74626. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74627. var engine = scene.getEngine();
  74628. 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);
  74629. 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);
  74630. blurX.onActivateObservable.add(function () {
  74631. var dw = blurX.width / engine.getRenderWidth();
  74632. blurX.kernel = _this[blurWidthKey] * dw;
  74633. });
  74634. blurY.onActivateObservable.add(function () {
  74635. var dw = blurY.height / engine.getRenderHeight();
  74636. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74637. });
  74638. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74639. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74640. this.blurHPostProcesses.push(blurX);
  74641. this.blurVPostProcesses.push(blurY);
  74642. };
  74643. // Create texture adder post-process
  74644. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74645. var _this = this;
  74646. 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);
  74647. this.textureAdderPostProcess.onApply = function (effect) {
  74648. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74649. effect.setTexture("lensSampler", _this.lensTexture);
  74650. effect.setFloat("exposure", _this.exposure);
  74651. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74652. };
  74653. // Add to pipeline
  74654. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74655. };
  74656. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74657. var _this = this;
  74658. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74659. geometryRenderer.enablePosition = true;
  74660. var geometry = geometryRenderer.getGBuffer();
  74661. // Base post-process
  74662. 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));
  74663. var depthValues = BABYLON.Vector2.Zero();
  74664. this.volumetricLightPostProcess.onApply = function (effect) {
  74665. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74666. var generator = _this.sourceLight.getShadowGenerator();
  74667. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74668. effect.setTexture("positionSampler", geometry.textures[2]);
  74669. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74670. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74671. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74672. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74673. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74674. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74675. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74676. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74677. effect.setVector2("depthValues", depthValues);
  74678. }
  74679. };
  74680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74681. // Smooth
  74682. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74683. // Merge
  74684. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74685. this.volumetricLightMergePostProces.onApply = function (effect) {
  74686. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74687. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74688. };
  74689. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74690. };
  74691. // Create luminance
  74692. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74693. var _this = this;
  74694. // Create luminance
  74695. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74696. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74697. var offsets = [];
  74698. this.luminancePostProcess.onApply = function (effect) {
  74699. var sU = (1.0 / _this.luminancePostProcess.width);
  74700. var sV = (1.0 / _this.luminancePostProcess.height);
  74701. offsets[0] = -0.5 * sU;
  74702. offsets[1] = 0.5 * sV;
  74703. offsets[2] = 0.5 * sU;
  74704. offsets[3] = 0.5 * sV;
  74705. offsets[4] = -0.5 * sU;
  74706. offsets[5] = -0.5 * sV;
  74707. offsets[6] = 0.5 * sU;
  74708. offsets[7] = -0.5 * sV;
  74709. effect.setArray2("lumOffsets", offsets);
  74710. };
  74711. // Add to pipeline
  74712. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74713. // Create down sample luminance
  74714. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74715. var size = Math.pow(3, i);
  74716. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74717. if (i === 0) {
  74718. defines += "#define FINAL_DOWN_SAMPLER";
  74719. }
  74720. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74721. this.luminanceDownSamplePostProcesses.push(postProcess);
  74722. }
  74723. // Create callbacks and add effects
  74724. var lastLuminance = this.luminancePostProcess;
  74725. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74726. var downSampleOffsets = new Array(18);
  74727. pp.onApply = function (effect) {
  74728. if (!lastLuminance) {
  74729. return;
  74730. }
  74731. var id = 0;
  74732. for (var x = -1; x < 2; x++) {
  74733. for (var y = -1; y < 2; y++) {
  74734. downSampleOffsets[id] = x / lastLuminance.width;
  74735. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74736. id += 2;
  74737. }
  74738. }
  74739. effect.setArray2("dsOffsets", downSampleOffsets);
  74740. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74741. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74742. lastLuminance = _this.luminancePostProcess;
  74743. }
  74744. else {
  74745. lastLuminance = pp;
  74746. }
  74747. };
  74748. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74749. pp.onAfterRender = function (effect) {
  74750. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74751. 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);
  74752. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74753. };
  74754. }
  74755. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74756. });
  74757. };
  74758. // Create HDR post-process
  74759. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74760. var _this = this;
  74761. 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);
  74762. var outputLiminance = 1;
  74763. var time = 0;
  74764. var lastTime = 0;
  74765. this.hdrPostProcess.onApply = function (effect) {
  74766. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74767. time += scene.getEngine().getDeltaTime();
  74768. if (outputLiminance < 0) {
  74769. outputLiminance = _this._hdrCurrentLuminance;
  74770. }
  74771. else {
  74772. var dt = (lastTime - time) / 1000.0;
  74773. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74774. outputLiminance += _this.hdrDecreaseRate * dt;
  74775. }
  74776. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74777. outputLiminance -= _this.hdrIncreaseRate * dt;
  74778. }
  74779. else {
  74780. outputLiminance = _this._hdrCurrentLuminance;
  74781. }
  74782. }
  74783. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74784. effect.setFloat("averageLuminance", outputLiminance);
  74785. lastTime = time;
  74786. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74787. };
  74788. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74789. };
  74790. // Create lens flare post-process
  74791. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74792. var _this = this;
  74793. 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);
  74794. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74795. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74796. 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);
  74797. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74798. var resolution = new BABYLON.Vector2(0, 0);
  74799. // Lens flare
  74800. this.lensFlarePostProcess.onApply = function (effect) {
  74801. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74802. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74803. effect.setFloat("strength", _this.lensFlareStrength);
  74804. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74805. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74806. // Shift
  74807. resolution.x = _this.lensFlarePostProcess.width;
  74808. resolution.y = _this.lensFlarePostProcess.height;
  74809. effect.setVector2("resolution", resolution);
  74810. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74811. };
  74812. // Compose
  74813. 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);
  74814. 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);
  74815. this.lensFlareComposePostProcess.onApply = function (effect) {
  74816. if (!_this._scene.activeCamera) {
  74817. return;
  74818. }
  74819. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74820. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74821. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74822. // Lens start rotation matrix
  74823. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74824. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74825. 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));
  74826. camRot *= 4.0;
  74827. 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);
  74828. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74829. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74830. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74831. };
  74832. };
  74833. // Create depth-of-field post-process
  74834. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74835. var _this = this;
  74836. 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);
  74837. this.depthOfFieldPostProcess.onApply = function (effect) {
  74838. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74839. effect.setTexture("depthSampler", _this._getDepthTexture());
  74840. effect.setFloat("distance", _this.depthOfFieldDistance);
  74841. };
  74842. // Add to pipeline
  74843. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74844. };
  74845. // Create motion blur post-process
  74846. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74847. var _this = this;
  74848. 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);
  74849. var motionScale = 0;
  74850. var prevViewProjection = BABYLON.Matrix.Identity();
  74851. var invViewProjection = BABYLON.Matrix.Identity();
  74852. var viewProjection = BABYLON.Matrix.Identity();
  74853. var screenSize = BABYLON.Vector2.Zero();
  74854. this.motionBlurPostProcess.onApply = function (effect) {
  74855. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74856. viewProjection.invertToRef(invViewProjection);
  74857. effect.setMatrix("inverseViewProjection", invViewProjection);
  74858. effect.setMatrix("prevViewProjection", prevViewProjection);
  74859. prevViewProjection = viewProjection;
  74860. screenSize.x = _this.motionBlurPostProcess.width;
  74861. screenSize.y = _this.motionBlurPostProcess.height;
  74862. effect.setVector2("screenSize", screenSize);
  74863. motionScale = scene.getEngine().getFps() / 60.0;
  74864. effect.setFloat("motionScale", motionScale);
  74865. effect.setFloat("motionStrength", _this.motionStrength);
  74866. effect.setTexture("depthSampler", _this._getDepthTexture());
  74867. };
  74868. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74869. };
  74870. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74871. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74872. var renderer = this._scene.enableGeometryBufferRenderer();
  74873. return renderer.getGBuffer().textures[0];
  74874. }
  74875. return this._scene.enableDepthRenderer().getDepthMap();
  74876. };
  74877. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74878. for (var i = 0; i < this._cameras.length; i++) {
  74879. var camera = this._cameras[i];
  74880. if (this.originalPostProcess) {
  74881. this.originalPostProcess.dispose(camera);
  74882. }
  74883. if (this.downSampleX4PostProcess) {
  74884. this.downSampleX4PostProcess.dispose(camera);
  74885. }
  74886. if (this.brightPassPostProcess) {
  74887. this.brightPassPostProcess.dispose(camera);
  74888. }
  74889. if (this.textureAdderPostProcess) {
  74890. this.textureAdderPostProcess.dispose(camera);
  74891. }
  74892. if (this.textureAdderFinalPostProcess) {
  74893. this.textureAdderFinalPostProcess.dispose(camera);
  74894. }
  74895. if (this.volumetricLightPostProcess) {
  74896. this.volumetricLightPostProcess.dispose(camera);
  74897. }
  74898. if (this.volumetricLightSmoothXPostProcess) {
  74899. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74900. }
  74901. if (this.volumetricLightSmoothYPostProcess) {
  74902. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74903. }
  74904. if (this.volumetricLightMergePostProces) {
  74905. this.volumetricLightMergePostProces.dispose(camera);
  74906. }
  74907. if (this.volumetricLightFinalPostProcess) {
  74908. this.volumetricLightFinalPostProcess.dispose(camera);
  74909. }
  74910. if (this.lensFlarePostProcess) {
  74911. this.lensFlarePostProcess.dispose(camera);
  74912. }
  74913. if (this.lensFlareComposePostProcess) {
  74914. this.lensFlareComposePostProcess.dispose(camera);
  74915. }
  74916. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74917. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74918. }
  74919. if (this.luminancePostProcess) {
  74920. this.luminancePostProcess.dispose(camera);
  74921. }
  74922. if (this.hdrPostProcess) {
  74923. this.hdrPostProcess.dispose(camera);
  74924. }
  74925. if (this.hdrFinalPostProcess) {
  74926. this.hdrFinalPostProcess.dispose(camera);
  74927. }
  74928. if (this.depthOfFieldPostProcess) {
  74929. this.depthOfFieldPostProcess.dispose(camera);
  74930. }
  74931. if (this.motionBlurPostProcess) {
  74932. this.motionBlurPostProcess.dispose(camera);
  74933. }
  74934. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74935. this.blurHPostProcesses[j].dispose(camera);
  74936. }
  74937. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74938. this.blurVPostProcesses[j].dispose(camera);
  74939. }
  74940. }
  74941. this.originalPostProcess = null;
  74942. this.downSampleX4PostProcess = null;
  74943. this.brightPassPostProcess = null;
  74944. this.textureAdderPostProcess = null;
  74945. this.textureAdderFinalPostProcess = null;
  74946. this.volumetricLightPostProcess = null;
  74947. this.volumetricLightSmoothXPostProcess = null;
  74948. this.volumetricLightSmoothYPostProcess = null;
  74949. this.volumetricLightMergePostProces = null;
  74950. this.volumetricLightFinalPostProcess = null;
  74951. this.lensFlarePostProcess = null;
  74952. this.lensFlareComposePostProcess = null;
  74953. this.luminancePostProcess = null;
  74954. this.hdrPostProcess = null;
  74955. this.hdrFinalPostProcess = null;
  74956. this.depthOfFieldPostProcess = null;
  74957. this.motionBlurPostProcess = null;
  74958. this.luminanceDownSamplePostProcesses = [];
  74959. this.blurHPostProcesses = [];
  74960. this.blurVPostProcesses = [];
  74961. };
  74962. /**
  74963. * Dispose of the pipeline and stop all post processes
  74964. */
  74965. StandardRenderingPipeline.prototype.dispose = function () {
  74966. this._disposePostProcesses();
  74967. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74968. _super.prototype.dispose.call(this);
  74969. };
  74970. /**
  74971. * Serialize the rendering pipeline (Used when exporting)
  74972. * @returns the serialized object
  74973. */
  74974. StandardRenderingPipeline.prototype.serialize = function () {
  74975. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74976. if (this.sourceLight) {
  74977. serializationObject.sourceLightId = this.sourceLight.id;
  74978. }
  74979. serializationObject.customType = "StandardRenderingPipeline";
  74980. return serializationObject;
  74981. };
  74982. /**
  74983. * Parse the serialized pipeline
  74984. * @param source Source pipeline.
  74985. * @param scene The scene to load the pipeline to.
  74986. * @param rootUrl The URL of the serialized pipeline.
  74987. * @returns An instantiated pipeline from the serialized object.
  74988. */
  74989. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74990. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74991. if (source.sourceLightId) {
  74992. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74993. }
  74994. return p;
  74995. };
  74996. // Luminance steps
  74997. StandardRenderingPipeline.LuminanceSteps = 6;
  74998. __decorate([
  74999. BABYLON.serialize()
  75000. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75001. __decorate([
  75002. BABYLON.serialize()
  75003. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75004. __decorate([
  75005. BABYLON.serialize()
  75006. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75007. __decorate([
  75008. BABYLON.serialize()
  75009. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75010. __decorate([
  75011. BABYLON.serializeAsTexture("lensTexture")
  75012. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75013. __decorate([
  75014. BABYLON.serialize()
  75015. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75016. __decorate([
  75017. BABYLON.serialize()
  75018. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75019. __decorate([
  75020. BABYLON.serialize()
  75021. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75022. __decorate([
  75023. BABYLON.serialize()
  75024. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75025. __decorate([
  75026. BABYLON.serialize()
  75027. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75028. __decorate([
  75029. BABYLON.serialize()
  75030. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75031. __decorate([
  75032. BABYLON.serializeAsTexture("lensColorTexture")
  75033. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75034. __decorate([
  75035. BABYLON.serialize()
  75036. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75037. __decorate([
  75038. BABYLON.serialize()
  75039. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75040. __decorate([
  75041. BABYLON.serialize()
  75042. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75043. __decorate([
  75044. BABYLON.serialize()
  75045. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75046. __decorate([
  75047. BABYLON.serializeAsTexture("lensStarTexture")
  75048. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75049. __decorate([
  75050. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75051. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75052. __decorate([
  75053. BABYLON.serialize()
  75054. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75055. __decorate([
  75056. BABYLON.serialize()
  75057. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75058. __decorate([
  75059. BABYLON.serialize()
  75060. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75061. __decorate([
  75062. BABYLON.serialize()
  75063. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75064. __decorate([
  75065. BABYLON.serialize()
  75066. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75067. __decorate([
  75068. BABYLON.serialize()
  75069. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75070. __decorate([
  75071. BABYLON.serialize()
  75072. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75073. __decorate([
  75074. BABYLON.serialize()
  75075. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75076. __decorate([
  75077. BABYLON.serialize()
  75078. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75079. __decorate([
  75080. BABYLON.serialize()
  75081. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75082. __decorate([
  75083. BABYLON.serialize()
  75084. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75085. __decorate([
  75086. BABYLON.serialize()
  75087. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75088. return StandardRenderingPipeline;
  75089. }(BABYLON.PostProcessRenderPipeline));
  75090. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75091. })(BABYLON || (BABYLON = {}));
  75092. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75093. var BABYLON;
  75094. (function (BABYLON) {
  75095. var FxaaPostProcess = /** @class */ (function (_super) {
  75096. __extends(FxaaPostProcess, _super);
  75097. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75098. if (camera === void 0) { camera = null; }
  75099. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75100. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75101. var defines = _this._getDefines();
  75102. _this.updateEffect(defines);
  75103. _this.onApplyObservable.add(function (effect) {
  75104. var texelSize = _this.texelSize;
  75105. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75106. });
  75107. return _this;
  75108. }
  75109. FxaaPostProcess.prototype._getDefines = function () {
  75110. var engine = this.getEngine();
  75111. if (!engine) {
  75112. return null;
  75113. }
  75114. var glInfo = engine.getGlInfo();
  75115. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75116. return "#define MALI 1\n";
  75117. }
  75118. return null;
  75119. };
  75120. return FxaaPostProcess;
  75121. }(BABYLON.PostProcess));
  75122. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75123. })(BABYLON || (BABYLON = {}));
  75124. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75125. var BABYLON;
  75126. (function (BABYLON) {
  75127. /**
  75128. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75129. */
  75130. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75131. __extends(ChromaticAberrationPostProcess, _super);
  75132. /**
  75133. * Creates a new instance ChromaticAberrationPostProcess
  75134. * @param name The name of the effect.
  75135. * @param screenWidth The width of the screen to apply the effect on.
  75136. * @param screenHeight The height of the screen to apply the effect on.
  75137. * @param options The required width/height ratio to downsize to before computing the render pass.
  75138. * @param camera The camera to apply the render pass to.
  75139. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75140. * @param engine The engine which the post process will be applied. (default: current engine)
  75141. * @param reusable If the post process can be reused on the same frame. (default: false)
  75142. * @param textureType Type of textures used when performing the post process. (default: 0)
  75143. * @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)
  75144. */
  75145. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75146. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75147. if (blockCompilation === void 0) { blockCompilation = false; }
  75148. 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;
  75149. /**
  75150. * The amount of seperation of rgb channels (default: 30)
  75151. */
  75152. _this.aberrationAmount = 30;
  75153. /**
  75154. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75155. */
  75156. _this.radialIntensity = 0;
  75157. /**
  75158. * 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))
  75159. */
  75160. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75161. /**
  75162. * 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))
  75163. */
  75164. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75165. _this.onApplyObservable.add(function (effect) {
  75166. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75167. effect.setFloat('screen_width', screenWidth);
  75168. effect.setFloat('screen_height', screenHeight);
  75169. effect.setFloat('radialIntensity', _this.radialIntensity);
  75170. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75171. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75172. });
  75173. return _this;
  75174. }
  75175. return ChromaticAberrationPostProcess;
  75176. }(BABYLON.PostProcess));
  75177. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75178. })(BABYLON || (BABYLON = {}));
  75179. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75180. var BABYLON;
  75181. (function (BABYLON) {
  75182. /**
  75183. * The GrainPostProcess adds noise to the image at mid luminance levels
  75184. */
  75185. var GrainPostProcess = /** @class */ (function (_super) {
  75186. __extends(GrainPostProcess, _super);
  75187. /**
  75188. * Creates a new instance of @see GrainPostProcess
  75189. * @param name The name of the effect.
  75190. * @param options The required width/height ratio to downsize to before computing the render pass.
  75191. * @param camera The camera to apply the render pass to.
  75192. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75193. * @param engine The engine which the post process will be applied. (default: current engine)
  75194. * @param reusable If the post process can be reused on the same frame. (default: false)
  75195. * @param textureType Type of textures used when performing the post process. (default: 0)
  75196. * @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)
  75197. */
  75198. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75199. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75200. if (blockCompilation === void 0) { blockCompilation = false; }
  75201. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75202. /**
  75203. * The intensity of the grain added (default: 30)
  75204. */
  75205. _this.intensity = 30;
  75206. /**
  75207. * If the grain should be randomized on every frame
  75208. */
  75209. _this.animated = false;
  75210. _this.onApplyObservable.add(function (effect) {
  75211. effect.setFloat('intensity', _this.intensity);
  75212. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75213. });
  75214. return _this;
  75215. }
  75216. return GrainPostProcess;
  75217. }(BABYLON.PostProcess));
  75218. BABYLON.GrainPostProcess = GrainPostProcess;
  75219. })(BABYLON || (BABYLON = {}));
  75220. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75221. var BABYLON;
  75222. (function (BABYLON) {
  75223. /**
  75224. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75225. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75226. */
  75227. var SharpenPostProcess = /** @class */ (function (_super) {
  75228. __extends(SharpenPostProcess, _super);
  75229. /**
  75230. * Creates a new instance ConvolutionPostProcess
  75231. * @param name The name of the effect.
  75232. * @param options The required width/height ratio to downsize to before computing the render pass.
  75233. * @param camera The camera to apply the render pass to.
  75234. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75235. * @param engine The engine which the post process will be applied. (default: current engine)
  75236. * @param reusable If the post process can be reused on the same frame. (default: false)
  75237. * @param textureType Type of textures used when performing the post process. (default: 0)
  75238. * @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)
  75239. */
  75240. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75241. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75242. if (blockCompilation === void 0) { blockCompilation = false; }
  75243. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75244. /**
  75245. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75246. */
  75247. _this.colorAmount = 1.0;
  75248. /**
  75249. * How much sharpness should be applied (default: 0.3)
  75250. */
  75251. _this.edgeAmount = 0.3;
  75252. _this.onApply = function (effect) {
  75253. effect.setFloat2("screenSize", _this.width, _this.height);
  75254. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75255. };
  75256. return _this;
  75257. }
  75258. return SharpenPostProcess;
  75259. }(BABYLON.PostProcess));
  75260. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75261. })(BABYLON || (BABYLON = {}));
  75262. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75263. var BABYLON;
  75264. (function (BABYLON) {
  75265. /**
  75266. * The Blur Post Process which blurs an image based on a kernel and direction.
  75267. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75268. */
  75269. var BlurPostProcess = /** @class */ (function (_super) {
  75270. __extends(BlurPostProcess, _super);
  75271. /**
  75272. * Creates a new instance BlurPostProcess
  75273. * @param name The name of the effect.
  75274. * @param direction The direction in which to blur the image.
  75275. * @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.
  75276. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75277. * @param camera The camera to apply the render pass to.
  75278. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75279. * @param engine The engine which the post process will be applied. (default: current engine)
  75280. * @param reusable If the post process can be reused on the same frame. (default: false)
  75281. * @param textureType Type of textures used when performing the post process. (default: 0)
  75282. * @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)
  75283. */
  75284. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75285. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75286. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75287. if (defines === void 0) { defines = ""; }
  75288. if (blockCompilation === void 0) { blockCompilation = false; }
  75289. 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;
  75290. _this.direction = direction;
  75291. _this.blockCompilation = blockCompilation;
  75292. _this._packedFloat = false;
  75293. _this._staticDefines = "";
  75294. _this._staticDefines = defines;
  75295. _this.onApplyObservable.add(function (effect) {
  75296. if (_this._outputTexture) {
  75297. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75298. }
  75299. else {
  75300. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75301. }
  75302. });
  75303. _this.kernel = kernel;
  75304. return _this;
  75305. }
  75306. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75307. /**
  75308. * Gets the length in pixels of the blur sample region
  75309. */
  75310. get: function () {
  75311. return this._idealKernel;
  75312. },
  75313. /**
  75314. * Sets the length in pixels of the blur sample region
  75315. */
  75316. set: function (v) {
  75317. if (this._idealKernel === v) {
  75318. return;
  75319. }
  75320. v = Math.max(v, 1);
  75321. this._idealKernel = v;
  75322. this._kernel = this._nearestBestKernel(v);
  75323. if (!this.blockCompilation) {
  75324. this._updateParameters();
  75325. }
  75326. },
  75327. enumerable: true,
  75328. configurable: true
  75329. });
  75330. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75331. /**
  75332. * Gets wether or not the blur is unpacking/repacking floats
  75333. */
  75334. get: function () {
  75335. return this._packedFloat;
  75336. },
  75337. /**
  75338. * Sets wether or not the blur needs to unpack/repack floats
  75339. */
  75340. set: function (v) {
  75341. if (this._packedFloat === v) {
  75342. return;
  75343. }
  75344. this._packedFloat = v;
  75345. if (!this.blockCompilation) {
  75346. this._updateParameters();
  75347. }
  75348. },
  75349. enumerable: true,
  75350. configurable: true
  75351. });
  75352. /**
  75353. * Updates the effect with the current post process compile time values and recompiles the shader.
  75354. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75355. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75356. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75357. * @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
  75358. * @param onCompiled Called when the shader has been compiled.
  75359. * @param onError Called if there is an error when compiling a shader.
  75360. */
  75361. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75362. if (defines === void 0) { defines = null; }
  75363. if (uniforms === void 0) { uniforms = null; }
  75364. if (samplers === void 0) { samplers = null; }
  75365. this._updateParameters(onCompiled, onError);
  75366. };
  75367. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75368. // Generate sampling offsets and weights
  75369. var N = this._kernel;
  75370. var centerIndex = (N - 1) / 2;
  75371. // Generate Gaussian sampling weights over kernel
  75372. var offsets = [];
  75373. var weights = [];
  75374. var totalWeight = 0;
  75375. for (var i = 0; i < N; i++) {
  75376. var u = i / (N - 1);
  75377. var w = this._gaussianWeight(u * 2.0 - 1);
  75378. offsets[i] = (i - centerIndex);
  75379. weights[i] = w;
  75380. totalWeight += w;
  75381. }
  75382. // Normalize weights
  75383. for (var i = 0; i < weights.length; i++) {
  75384. weights[i] /= totalWeight;
  75385. }
  75386. // Optimize: combine samples to take advantage of hardware linear sampling
  75387. // Walk from left to center, combining pairs (symmetrically)
  75388. var linearSamplingWeights = [];
  75389. var linearSamplingOffsets = [];
  75390. var linearSamplingMap = [];
  75391. for (var i = 0; i <= centerIndex; i += 2) {
  75392. var j = Math.min(i + 1, Math.floor(centerIndex));
  75393. var singleCenterSample = i === j;
  75394. if (singleCenterSample) {
  75395. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75396. }
  75397. else {
  75398. var sharedCell = j === centerIndex;
  75399. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75400. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75401. if (offsetLinear === 0) {
  75402. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75403. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75404. }
  75405. else {
  75406. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75407. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75408. }
  75409. }
  75410. }
  75411. for (var i = 0; i < linearSamplingMap.length; i++) {
  75412. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75413. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75414. }
  75415. // Replace with optimized
  75416. offsets = linearSamplingOffsets;
  75417. weights = linearSamplingWeights;
  75418. // Generate shaders
  75419. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75420. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75421. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75422. var defines = "";
  75423. defines += this._staticDefines;
  75424. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75425. if (this._staticDefines.indexOf("DOF") != -1) {
  75426. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75427. varyingCount--;
  75428. }
  75429. for (var i = 0; i < varyingCount; i++) {
  75430. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75431. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75432. }
  75433. var depCount = 0;
  75434. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75435. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75436. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75437. depCount++;
  75438. }
  75439. if (this.packedFloat) {
  75440. defines += "#define PACKEDFLOAT 1";
  75441. }
  75442. this.blockCompilation = false;
  75443. _super.prototype.updateEffect.call(this, defines, null, null, {
  75444. varyingCount: varyingCount,
  75445. depCount: depCount
  75446. }, onCompiled, onError);
  75447. };
  75448. /**
  75449. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75450. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75451. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75452. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75453. * The gaps between physical kernels are compensated for in the weighting of the samples
  75454. * @param idealKernel Ideal blur kernel.
  75455. * @return Nearest best kernel.
  75456. */
  75457. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75458. var v = Math.round(idealKernel);
  75459. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75460. var k = _a[_i];
  75461. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75462. return Math.max(k, 3);
  75463. }
  75464. }
  75465. return Math.max(v, 3);
  75466. };
  75467. /**
  75468. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75469. * @param x The point on the Gaussian distribution to sample.
  75470. * @return the value of the Gaussian function at x.
  75471. */
  75472. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75473. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75474. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75475. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75476. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75477. // truncated at around 1.3% of peak strength.
  75478. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75479. var sigma = (1 / 3);
  75480. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75481. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75482. var weight = (1.0 / denominator) * Math.exp(exponent);
  75483. return weight;
  75484. };
  75485. /**
  75486. * Generates a string that can be used as a floating point number in GLSL.
  75487. * @param x Value to print.
  75488. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75489. * @return GLSL float string.
  75490. */
  75491. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75492. if (decimalFigures === void 0) { decimalFigures = 8; }
  75493. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75494. };
  75495. return BlurPostProcess;
  75496. }(BABYLON.PostProcess));
  75497. BABYLON.BlurPostProcess = BlurPostProcess;
  75498. })(BABYLON || (BABYLON = {}));
  75499. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75500. var BABYLON;
  75501. (function (BABYLON) {
  75502. /**
  75503. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75504. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75505. * based on samples that have a large difference in distance than the center pixel.
  75506. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75507. */
  75508. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75509. __extends(DepthOfFieldBlurPostProcess, _super);
  75510. /**
  75511. * Creates a new instance CircleOfConfusionPostProcess
  75512. * @param name The name of the effect.
  75513. * @param scene The scene the effect belongs to.
  75514. * @param direction The direction the blur should be applied.
  75515. * @param kernel The size of the kernel used to blur.
  75516. * @param options The required width/height ratio to downsize to before computing the render pass.
  75517. * @param camera The camera to apply the render pass to.
  75518. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75519. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75520. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75521. * @param engine The engine which the post process will be applied. (default: current engine)
  75522. * @param reusable If the post process can be reused on the same frame. (default: false)
  75523. * @param textureType Type of textures used when performing the post process. (default: 0)
  75524. * @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)
  75525. */
  75526. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75527. if (imageToBlur === void 0) { imageToBlur = null; }
  75528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75529. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75530. if (blockCompilation === void 0) { blockCompilation = false; }
  75531. 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;
  75532. _this.direction = direction;
  75533. _this.onApplyObservable.add(function (effect) {
  75534. if (imageToBlur != null) {
  75535. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75536. }
  75537. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75538. if (scene.activeCamera) {
  75539. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75540. }
  75541. });
  75542. return _this;
  75543. }
  75544. return DepthOfFieldBlurPostProcess;
  75545. }(BABYLON.BlurPostProcess));
  75546. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75547. })(BABYLON || (BABYLON = {}));
  75548. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75549. var BABYLON;
  75550. (function (BABYLON) {
  75551. /**
  75552. * Options to be set when merging outputs from the default pipeline.
  75553. */
  75554. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75555. function DepthOfFieldMergePostProcessOptions() {
  75556. }
  75557. return DepthOfFieldMergePostProcessOptions;
  75558. }());
  75559. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75560. /**
  75561. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75562. */
  75563. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75564. __extends(DepthOfFieldMergePostProcess, _super);
  75565. /**
  75566. * Creates a new instance of DepthOfFieldMergePostProcess
  75567. * @param name The name of the effect.
  75568. * @param originalFromInput Post process which's input will be used for the merge.
  75569. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75570. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75571. * @param options The required width/height ratio to downsize to before computing the render pass.
  75572. * @param camera The camera to apply the render pass to.
  75573. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75574. * @param engine The engine which the post process will be applied. (default: current engine)
  75575. * @param reusable If the post process can be reused on the same frame. (default: false)
  75576. * @param textureType Type of textures used when performing the post process. (default: 0)
  75577. * @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)
  75578. */
  75579. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75580. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75581. if (blockCompilation === void 0) { blockCompilation = false; }
  75582. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75583. _this.blurSteps = blurSteps;
  75584. _this.onApplyObservable.add(function (effect) {
  75585. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75586. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75587. blurSteps.forEach(function (step, index) {
  75588. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75589. });
  75590. });
  75591. if (!blockCompilation) {
  75592. _this.updateEffect();
  75593. }
  75594. return _this;
  75595. }
  75596. /**
  75597. * Updates the effect with the current post process compile time values and recompiles the shader.
  75598. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75599. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75600. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75601. * @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
  75602. * @param onCompiled Called when the shader has been compiled.
  75603. * @param onError Called if there is an error when compiling a shader.
  75604. */
  75605. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75606. if (defines === void 0) { defines = null; }
  75607. if (uniforms === void 0) { uniforms = null; }
  75608. if (samplers === void 0) { samplers = null; }
  75609. if (!defines) {
  75610. defines = "";
  75611. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75612. }
  75613. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75614. };
  75615. return DepthOfFieldMergePostProcess;
  75616. }(BABYLON.PostProcess));
  75617. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75618. })(BABYLON || (BABYLON = {}));
  75619. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75620. var BABYLON;
  75621. (function (BABYLON) {
  75622. /**
  75623. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75624. */
  75625. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75626. __extends(CircleOfConfusionPostProcess, _super);
  75627. /**
  75628. * Creates a new instance CircleOfConfusionPostProcess
  75629. * @param name The name of the effect.
  75630. * @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.
  75631. * @param options The required width/height ratio to downsize to before computing the render pass.
  75632. * @param camera The camera to apply the render pass to.
  75633. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75634. * @param engine The engine which the post process will be applied. (default: current engine)
  75635. * @param reusable If the post process can be reused on the same frame. (default: false)
  75636. * @param textureType Type of textures used when performing the post process. (default: 0)
  75637. * @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)
  75638. */
  75639. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75640. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75641. if (blockCompilation === void 0) { blockCompilation = false; }
  75642. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75643. /**
  75644. * 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.
  75645. */
  75646. _this.lensSize = 50;
  75647. /**
  75648. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75649. */
  75650. _this.fStop = 1.4;
  75651. /**
  75652. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75653. */
  75654. _this.focusDistance = 2000;
  75655. /**
  75656. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75657. */
  75658. _this.focalLength = 50;
  75659. _this._depthTexture = null;
  75660. _this._depthTexture = depthTexture;
  75661. _this.onApplyObservable.add(function (effect) {
  75662. if (!_this._depthTexture) {
  75663. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75664. return;
  75665. }
  75666. effect.setTexture("depthSampler", _this._depthTexture);
  75667. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75668. var aperture = _this.lensSize / _this.fStop;
  75669. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75670. effect.setFloat('focusDistance', _this.focusDistance);
  75671. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75672. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75673. });
  75674. return _this;
  75675. }
  75676. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75677. /**
  75678. * 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.
  75679. */
  75680. set: function (value) {
  75681. this._depthTexture = value;
  75682. },
  75683. enumerable: true,
  75684. configurable: true
  75685. });
  75686. return CircleOfConfusionPostProcess;
  75687. }(BABYLON.PostProcess));
  75688. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75689. })(BABYLON || (BABYLON = {}));
  75690. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75691. var BABYLON;
  75692. (function (BABYLON) {
  75693. /**
  75694. * Specifies the level of max blur that should be applied when using the depth of field effect
  75695. */
  75696. var DepthOfFieldEffectBlurLevel;
  75697. (function (DepthOfFieldEffectBlurLevel) {
  75698. /**
  75699. * Subtle blur
  75700. */
  75701. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75702. /**
  75703. * Medium blur
  75704. */
  75705. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75706. /**
  75707. * Large blur
  75708. */
  75709. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75710. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75711. ;
  75712. /**
  75713. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75714. */
  75715. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75716. __extends(DepthOfFieldEffect, _super);
  75717. /**
  75718. * Creates a new instance DepthOfFieldEffect
  75719. * @param scene The scene the effect belongs to.
  75720. * @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.
  75721. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75722. * @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)
  75723. */
  75724. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75725. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75726. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75727. if (blockCompilation === void 0) { blockCompilation = false; }
  75728. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75729. return _this._effects;
  75730. }, true) || this;
  75731. /**
  75732. * Internal post processes in depth of field effect
  75733. */
  75734. _this._effects = [];
  75735. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75736. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75737. // 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)
  75738. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75739. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75740. _this._depthOfFieldBlurY = [];
  75741. _this._depthOfFieldBlurX = [];
  75742. var blurCount = 1;
  75743. var kernelSize = 15;
  75744. switch (blurLevel) {
  75745. case DepthOfFieldEffectBlurLevel.High: {
  75746. blurCount = 3;
  75747. kernelSize = 51;
  75748. break;
  75749. }
  75750. case DepthOfFieldEffectBlurLevel.Medium: {
  75751. blurCount = 2;
  75752. kernelSize = 31;
  75753. break;
  75754. }
  75755. default: {
  75756. kernelSize = 15;
  75757. blurCount = 1;
  75758. break;
  75759. }
  75760. }
  75761. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75762. var ratio = 1.0;
  75763. for (var i = 0; i < blurCount; i++) {
  75764. 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);
  75765. blurY.autoClear = false;
  75766. ratio = 0.75 / Math.pow(2, i);
  75767. 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);
  75768. blurX.autoClear = false;
  75769. _this._depthOfFieldBlurY.push(blurY);
  75770. _this._depthOfFieldBlurX.push(blurX);
  75771. }
  75772. // Set all post processes on the effect.
  75773. _this._effects = [_this._circleOfConfusion];
  75774. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75775. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75776. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75777. }
  75778. // Merge blurred images with original image based on circleOfConfusion
  75779. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75780. _this._dofMerge.autoClear = false;
  75781. _this._effects.push(_this._dofMerge);
  75782. return _this;
  75783. }
  75784. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75785. get: function () {
  75786. return this._circleOfConfusion.focalLength;
  75787. },
  75788. /**
  75789. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75790. */
  75791. set: function (value) {
  75792. this._circleOfConfusion.focalLength = value;
  75793. },
  75794. enumerable: true,
  75795. configurable: true
  75796. });
  75797. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75798. get: function () {
  75799. return this._circleOfConfusion.fStop;
  75800. },
  75801. /**
  75802. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75803. */
  75804. set: function (value) {
  75805. this._circleOfConfusion.fStop = value;
  75806. },
  75807. enumerable: true,
  75808. configurable: true
  75809. });
  75810. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75811. get: function () {
  75812. return this._circleOfConfusion.focusDistance;
  75813. },
  75814. /**
  75815. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75816. */
  75817. set: function (value) {
  75818. this._circleOfConfusion.focusDistance = value;
  75819. },
  75820. enumerable: true,
  75821. configurable: true
  75822. });
  75823. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75824. get: function () {
  75825. return this._circleOfConfusion.lensSize;
  75826. },
  75827. /**
  75828. * 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.
  75829. */
  75830. set: function (value) {
  75831. this._circleOfConfusion.lensSize = value;
  75832. },
  75833. enumerable: true,
  75834. configurable: true
  75835. });
  75836. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75837. /**
  75838. * 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.
  75839. */
  75840. set: function (value) {
  75841. this._circleOfConfusion.depthTexture = value;
  75842. },
  75843. enumerable: true,
  75844. configurable: true
  75845. });
  75846. /**
  75847. * Disposes each of the internal effects for a given camera.
  75848. * @param camera The camera to dispose the effect on.
  75849. */
  75850. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75851. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75852. this._effects[effectIndex].dispose(camera);
  75853. }
  75854. };
  75855. /**
  75856. * Internal
  75857. */
  75858. DepthOfFieldEffect.prototype._updateEffects = function () {
  75859. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75860. this._effects[effectIndex].updateEffect();
  75861. }
  75862. };
  75863. /**
  75864. * Internal
  75865. * @returns if all the contained post processes are ready.
  75866. */
  75867. DepthOfFieldEffect.prototype._isReady = function () {
  75868. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75869. if (!this._effects[effectIndex].isReady()) {
  75870. return false;
  75871. }
  75872. }
  75873. return true;
  75874. };
  75875. return DepthOfFieldEffect;
  75876. }(BABYLON.PostProcessRenderEffect));
  75877. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75878. })(BABYLON || (BABYLON = {}));
  75879. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75880. var BABYLON;
  75881. (function (BABYLON) {
  75882. /**
  75883. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75884. */
  75885. var BloomMergePostProcess = /** @class */ (function (_super) {
  75886. __extends(BloomMergePostProcess, _super);
  75887. /**
  75888. * Creates a new instance of @see BloomMergePostProcess
  75889. * @param name The name of the effect.
  75890. * @param originalFromInput Post process which's input will be used for the merge.
  75891. * @param blurred Blurred highlights post process which's output will be used.
  75892. * @param weight Weight of the bloom to be added to the original input.
  75893. * @param options The required width/height ratio to downsize to before computing the render pass.
  75894. * @param camera The camera to apply the render pass to.
  75895. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75896. * @param engine The engine which the post process will be applied. (default: current engine)
  75897. * @param reusable If the post process can be reused on the same frame. (default: false)
  75898. * @param textureType Type of textures used when performing the post process. (default: 0)
  75899. * @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)
  75900. */
  75901. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75902. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75903. if (blockCompilation === void 0) { blockCompilation = false; }
  75904. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75905. _this.weight = weight;
  75906. _this.onApplyObservable.add(function (effect) {
  75907. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75908. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75909. effect.setFloat("bloomWeight", _this.weight);
  75910. });
  75911. if (!blockCompilation) {
  75912. _this.updateEffect();
  75913. }
  75914. return _this;
  75915. }
  75916. return BloomMergePostProcess;
  75917. }(BABYLON.PostProcess));
  75918. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75919. })(BABYLON || (BABYLON = {}));
  75920. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75921. var BABYLON;
  75922. (function (BABYLON) {
  75923. /**
  75924. * 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.
  75925. */
  75926. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75927. __extends(ExtractHighlightsPostProcess, _super);
  75928. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75929. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75930. if (blockCompilation === void 0) { blockCompilation = false; }
  75931. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75932. /**
  75933. * The luminance threshold, pixels below this value will be set to black.
  75934. */
  75935. _this.threshold = 0.9;
  75936. /**
  75937. * Internal
  75938. */
  75939. _this._exposure = 1;
  75940. /**
  75941. * Post process which has the input texture to be used when performing highlight extraction
  75942. */
  75943. _this._inputPostProcess = null;
  75944. _this.onApplyObservable.add(function (effect) {
  75945. if (_this._inputPostProcess) {
  75946. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75947. }
  75948. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75949. effect.setFloat('exposure', _this._exposure);
  75950. });
  75951. return _this;
  75952. }
  75953. return ExtractHighlightsPostProcess;
  75954. }(BABYLON.PostProcess));
  75955. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75956. })(BABYLON || (BABYLON = {}));
  75957. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75958. var BABYLON;
  75959. (function (BABYLON) {
  75960. /**
  75961. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75962. */
  75963. var BloomEffect = /** @class */ (function (_super) {
  75964. __extends(BloomEffect, _super);
  75965. /**
  75966. * Creates a new instance of @see BloomEffect
  75967. * @param scene The scene the effect belongs to.
  75968. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75969. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75970. * @param bloomWeight The the strength of bloom.
  75971. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75972. * @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)
  75973. */
  75974. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75975. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75976. if (blockCompilation === void 0) { blockCompilation = false; }
  75977. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75978. return _this._effects;
  75979. }, true) || this;
  75980. _this.bloomScale = bloomScale;
  75981. /**
  75982. * Internal
  75983. */
  75984. _this._effects = [];
  75985. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75986. _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);
  75987. _this._blurX.alwaysForcePOT = true;
  75988. _this._blurX.autoClear = false;
  75989. _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);
  75990. _this._blurY.alwaysForcePOT = true;
  75991. _this._blurY.autoClear = false;
  75992. _this.kernel = bloomKernel;
  75993. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75994. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75995. _this._merge.autoClear = false;
  75996. _this._effects.push(_this._merge);
  75997. return _this;
  75998. }
  75999. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76000. /**
  76001. * The luminance threshold to find bright areas of the image to bloom.
  76002. */
  76003. get: function () {
  76004. return this._downscale.threshold;
  76005. },
  76006. set: function (value) {
  76007. this._downscale.threshold = value;
  76008. },
  76009. enumerable: true,
  76010. configurable: true
  76011. });
  76012. Object.defineProperty(BloomEffect.prototype, "weight", {
  76013. /**
  76014. * The strength of the bloom.
  76015. */
  76016. get: function () {
  76017. return this._merge.weight;
  76018. },
  76019. set: function (value) {
  76020. this._merge.weight = value;
  76021. },
  76022. enumerable: true,
  76023. configurable: true
  76024. });
  76025. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76026. /**
  76027. * Specifies the size of the bloom blur kernel, relative to the final output size
  76028. */
  76029. get: function () {
  76030. return this._blurX.kernel / this.bloomScale;
  76031. },
  76032. set: function (value) {
  76033. this._blurX.kernel = value * this.bloomScale;
  76034. this._blurY.kernel = value * this.bloomScale;
  76035. },
  76036. enumerable: true,
  76037. configurable: true
  76038. });
  76039. /**
  76040. * Disposes each of the internal effects for a given camera.
  76041. * @param camera The camera to dispose the effect on.
  76042. */
  76043. BloomEffect.prototype.disposeEffects = function (camera) {
  76044. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76045. this._effects[effectIndex].dispose(camera);
  76046. }
  76047. };
  76048. /**
  76049. * Internal
  76050. */
  76051. BloomEffect.prototype._updateEffects = function () {
  76052. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76053. this._effects[effectIndex].updateEffect();
  76054. }
  76055. };
  76056. /**
  76057. * Internal
  76058. * @returns if all the contained post processes are ready.
  76059. */
  76060. BloomEffect.prototype._isReady = function () {
  76061. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76062. if (!this._effects[effectIndex].isReady()) {
  76063. return false;
  76064. }
  76065. }
  76066. return true;
  76067. };
  76068. return BloomEffect;
  76069. }(BABYLON.PostProcessRenderEffect));
  76070. BABYLON.BloomEffect = BloomEffect;
  76071. })(BABYLON || (BABYLON = {}));
  76072. //# sourceMappingURL=babylon.bloomEffect.js.map
  76073. var BABYLON;
  76074. (function (BABYLON) {
  76075. /**
  76076. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76077. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76078. */
  76079. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76080. __extends(DefaultRenderingPipeline, _super);
  76081. /**
  76082. * @constructor
  76083. * @param {string} name - The rendering pipeline name (default: "")
  76084. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76085. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76086. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76087. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76088. */
  76089. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76090. if (name === void 0) { name = ""; }
  76091. if (hdr === void 0) { hdr = true; }
  76092. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76093. if (automaticBuild === void 0) { automaticBuild = true; }
  76094. var _this = _super.call(this, scene.getEngine(), name) || this;
  76095. _this._camerasToBeAttached = [];
  76096. /**
  76097. * ID of the sharpen post process,
  76098. */
  76099. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76100. /**
  76101. * ID of the image processing post process;
  76102. */
  76103. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76104. /**
  76105. * ID of the Fast Approximate Anti-Aliasing post process;
  76106. */
  76107. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76108. /**
  76109. * ID of the chromatic aberration post process,
  76110. */
  76111. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76112. /**
  76113. * ID of the grain post process
  76114. */
  76115. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76116. /**
  76117. * Glow post process which adds a glow to emmisive areas of the image
  76118. */
  76119. _this._glowLayer = null;
  76120. /**
  76121. * Animations which can be used to tweak settings over a period of time
  76122. */
  76123. _this.animations = [];
  76124. _this._imageProcessingConfigurationObserver = null;
  76125. // Values
  76126. _this._sharpenEnabled = false;
  76127. _this._bloomEnabled = false;
  76128. _this._depthOfFieldEnabled = false;
  76129. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76130. _this._fxaaEnabled = false;
  76131. _this._imageProcessingEnabled = true;
  76132. _this._bloomScale = 0.5;
  76133. _this._chromaticAberrationEnabled = false;
  76134. _this._grainEnabled = false;
  76135. _this._buildAllowed = true;
  76136. _this._resizeObserver = null;
  76137. _this._hardwareScaleLevel = 1.0;
  76138. _this._bloomKernel = 64;
  76139. /**
  76140. * Specifies the weight of the bloom in the final rendering
  76141. */
  76142. _this._bloomWeight = 0.15;
  76143. /**
  76144. * Specifies the luma threshold for the area that will be blurred by the bloom
  76145. */
  76146. _this._bloomThreshold = 0.9;
  76147. _this._samples = 1;
  76148. _this._hasCleared = false;
  76149. _this._prevPostProcess = null;
  76150. _this._prevPrevPostProcess = null;
  76151. _this._cameras = cameras || scene.cameras;
  76152. _this._camerasToBeAttached = _this._cameras.slice();
  76153. _this._buildAllowed = automaticBuild;
  76154. // Initialize
  76155. _this._scene = scene;
  76156. var caps = _this._scene.getEngine().getCaps();
  76157. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76158. // Misc
  76159. if (_this._hdr) {
  76160. if (caps.textureHalfFloatRender) {
  76161. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76162. }
  76163. else if (caps.textureFloatRender) {
  76164. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76165. }
  76166. }
  76167. else {
  76168. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76169. }
  76170. // Attach
  76171. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76172. var engine = _this._scene.getEngine();
  76173. // Create post processes before hand so they can be modified before enabled.
  76174. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76175. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76176. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76177. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76178. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76179. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76180. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76181. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76182. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76183. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76184. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76185. _this.bloomKernel = _this.bloomKernel;
  76186. });
  76187. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76188. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76189. });
  76190. _this._buildPipeline();
  76191. return _this;
  76192. }
  76193. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76194. get: function () {
  76195. return this._sharpenEnabled;
  76196. },
  76197. /**
  76198. * Enable or disable the sharpen process from the pipeline
  76199. */
  76200. set: function (enabled) {
  76201. if (this._sharpenEnabled === enabled) {
  76202. return;
  76203. }
  76204. this._sharpenEnabled = enabled;
  76205. this._buildPipeline();
  76206. },
  76207. enumerable: true,
  76208. configurable: true
  76209. });
  76210. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76211. /**
  76212. * Specifies the size of the bloom blur kernel, relative to the final output size
  76213. */
  76214. get: function () {
  76215. return this._bloomKernel;
  76216. },
  76217. set: function (value) {
  76218. this._bloomKernel = value;
  76219. this.bloom.kernel = value / this._hardwareScaleLevel;
  76220. },
  76221. enumerable: true,
  76222. configurable: true
  76223. });
  76224. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76225. get: function () {
  76226. return this._bloomWeight;
  76227. },
  76228. /**
  76229. * The strength of the bloom.
  76230. */
  76231. set: function (value) {
  76232. if (this._bloomWeight === value) {
  76233. return;
  76234. }
  76235. this.bloom.weight = value;
  76236. this._bloomWeight = value;
  76237. },
  76238. enumerable: true,
  76239. configurable: true
  76240. });
  76241. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76242. get: function () {
  76243. return this._bloomThreshold;
  76244. },
  76245. /**
  76246. * The strength of the bloom.
  76247. */
  76248. set: function (value) {
  76249. if (this._bloomThreshold === value) {
  76250. return;
  76251. }
  76252. this.bloom.threshold = value;
  76253. this._bloomThreshold = value;
  76254. },
  76255. enumerable: true,
  76256. configurable: true
  76257. });
  76258. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76259. get: function () {
  76260. return this._bloomScale;
  76261. },
  76262. /**
  76263. * The scale of the bloom, lower value will provide better performance.
  76264. */
  76265. set: function (value) {
  76266. if (this._bloomScale === value) {
  76267. return;
  76268. }
  76269. this._bloomScale = value;
  76270. // recreate bloom and dispose old as this setting is not dynamic
  76271. this._rebuildBloom();
  76272. this._buildPipeline();
  76273. },
  76274. enumerable: true,
  76275. configurable: true
  76276. });
  76277. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76278. get: function () {
  76279. return this._bloomEnabled;
  76280. },
  76281. /**
  76282. * Enable or disable the bloom from the pipeline
  76283. */
  76284. set: function (enabled) {
  76285. if (this._bloomEnabled === enabled) {
  76286. return;
  76287. }
  76288. this._bloomEnabled = enabled;
  76289. this._buildPipeline();
  76290. },
  76291. enumerable: true,
  76292. configurable: true
  76293. });
  76294. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76295. // recreate bloom and dispose old as this setting is not dynamic
  76296. var oldBloom = this.bloom;
  76297. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76298. this.bloom.threshold = oldBloom.threshold;
  76299. for (var i = 0; i < this._cameras.length; i++) {
  76300. oldBloom.disposeEffects(this._cameras[i]);
  76301. }
  76302. };
  76303. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76304. /**
  76305. * If the depth of field is enabled.
  76306. */
  76307. get: function () {
  76308. return this._depthOfFieldEnabled;
  76309. },
  76310. set: function (enabled) {
  76311. if (this._depthOfFieldEnabled === enabled) {
  76312. return;
  76313. }
  76314. this._depthOfFieldEnabled = enabled;
  76315. this._buildPipeline();
  76316. },
  76317. enumerable: true,
  76318. configurable: true
  76319. });
  76320. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76321. /**
  76322. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76323. */
  76324. get: function () {
  76325. return this._depthOfFieldBlurLevel;
  76326. },
  76327. set: function (value) {
  76328. if (this._depthOfFieldBlurLevel === value) {
  76329. return;
  76330. }
  76331. this._depthOfFieldBlurLevel = value;
  76332. // recreate dof and dispose old as this setting is not dynamic
  76333. var oldDof = this.depthOfField;
  76334. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76335. this.depthOfField.focalLength = oldDof.focalLength;
  76336. this.depthOfField.focusDistance = oldDof.focusDistance;
  76337. this.depthOfField.fStop = oldDof.fStop;
  76338. this.depthOfField.lensSize = oldDof.lensSize;
  76339. for (var i = 0; i < this._cameras.length; i++) {
  76340. oldDof.disposeEffects(this._cameras[i]);
  76341. }
  76342. this._buildPipeline();
  76343. },
  76344. enumerable: true,
  76345. configurable: true
  76346. });
  76347. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76348. get: function () {
  76349. return this._fxaaEnabled;
  76350. },
  76351. /**
  76352. * If the anti aliasing is enabled.
  76353. */
  76354. set: function (enabled) {
  76355. if (this._fxaaEnabled === enabled) {
  76356. return;
  76357. }
  76358. this._fxaaEnabled = enabled;
  76359. this._buildPipeline();
  76360. },
  76361. enumerable: true,
  76362. configurable: true
  76363. });
  76364. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76365. get: function () {
  76366. return this._samples;
  76367. },
  76368. /**
  76369. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76370. */
  76371. set: function (sampleCount) {
  76372. if (this._samples === sampleCount) {
  76373. return;
  76374. }
  76375. this._samples = sampleCount;
  76376. this._buildPipeline();
  76377. },
  76378. enumerable: true,
  76379. configurable: true
  76380. });
  76381. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76382. get: function () {
  76383. return this._imageProcessingEnabled;
  76384. },
  76385. /**
  76386. * If image processing is enabled.
  76387. */
  76388. set: function (enabled) {
  76389. if (this._imageProcessingEnabled === enabled) {
  76390. return;
  76391. }
  76392. this._imageProcessingEnabled = enabled;
  76393. this._buildPipeline();
  76394. },
  76395. enumerable: true,
  76396. configurable: true
  76397. });
  76398. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76399. get: function () {
  76400. return this._glowLayer == null;
  76401. },
  76402. /**
  76403. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76404. */
  76405. set: function (enabled) {
  76406. if (enabled && !this._glowLayer) {
  76407. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76408. }
  76409. else if (!enabled && this._glowLayer) {
  76410. this._glowLayer.dispose();
  76411. this._glowLayer = null;
  76412. }
  76413. },
  76414. enumerable: true,
  76415. configurable: true
  76416. });
  76417. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76418. get: function () {
  76419. return this._chromaticAberrationEnabled;
  76420. },
  76421. /**
  76422. * Enable or disable the chromaticAberration process from the pipeline
  76423. */
  76424. set: function (enabled) {
  76425. if (this._chromaticAberrationEnabled === enabled) {
  76426. return;
  76427. }
  76428. this._chromaticAberrationEnabled = enabled;
  76429. this._buildPipeline();
  76430. },
  76431. enumerable: true,
  76432. configurable: true
  76433. });
  76434. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76435. get: function () {
  76436. return this._grainEnabled;
  76437. },
  76438. /**
  76439. * Enable or disable the grain process from the pipeline
  76440. */
  76441. set: function (enabled) {
  76442. if (this._grainEnabled === enabled) {
  76443. return;
  76444. }
  76445. this._grainEnabled = enabled;
  76446. this._buildPipeline();
  76447. },
  76448. enumerable: true,
  76449. configurable: true
  76450. });
  76451. /**
  76452. * Force the compilation of the entire pipeline.
  76453. */
  76454. DefaultRenderingPipeline.prototype.prepare = function () {
  76455. var previousState = this._buildAllowed;
  76456. this._buildAllowed = true;
  76457. this._buildPipeline();
  76458. this._buildAllowed = previousState;
  76459. };
  76460. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76461. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76462. if (this._hasCleared) {
  76463. postProcess.autoClear = false;
  76464. }
  76465. else {
  76466. postProcess.autoClear = true;
  76467. this._scene.autoClear = false;
  76468. this._hasCleared = true;
  76469. }
  76470. if (!skipTextureSharing) {
  76471. if (this._prevPrevPostProcess) {
  76472. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76473. }
  76474. else {
  76475. postProcess.useOwnOutput();
  76476. }
  76477. if (this._prevPostProcess) {
  76478. this._prevPrevPostProcess = this._prevPostProcess;
  76479. }
  76480. this._prevPostProcess = postProcess;
  76481. }
  76482. };
  76483. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76484. var _this = this;
  76485. if (!this._buildAllowed) {
  76486. return;
  76487. }
  76488. this._scene.autoClear = true;
  76489. var engine = this._scene.getEngine();
  76490. this._disposePostProcesses();
  76491. if (this._cameras !== null) {
  76492. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76493. // get back cameras to be used to reattach pipeline
  76494. this._cameras = this._camerasToBeAttached.slice();
  76495. }
  76496. this._reset();
  76497. this._prevPostProcess = null;
  76498. this._prevPrevPostProcess = null;
  76499. this._hasCleared = false;
  76500. if (this.depthOfFieldEnabled) {
  76501. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76502. this.depthOfField.depthTexture = depthTexture;
  76503. if (!this.depthOfField._isReady()) {
  76504. this.depthOfField._updateEffects();
  76505. }
  76506. this.addEffect(this.depthOfField);
  76507. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76508. }
  76509. if (this.bloomEnabled) {
  76510. if (!this.bloom._isReady()) {
  76511. this.bloom._updateEffects();
  76512. }
  76513. this.addEffect(this.bloom);
  76514. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76515. }
  76516. if (this._imageProcessingEnabled) {
  76517. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76518. if (this._hdr) {
  76519. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76520. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76521. }
  76522. else {
  76523. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76524. }
  76525. }
  76526. if (this.sharpenEnabled) {
  76527. if (!this.sharpen.isReady()) {
  76528. this.sharpen.updateEffect();
  76529. }
  76530. this.addEffect(this._sharpenEffect);
  76531. this._setAutoClearAndTextureSharing(this.sharpen);
  76532. }
  76533. if (this.grainEnabled) {
  76534. if (!this.grain.isReady()) {
  76535. this.grain.updateEffect();
  76536. }
  76537. this.addEffect(this._grainEffect);
  76538. this._setAutoClearAndTextureSharing(this.grain);
  76539. }
  76540. if (this.chromaticAberrationEnabled) {
  76541. if (!this.chromaticAberration.isReady()) {
  76542. this.chromaticAberration.updateEffect();
  76543. }
  76544. this.addEffect(this._chromaticAberrationEffect);
  76545. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76546. }
  76547. if (this.fxaaEnabled) {
  76548. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76549. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76550. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76551. }
  76552. if (this._cameras !== null) {
  76553. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76554. }
  76555. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76556. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76557. }
  76558. };
  76559. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76560. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76561. for (var i = 0; i < this._cameras.length; i++) {
  76562. var camera = this._cameras[i];
  76563. if (this.imageProcessing) {
  76564. this.imageProcessing.dispose(camera);
  76565. }
  76566. if (this.fxaa) {
  76567. this.fxaa.dispose(camera);
  76568. }
  76569. // These are created in the constructor and should not be disposed on every pipeline change
  76570. if (disposeNonRecreated) {
  76571. if (this.sharpen) {
  76572. this.sharpen.dispose(camera);
  76573. }
  76574. if (this.depthOfField) {
  76575. this.depthOfField.disposeEffects(camera);
  76576. }
  76577. if (this.bloom) {
  76578. this.bloom.disposeEffects(camera);
  76579. }
  76580. if (this.chromaticAberration) {
  76581. this.chromaticAberration.dispose(camera);
  76582. }
  76583. if (this.grain) {
  76584. this.grain.dispose(camera);
  76585. }
  76586. if (this._glowLayer) {
  76587. this._glowLayer.dispose();
  76588. }
  76589. }
  76590. }
  76591. this.imageProcessing = null;
  76592. this.fxaa = null;
  76593. if (disposeNonRecreated) {
  76594. this.sharpen = null;
  76595. this._sharpenEffect = null;
  76596. this.depthOfField = null;
  76597. this.bloom = null;
  76598. this.chromaticAberration = null;
  76599. this._chromaticAberrationEffect = null;
  76600. this.grain = null;
  76601. this._grainEffect = null;
  76602. this._glowLayer = null;
  76603. }
  76604. };
  76605. /**
  76606. * Adds a camera to the pipeline
  76607. * @param camera the camera to be added
  76608. */
  76609. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76610. this._camerasToBeAttached.push(camera);
  76611. this._buildPipeline();
  76612. };
  76613. /**
  76614. * Removes a camera from the pipeline
  76615. * @param camera the camera to remove
  76616. */
  76617. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76618. var index = this._camerasToBeAttached.indexOf(camera);
  76619. this._camerasToBeAttached.splice(index, 1);
  76620. this._buildPipeline();
  76621. };
  76622. /**
  76623. * Dispose of the pipeline and stop all post processes
  76624. */
  76625. DefaultRenderingPipeline.prototype.dispose = function () {
  76626. this._disposePostProcesses(true);
  76627. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76628. this._scene.autoClear = true;
  76629. if (this._resizeObserver) {
  76630. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76631. this._resizeObserver = null;
  76632. }
  76633. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76634. _super.prototype.dispose.call(this);
  76635. };
  76636. /**
  76637. * Serialize the rendering pipeline (Used when exporting)
  76638. * @returns the serialized object
  76639. */
  76640. DefaultRenderingPipeline.prototype.serialize = function () {
  76641. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76642. serializationObject.customType = "DefaultRenderingPipeline";
  76643. return serializationObject;
  76644. };
  76645. /**
  76646. * Parse the serialized pipeline
  76647. * @param source Source pipeline.
  76648. * @param scene The scene to load the pipeline to.
  76649. * @param rootUrl The URL of the serialized pipeline.
  76650. * @returns An instantiated pipeline from the serialized object.
  76651. */
  76652. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76653. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76654. };
  76655. __decorate([
  76656. BABYLON.serialize()
  76657. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76658. __decorate([
  76659. BABYLON.serialize()
  76660. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76661. __decorate([
  76662. BABYLON.serialize()
  76663. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76664. __decorate([
  76665. BABYLON.serialize()
  76666. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76667. __decorate([
  76668. BABYLON.serialize()
  76669. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76670. __decorate([
  76671. BABYLON.serialize()
  76672. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76673. __decorate([
  76674. BABYLON.serialize()
  76675. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76676. __decorate([
  76677. BABYLON.serialize()
  76678. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76679. __decorate([
  76680. BABYLON.serialize()
  76681. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76682. __decorate([
  76683. BABYLON.serialize()
  76684. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76685. __decorate([
  76686. BABYLON.serialize()
  76687. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76688. __decorate([
  76689. BABYLON.serialize()
  76690. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76691. __decorate([
  76692. BABYLON.serialize()
  76693. ], DefaultRenderingPipeline.prototype, "samples", null);
  76694. __decorate([
  76695. BABYLON.serialize()
  76696. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76697. __decorate([
  76698. BABYLON.serialize()
  76699. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76700. __decorate([
  76701. BABYLON.serialize()
  76702. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76703. __decorate([
  76704. BABYLON.serialize()
  76705. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76706. return DefaultRenderingPipeline;
  76707. }(BABYLON.PostProcessRenderPipeline));
  76708. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76709. })(BABYLON || (BABYLON = {}));
  76710. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76711. var BABYLON;
  76712. (function (BABYLON) {
  76713. /**
  76714. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76715. */
  76716. var GeometryBufferRenderer = /** @class */ (function () {
  76717. /**
  76718. * Creates a new G Buffer for the scene
  76719. * @param scene The scene the buffer belongs to
  76720. * @param ratio How big is the buffer related to the main canvas.
  76721. */
  76722. function GeometryBufferRenderer(scene, ratio) {
  76723. if (ratio === void 0) { ratio = 1; }
  76724. this._enablePosition = false;
  76725. this._scene = scene;
  76726. this._ratio = ratio;
  76727. // Render target
  76728. this._createRenderTargets();
  76729. }
  76730. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76731. /**
  76732. * Set the render list (meshes to be rendered) used in the G buffer.
  76733. */
  76734. set: function (meshes) {
  76735. this._multiRenderTarget.renderList = meshes;
  76736. },
  76737. enumerable: true,
  76738. configurable: true
  76739. });
  76740. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76741. /**
  76742. * Gets wether or not G buffer are supported by the running hardware.
  76743. * This requires draw buffer supports
  76744. */
  76745. get: function () {
  76746. return this._multiRenderTarget.isSupported;
  76747. },
  76748. enumerable: true,
  76749. configurable: true
  76750. });
  76751. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76752. /**
  76753. * Gets wether or not position are enabled for the G buffer.
  76754. */
  76755. get: function () {
  76756. return this._enablePosition;
  76757. },
  76758. /**
  76759. * Sets wether or not position are enabled for the G buffer.
  76760. */
  76761. set: function (enable) {
  76762. this._enablePosition = enable;
  76763. this.dispose();
  76764. this._createRenderTargets();
  76765. },
  76766. enumerable: true,
  76767. configurable: true
  76768. });
  76769. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76770. /**
  76771. * Gets the scene associated with the buffer.
  76772. */
  76773. get: function () {
  76774. return this._scene;
  76775. },
  76776. enumerable: true,
  76777. configurable: true
  76778. });
  76779. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76780. /**
  76781. * Gets the ratio used by the buffer during its creation.
  76782. * How big is the buffer related to the main canvas.
  76783. */
  76784. get: function () {
  76785. return this._ratio;
  76786. },
  76787. enumerable: true,
  76788. configurable: true
  76789. });
  76790. /**
  76791. * Checks wether everything is ready to render a submesh to the G buffer.
  76792. * @param subMesh the submesh to check readiness for
  76793. * @param useInstances is the mesh drawn using instance or not
  76794. * @returns true if ready otherwise false
  76795. */
  76796. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76797. var material = subMesh.getMaterial();
  76798. if (material && material.disableDepthWrite) {
  76799. return false;
  76800. }
  76801. var defines = [];
  76802. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76803. var mesh = subMesh.getMesh();
  76804. // Alpha test
  76805. if (material && material.needAlphaTesting()) {
  76806. defines.push("#define ALPHATEST");
  76807. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76808. attribs.push(BABYLON.VertexBuffer.UVKind);
  76809. defines.push("#define UV1");
  76810. }
  76811. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76812. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76813. defines.push("#define UV2");
  76814. }
  76815. }
  76816. // Buffers
  76817. if (this._enablePosition) {
  76818. defines.push("#define POSITION");
  76819. }
  76820. // Bones
  76821. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76822. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76823. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76824. if (mesh.numBoneInfluencers > 4) {
  76825. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76826. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76827. }
  76828. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76829. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76830. }
  76831. else {
  76832. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76833. }
  76834. // Instances
  76835. if (useInstances) {
  76836. defines.push("#define INSTANCES");
  76837. attribs.push("world0");
  76838. attribs.push("world1");
  76839. attribs.push("world2");
  76840. attribs.push("world3");
  76841. }
  76842. // Get correct effect
  76843. var join = defines.join("\n");
  76844. if (this._cachedDefines !== join) {
  76845. this._cachedDefines = join;
  76846. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76847. }
  76848. return this._effect.isReady();
  76849. };
  76850. /**
  76851. * Gets the current underlying G Buffer.
  76852. * @returns the buffer
  76853. */
  76854. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76855. return this._multiRenderTarget;
  76856. };
  76857. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76858. /**
  76859. * Gets the number of samples used to render the buffer (anti aliasing).
  76860. */
  76861. get: function () {
  76862. return this._multiRenderTarget.samples;
  76863. },
  76864. /**
  76865. * Sets the number of samples used to render the buffer (anti aliasing).
  76866. */
  76867. set: function (value) {
  76868. this._multiRenderTarget.samples = value;
  76869. },
  76870. enumerable: true,
  76871. configurable: true
  76872. });
  76873. /**
  76874. * Disposes the renderer and frees up associated resources.
  76875. */
  76876. GeometryBufferRenderer.prototype.dispose = function () {
  76877. this.getGBuffer().dispose();
  76878. };
  76879. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76880. var _this = this;
  76881. var engine = this._scene.getEngine();
  76882. var count = this._enablePosition ? 3 : 2;
  76883. 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 });
  76884. if (!this.isSupported) {
  76885. return;
  76886. }
  76887. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76888. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76889. this._multiRenderTarget.refreshRate = 1;
  76890. this._multiRenderTarget.renderParticles = false;
  76891. this._multiRenderTarget.renderList = null;
  76892. // set default depth value to 1.0 (far away)
  76893. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76894. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76895. });
  76896. // Custom render function
  76897. var renderSubMesh = function (subMesh) {
  76898. var mesh = subMesh.getRenderingMesh();
  76899. var scene = _this._scene;
  76900. var engine = scene.getEngine();
  76901. var material = subMesh.getMaterial();
  76902. if (!material) {
  76903. return;
  76904. }
  76905. // Culling
  76906. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76907. // Managing instances
  76908. var batch = mesh._getInstancesRenderList(subMesh._id);
  76909. if (batch.mustReturn) {
  76910. return;
  76911. }
  76912. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76913. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76914. engine.enableEffect(_this._effect);
  76915. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76916. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76917. _this._effect.setMatrix("view", scene.getViewMatrix());
  76918. // Alpha test
  76919. if (material && material.needAlphaTesting()) {
  76920. var alphaTexture = material.getAlphaTestTexture();
  76921. if (alphaTexture) {
  76922. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76923. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76924. }
  76925. }
  76926. // Bones
  76927. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76928. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76929. }
  76930. // Draw
  76931. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76932. }
  76933. };
  76934. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76935. var index;
  76936. if (depthOnlySubMeshes.length) {
  76937. engine.setColorWrite(false);
  76938. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76939. renderSubMesh(depthOnlySubMeshes.data[index]);
  76940. }
  76941. engine.setColorWrite(true);
  76942. }
  76943. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76944. renderSubMesh(opaqueSubMeshes.data[index]);
  76945. }
  76946. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76947. renderSubMesh(alphaTestSubMeshes.data[index]);
  76948. }
  76949. };
  76950. };
  76951. return GeometryBufferRenderer;
  76952. }());
  76953. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76954. })(BABYLON || (BABYLON = {}));
  76955. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76956. var BABYLON;
  76957. (function (BABYLON) {
  76958. /**
  76959. * This groups together the common properties used for image processing either in direct forward pass
  76960. * or through post processing effect depending on the use of the image processing pipeline in your scene
  76961. * or not.
  76962. */
  76963. var ImageProcessingConfiguration = /** @class */ (function () {
  76964. function ImageProcessingConfiguration() {
  76965. /**
  76966. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  76967. */
  76968. this.colorCurves = new BABYLON.ColorCurves();
  76969. this._colorCurvesEnabled = false;
  76970. this._colorGradingEnabled = false;
  76971. this._colorGradingWithGreenDepth = true;
  76972. this._colorGradingBGR = true;
  76973. this._exposure = 1.0;
  76974. this._toneMappingEnabled = false;
  76975. this._contrast = 1.0;
  76976. /**
  76977. * Vignette stretch size.
  76978. */
  76979. this.vignetteStretch = 0;
  76980. /**
  76981. * Vignette centre X Offset.
  76982. */
  76983. this.vignetteCentreX = 0;
  76984. /**
  76985. * Vignette centre Y Offset.
  76986. */
  76987. this.vignetteCentreY = 0;
  76988. /**
  76989. * Vignette weight or intensity of the vignette effect.
  76990. */
  76991. this.vignetteWeight = 1.5;
  76992. /**
  76993. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76994. * if vignetteEnabled is set to true.
  76995. */
  76996. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  76997. /**
  76998. * Camera field of view used by the Vignette effect.
  76999. */
  77000. this.vignetteCameraFov = 0.5;
  77001. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77002. this._vignetteEnabled = false;
  77003. this._applyByPostProcess = false;
  77004. this._isEnabled = true;
  77005. /**
  77006. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77007. */
  77008. this.onUpdateParameters = new BABYLON.Observable();
  77009. }
  77010. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77011. /**
  77012. * Gets wether the color curves effect is enabled.
  77013. */
  77014. get: function () {
  77015. return this._colorCurvesEnabled;
  77016. },
  77017. /**
  77018. * Sets wether the color curves effect is enabled.
  77019. */
  77020. set: function (value) {
  77021. if (this._colorCurvesEnabled === value) {
  77022. return;
  77023. }
  77024. this._colorCurvesEnabled = value;
  77025. this._updateParameters();
  77026. },
  77027. enumerable: true,
  77028. configurable: true
  77029. });
  77030. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77031. /**
  77032. * Gets wether the color grading effect is enabled.
  77033. */
  77034. get: function () {
  77035. return this._colorGradingEnabled;
  77036. },
  77037. /**
  77038. * Sets wether the color grading effect is enabled.
  77039. */
  77040. set: function (value) {
  77041. if (this._colorGradingEnabled === value) {
  77042. return;
  77043. }
  77044. this._colorGradingEnabled = value;
  77045. this._updateParameters();
  77046. },
  77047. enumerable: true,
  77048. configurable: true
  77049. });
  77050. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77051. /**
  77052. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77053. */
  77054. get: function () {
  77055. return this._colorGradingWithGreenDepth;
  77056. },
  77057. /**
  77058. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77059. */
  77060. set: function (value) {
  77061. if (this._colorGradingWithGreenDepth === value) {
  77062. return;
  77063. }
  77064. this._colorGradingWithGreenDepth = value;
  77065. this._updateParameters();
  77066. },
  77067. enumerable: true,
  77068. configurable: true
  77069. });
  77070. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77071. /**
  77072. * Gets wether the color grading texture contains BGR values.
  77073. */
  77074. get: function () {
  77075. return this._colorGradingBGR;
  77076. },
  77077. /**
  77078. * Sets wether the color grading texture contains BGR values.
  77079. */
  77080. set: function (value) {
  77081. if (this._colorGradingBGR === value) {
  77082. return;
  77083. }
  77084. this._colorGradingBGR = value;
  77085. this._updateParameters();
  77086. },
  77087. enumerable: true,
  77088. configurable: true
  77089. });
  77090. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77091. /**
  77092. * Gets the Exposure used in the effect.
  77093. */
  77094. get: function () {
  77095. return this._exposure;
  77096. },
  77097. /**
  77098. * Sets the Exposure used in the effect.
  77099. */
  77100. set: function (value) {
  77101. if (this._exposure === value) {
  77102. return;
  77103. }
  77104. this._exposure = value;
  77105. this._updateParameters();
  77106. },
  77107. enumerable: true,
  77108. configurable: true
  77109. });
  77110. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77111. /**
  77112. * Gets wether the tone mapping effect is enabled.
  77113. */
  77114. get: function () {
  77115. return this._toneMappingEnabled;
  77116. },
  77117. /**
  77118. * Sets wether the tone mapping effect is enabled.
  77119. */
  77120. set: function (value) {
  77121. if (this._toneMappingEnabled === value) {
  77122. return;
  77123. }
  77124. this._toneMappingEnabled = value;
  77125. this._updateParameters();
  77126. },
  77127. enumerable: true,
  77128. configurable: true
  77129. });
  77130. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77131. /**
  77132. * Gets the contrast used in the effect.
  77133. */
  77134. get: function () {
  77135. return this._contrast;
  77136. },
  77137. /**
  77138. * Sets the contrast used in the effect.
  77139. */
  77140. set: function (value) {
  77141. if (this._contrast === value) {
  77142. return;
  77143. }
  77144. this._contrast = value;
  77145. this._updateParameters();
  77146. },
  77147. enumerable: true,
  77148. configurable: true
  77149. });
  77150. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77151. /**
  77152. * Gets the vignette blend mode allowing different kind of effect.
  77153. */
  77154. get: function () {
  77155. return this._vignetteBlendMode;
  77156. },
  77157. /**
  77158. * Sets the vignette blend mode allowing different kind of effect.
  77159. */
  77160. set: function (value) {
  77161. if (this._vignetteBlendMode === value) {
  77162. return;
  77163. }
  77164. this._vignetteBlendMode = value;
  77165. this._updateParameters();
  77166. },
  77167. enumerable: true,
  77168. configurable: true
  77169. });
  77170. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77171. /**
  77172. * Gets wether the vignette effect is enabled.
  77173. */
  77174. get: function () {
  77175. return this._vignetteEnabled;
  77176. },
  77177. /**
  77178. * Sets wether the vignette effect is enabled.
  77179. */
  77180. set: function (value) {
  77181. if (this._vignetteEnabled === value) {
  77182. return;
  77183. }
  77184. this._vignetteEnabled = value;
  77185. this._updateParameters();
  77186. },
  77187. enumerable: true,
  77188. configurable: true
  77189. });
  77190. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77191. /**
  77192. * Gets wether the image processing is applied through a post process or not.
  77193. */
  77194. get: function () {
  77195. return this._applyByPostProcess;
  77196. },
  77197. /**
  77198. * Sets wether the image processing is applied through a post process or not.
  77199. */
  77200. set: function (value) {
  77201. if (this._applyByPostProcess === value) {
  77202. return;
  77203. }
  77204. this._applyByPostProcess = value;
  77205. this._updateParameters();
  77206. },
  77207. enumerable: true,
  77208. configurable: true
  77209. });
  77210. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77211. /**
  77212. * Gets wether the image processing is enabled or not.
  77213. */
  77214. get: function () {
  77215. return this._isEnabled;
  77216. },
  77217. /**
  77218. * Sets wether the image processing is enabled or not.
  77219. */
  77220. set: function (value) {
  77221. if (this._isEnabled === value) {
  77222. return;
  77223. }
  77224. this._isEnabled = value;
  77225. this._updateParameters();
  77226. },
  77227. enumerable: true,
  77228. configurable: true
  77229. });
  77230. /**
  77231. * Method called each time the image processing information changes requires to recompile the effect.
  77232. */
  77233. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77234. this.onUpdateParameters.notifyObservers(this);
  77235. };
  77236. ImageProcessingConfiguration.prototype.getClassName = function () {
  77237. return "ImageProcessingConfiguration";
  77238. };
  77239. /**
  77240. * Prepare the list of uniforms associated with the Image Processing effects.
  77241. * @param uniformsList The list of uniforms used in the effect
  77242. * @param defines the list of defines currently in use
  77243. */
  77244. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77245. if (defines.EXPOSURE) {
  77246. uniforms.push("exposureLinear");
  77247. }
  77248. if (defines.CONTRAST) {
  77249. uniforms.push("contrast");
  77250. }
  77251. if (defines.COLORGRADING) {
  77252. uniforms.push("colorTransformSettings");
  77253. }
  77254. if (defines.VIGNETTE) {
  77255. uniforms.push("vInverseScreenSize");
  77256. uniforms.push("vignetteSettings1");
  77257. uniforms.push("vignetteSettings2");
  77258. }
  77259. if (defines.COLORCURVES) {
  77260. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77261. }
  77262. };
  77263. /**
  77264. * Prepare the list of samplers associated with the Image Processing effects.
  77265. * @param uniformsList The list of uniforms used in the effect
  77266. * @param defines the list of defines currently in use
  77267. */
  77268. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77269. if (defines.COLORGRADING) {
  77270. samplersList.push("txColorTransform");
  77271. }
  77272. };
  77273. /**
  77274. * Prepare the list of defines associated to the shader.
  77275. * @param defines the list of defines to complete
  77276. */
  77277. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77278. if (forPostProcess === void 0) { forPostProcess = false; }
  77279. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77280. defines.VIGNETTE = false;
  77281. defines.TONEMAPPING = false;
  77282. defines.CONTRAST = false;
  77283. defines.EXPOSURE = false;
  77284. defines.COLORCURVES = false;
  77285. defines.COLORGRADING = false;
  77286. defines.COLORGRADING3D = false;
  77287. defines.IMAGEPROCESSING = false;
  77288. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77289. return;
  77290. }
  77291. defines.VIGNETTE = this.vignetteEnabled;
  77292. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77293. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77294. defines.TONEMAPPING = this.toneMappingEnabled;
  77295. defines.CONTRAST = (this.contrast !== 1.0);
  77296. defines.EXPOSURE = (this.exposure !== 1.0);
  77297. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77298. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77299. if (defines.COLORGRADING) {
  77300. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77301. }
  77302. else {
  77303. defines.COLORGRADING3D = false;
  77304. }
  77305. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77306. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77307. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77308. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77309. };
  77310. /**
  77311. * Returns true if all the image processing information are ready.
  77312. */
  77313. ImageProcessingConfiguration.prototype.isReady = function () {
  77314. // Color Grading texure can not be none blocking.
  77315. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77316. };
  77317. /**
  77318. * Binds the image processing to the shader.
  77319. * @param effect The effect to bind to
  77320. */
  77321. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77322. if (aspectRatio === void 0) { aspectRatio = 1; }
  77323. // Color Curves
  77324. if (this._colorCurvesEnabled && this.colorCurves) {
  77325. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77326. }
  77327. // Vignette
  77328. if (this._vignetteEnabled) {
  77329. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77330. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77331. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77332. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77333. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77334. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77335. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77336. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77337. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77338. var vignettePower = -2.0 * this.vignetteWeight;
  77339. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77340. }
  77341. // Exposure
  77342. effect.setFloat("exposureLinear", this.exposure);
  77343. // Contrast
  77344. effect.setFloat("contrast", this.contrast);
  77345. // Color transform settings
  77346. if (this.colorGradingTexture) {
  77347. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77348. var textureSize = this.colorGradingTexture.getSize().height;
  77349. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77350. 0.5 / textureSize, // textureOffset
  77351. textureSize, // textureSize
  77352. this.colorGradingTexture.level // weight
  77353. );
  77354. }
  77355. };
  77356. /**
  77357. * Clones the current image processing instance.
  77358. * @return The cloned image processing
  77359. */
  77360. ImageProcessingConfiguration.prototype.clone = function () {
  77361. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77362. };
  77363. /**
  77364. * Serializes the current image processing instance to a json representation.
  77365. * @return a JSON representation
  77366. */
  77367. ImageProcessingConfiguration.prototype.serialize = function () {
  77368. return BABYLON.SerializationHelper.Serialize(this);
  77369. };
  77370. /**
  77371. * Parses the image processing from a json representation.
  77372. * @param source the JSON source to parse
  77373. * @return The parsed image processing
  77374. */
  77375. ImageProcessingConfiguration.Parse = function (source) {
  77376. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77377. };
  77378. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77379. /**
  77380. * Used to apply the vignette as a mix with the pixel color.
  77381. */
  77382. get: function () {
  77383. return this._VIGNETTEMODE_MULTIPLY;
  77384. },
  77385. enumerable: true,
  77386. configurable: true
  77387. });
  77388. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77389. /**
  77390. * Used to apply the vignette as a replacement of the pixel color.
  77391. */
  77392. get: function () {
  77393. return this._VIGNETTEMODE_OPAQUE;
  77394. },
  77395. enumerable: true,
  77396. configurable: true
  77397. });
  77398. // Static constants associated to the image processing.
  77399. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77400. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77401. __decorate([
  77402. BABYLON.serializeAsColorCurves()
  77403. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77404. __decorate([
  77405. BABYLON.serialize()
  77406. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77407. __decorate([
  77408. BABYLON.serializeAsTexture()
  77409. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77410. __decorate([
  77411. BABYLON.serialize()
  77412. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77413. __decorate([
  77414. BABYLON.serialize()
  77415. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77416. __decorate([
  77417. BABYLON.serialize()
  77418. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77419. __decorate([
  77420. BABYLON.serialize()
  77421. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77422. __decorate([
  77423. BABYLON.serialize()
  77424. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77425. __decorate([
  77426. BABYLON.serialize()
  77427. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77428. __decorate([
  77429. BABYLON.serialize()
  77430. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77431. __decorate([
  77432. BABYLON.serialize()
  77433. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77434. __decorate([
  77435. BABYLON.serialize()
  77436. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77437. __decorate([
  77438. BABYLON.serialize()
  77439. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77440. __decorate([
  77441. BABYLON.serializeAsColor4()
  77442. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77443. __decorate([
  77444. BABYLON.serialize()
  77445. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77446. __decorate([
  77447. BABYLON.serialize()
  77448. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77449. __decorate([
  77450. BABYLON.serialize()
  77451. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77452. __decorate([
  77453. BABYLON.serialize()
  77454. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77455. __decorate([
  77456. BABYLON.serialize()
  77457. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77458. return ImageProcessingConfiguration;
  77459. }());
  77460. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77461. })(BABYLON || (BABYLON = {}));
  77462. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77463. var BABYLON;
  77464. (function (BABYLON) {
  77465. /**
  77466. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77467. * It can help converting any input color in a desired output one. This can then be used to create effects
  77468. * from sepia, black and white to sixties or futuristic rendering...
  77469. *
  77470. * The only supported format is currently 3dl.
  77471. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77472. */
  77473. var ColorGradingTexture = /** @class */ (function (_super) {
  77474. __extends(ColorGradingTexture, _super);
  77475. /**
  77476. * Instantiates a ColorGradingTexture from the following parameters.
  77477. *
  77478. * @param url The location of the color gradind data (currently only supporting 3dl)
  77479. * @param scene The scene the texture will be used in
  77480. */
  77481. function ColorGradingTexture(url, scene) {
  77482. var _this = _super.call(this, scene) || this;
  77483. if (!url) {
  77484. return _this;
  77485. }
  77486. _this._engine = scene.getEngine();
  77487. _this._textureMatrix = BABYLON.Matrix.Identity();
  77488. _this.name = url;
  77489. _this.url = url;
  77490. _this.hasAlpha = false;
  77491. _this.isCube = false;
  77492. _this.is3D = _this._engine.webGLVersion > 1;
  77493. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77494. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77495. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77496. _this.anisotropicFilteringLevel = 1;
  77497. _this._texture = _this._getFromCache(url, true);
  77498. if (!_this._texture) {
  77499. if (!scene.useDelayedTextureLoading) {
  77500. _this.loadTexture();
  77501. }
  77502. else {
  77503. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77504. }
  77505. }
  77506. return _this;
  77507. }
  77508. /**
  77509. * Returns the texture matrix used in most of the material.
  77510. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77511. */
  77512. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77513. return this._textureMatrix;
  77514. };
  77515. /**
  77516. * Occurs when the file being loaded is a .3dl LUT file.
  77517. */
  77518. ColorGradingTexture.prototype.load3dlTexture = function () {
  77519. var engine = this._engine;
  77520. var texture;
  77521. if (engine.webGLVersion === 1) {
  77522. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77523. }
  77524. else {
  77525. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77526. }
  77527. this._texture = texture;
  77528. var callback = function (text) {
  77529. if (typeof text !== "string") {
  77530. return;
  77531. }
  77532. var data = null;
  77533. var tempData = null;
  77534. var line;
  77535. var lines = text.split('\n');
  77536. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77537. var maxColor = 0;
  77538. for (var i = 0; i < lines.length; i++) {
  77539. line = lines[i];
  77540. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77541. continue;
  77542. if (line.indexOf('#') === 0)
  77543. continue;
  77544. var words = line.split(" ");
  77545. if (size === 0) {
  77546. // Number of space + one
  77547. size = words.length;
  77548. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77549. tempData = new Float32Array(size * size * size * 4);
  77550. continue;
  77551. }
  77552. if (size != 0) {
  77553. var r = Math.max(parseInt(words[0]), 0);
  77554. var g = Math.max(parseInt(words[1]), 0);
  77555. var b = Math.max(parseInt(words[2]), 0);
  77556. maxColor = Math.max(r, maxColor);
  77557. maxColor = Math.max(g, maxColor);
  77558. maxColor = Math.max(b, maxColor);
  77559. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77560. if (tempData) {
  77561. tempData[pixelStorageIndex + 0] = r;
  77562. tempData[pixelStorageIndex + 1] = g;
  77563. tempData[pixelStorageIndex + 2] = b;
  77564. }
  77565. pixelIndexSlice++;
  77566. if (pixelIndexSlice % size == 0) {
  77567. pixelIndexH++;
  77568. pixelIndexSlice = 0;
  77569. if (pixelIndexH % size == 0) {
  77570. pixelIndexW++;
  77571. pixelIndexH = 0;
  77572. }
  77573. }
  77574. }
  77575. }
  77576. if (tempData && data) {
  77577. for (var i = 0; i < tempData.length; i++) {
  77578. if (i > 0 && (i + 1) % 4 === 0) {
  77579. data[i] = 255;
  77580. }
  77581. else {
  77582. var value = tempData[i];
  77583. data[i] = (value / maxColor * 255);
  77584. }
  77585. }
  77586. }
  77587. if (texture.is3D) {
  77588. texture.updateSize(size, size, size);
  77589. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77590. }
  77591. else {
  77592. texture.updateSize(size * size, size);
  77593. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77594. }
  77595. };
  77596. var scene = this.getScene();
  77597. if (scene) {
  77598. scene._loadFile(this.url, callback);
  77599. }
  77600. else {
  77601. this._engine._loadFile(this.url, callback);
  77602. }
  77603. return this._texture;
  77604. };
  77605. /**
  77606. * Starts the loading process of the texture.
  77607. */
  77608. ColorGradingTexture.prototype.loadTexture = function () {
  77609. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77610. this.load3dlTexture();
  77611. }
  77612. };
  77613. /**
  77614. * Clones the color gradind texture.
  77615. */
  77616. ColorGradingTexture.prototype.clone = function () {
  77617. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77618. // Base texture
  77619. newTexture.level = this.level;
  77620. return newTexture;
  77621. };
  77622. /**
  77623. * Called during delayed load for textures.
  77624. */
  77625. ColorGradingTexture.prototype.delayLoad = function () {
  77626. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77627. return;
  77628. }
  77629. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77630. this._texture = this._getFromCache(this.url, true);
  77631. if (!this._texture) {
  77632. this.loadTexture();
  77633. }
  77634. };
  77635. /**
  77636. * Parses a color grading texture serialized by Babylon.
  77637. * @param parsedTexture The texture information being parsedTexture
  77638. * @param scene The scene to load the texture in
  77639. * @param rootUrl The root url of the data assets to load
  77640. * @return A color gradind texture
  77641. */
  77642. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77643. var texture = null;
  77644. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77645. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77646. texture.name = parsedTexture.name;
  77647. texture.level = parsedTexture.level;
  77648. }
  77649. return texture;
  77650. };
  77651. /**
  77652. * Serializes the LUT texture to json format.
  77653. */
  77654. ColorGradingTexture.prototype.serialize = function () {
  77655. if (!this.name) {
  77656. return null;
  77657. }
  77658. var serializationObject = {};
  77659. serializationObject.name = this.name;
  77660. serializationObject.level = this.level;
  77661. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77662. return serializationObject;
  77663. };
  77664. /**
  77665. * Empty line regex stored for GC.
  77666. */
  77667. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77668. return ColorGradingTexture;
  77669. }(BABYLON.BaseTexture));
  77670. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77671. })(BABYLON || (BABYLON = {}));
  77672. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77673. var BABYLON;
  77674. (function (BABYLON) {
  77675. /**
  77676. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77677. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77678. * 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;
  77679. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77680. */
  77681. var ColorCurves = /** @class */ (function () {
  77682. function ColorCurves() {
  77683. this._dirty = true;
  77684. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77685. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77686. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77687. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77688. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77689. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77690. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77691. this._globalHue = 30;
  77692. this._globalDensity = 0;
  77693. this._globalSaturation = 0;
  77694. this._globalExposure = 0;
  77695. this._highlightsHue = 30;
  77696. this._highlightsDensity = 0;
  77697. this._highlightsSaturation = 0;
  77698. this._highlightsExposure = 0;
  77699. this._midtonesHue = 30;
  77700. this._midtonesDensity = 0;
  77701. this._midtonesSaturation = 0;
  77702. this._midtonesExposure = 0;
  77703. this._shadowsHue = 30;
  77704. this._shadowsDensity = 0;
  77705. this._shadowsSaturation = 0;
  77706. this._shadowsExposure = 0;
  77707. }
  77708. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77709. /**
  77710. * Gets the global Hue value.
  77711. * 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).
  77712. */
  77713. get: function () {
  77714. return this._globalHue;
  77715. },
  77716. /**
  77717. * Sets the global Hue value.
  77718. * 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).
  77719. */
  77720. set: function (value) {
  77721. this._globalHue = value;
  77722. this._dirty = true;
  77723. },
  77724. enumerable: true,
  77725. configurable: true
  77726. });
  77727. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77728. /**
  77729. * Gets the global Density value.
  77730. * 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.
  77731. * Values less than zero provide a filter of opposite hue.
  77732. */
  77733. get: function () {
  77734. return this._globalDensity;
  77735. },
  77736. /**
  77737. * Sets the global Density value.
  77738. * 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.
  77739. * Values less than zero provide a filter of opposite hue.
  77740. */
  77741. set: function (value) {
  77742. this._globalDensity = value;
  77743. this._dirty = true;
  77744. },
  77745. enumerable: true,
  77746. configurable: true
  77747. });
  77748. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77749. /**
  77750. * Gets the global Saturation value.
  77751. * 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.
  77752. */
  77753. get: function () {
  77754. return this._globalSaturation;
  77755. },
  77756. /**
  77757. * Sets the global Saturation value.
  77758. * 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.
  77759. */
  77760. set: function (value) {
  77761. this._globalSaturation = value;
  77762. this._dirty = true;
  77763. },
  77764. enumerable: true,
  77765. configurable: true
  77766. });
  77767. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77768. /**
  77769. * Gets the global Exposure value.
  77770. * 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.
  77771. */
  77772. get: function () {
  77773. return this._globalExposure;
  77774. },
  77775. /**
  77776. * Sets the global Exposure value.
  77777. * 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.
  77778. */
  77779. set: function (value) {
  77780. this._globalExposure = value;
  77781. this._dirty = true;
  77782. },
  77783. enumerable: true,
  77784. configurable: true
  77785. });
  77786. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77787. /**
  77788. * Gets the highlights Hue value.
  77789. * 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).
  77790. */
  77791. get: function () {
  77792. return this._highlightsHue;
  77793. },
  77794. /**
  77795. * Sets the highlights Hue value.
  77796. * 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).
  77797. */
  77798. set: function (value) {
  77799. this._highlightsHue = value;
  77800. this._dirty = true;
  77801. },
  77802. enumerable: true,
  77803. configurable: true
  77804. });
  77805. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77806. /**
  77807. * Gets the highlights Density value.
  77808. * 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.
  77809. * Values less than zero provide a filter of opposite hue.
  77810. */
  77811. get: function () {
  77812. return this._highlightsDensity;
  77813. },
  77814. /**
  77815. * Sets the highlights Density value.
  77816. * 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.
  77817. * Values less than zero provide a filter of opposite hue.
  77818. */
  77819. set: function (value) {
  77820. this._highlightsDensity = value;
  77821. this._dirty = true;
  77822. },
  77823. enumerable: true,
  77824. configurable: true
  77825. });
  77826. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77827. /**
  77828. * Gets the highlights Saturation value.
  77829. * 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.
  77830. */
  77831. get: function () {
  77832. return this._highlightsSaturation;
  77833. },
  77834. /**
  77835. * Sets the highlights Saturation value.
  77836. * 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.
  77837. */
  77838. set: function (value) {
  77839. this._highlightsSaturation = value;
  77840. this._dirty = true;
  77841. },
  77842. enumerable: true,
  77843. configurable: true
  77844. });
  77845. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  77846. /**
  77847. * Gets the highlights Exposure value.
  77848. * 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.
  77849. */
  77850. get: function () {
  77851. return this._highlightsExposure;
  77852. },
  77853. /**
  77854. * Sets the highlights Exposure value.
  77855. * 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.
  77856. */
  77857. set: function (value) {
  77858. this._highlightsExposure = value;
  77859. this._dirty = true;
  77860. },
  77861. enumerable: true,
  77862. configurable: true
  77863. });
  77864. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  77865. /**
  77866. * Gets the midtones Hue value.
  77867. * 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).
  77868. */
  77869. get: function () {
  77870. return this._midtonesHue;
  77871. },
  77872. /**
  77873. * Sets the midtones Hue value.
  77874. * 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).
  77875. */
  77876. set: function (value) {
  77877. this._midtonesHue = value;
  77878. this._dirty = true;
  77879. },
  77880. enumerable: true,
  77881. configurable: true
  77882. });
  77883. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  77884. /**
  77885. * Gets the midtones Density value.
  77886. * 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.
  77887. * Values less than zero provide a filter of opposite hue.
  77888. */
  77889. get: function () {
  77890. return this._midtonesDensity;
  77891. },
  77892. /**
  77893. * Sets the midtones Density value.
  77894. * 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.
  77895. * Values less than zero provide a filter of opposite hue.
  77896. */
  77897. set: function (value) {
  77898. this._midtonesDensity = value;
  77899. this._dirty = true;
  77900. },
  77901. enumerable: true,
  77902. configurable: true
  77903. });
  77904. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  77905. /**
  77906. * Gets the midtones Saturation value.
  77907. * 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.
  77908. */
  77909. get: function () {
  77910. return this._midtonesSaturation;
  77911. },
  77912. /**
  77913. * Sets the midtones Saturation value.
  77914. * 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.
  77915. */
  77916. set: function (value) {
  77917. this._midtonesSaturation = value;
  77918. this._dirty = true;
  77919. },
  77920. enumerable: true,
  77921. configurable: true
  77922. });
  77923. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  77924. /**
  77925. * Gets the midtones Exposure value.
  77926. * 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.
  77927. */
  77928. get: function () {
  77929. return this._midtonesExposure;
  77930. },
  77931. /**
  77932. * Sets the midtones Exposure value.
  77933. * 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.
  77934. */
  77935. set: function (value) {
  77936. this._midtonesExposure = value;
  77937. this._dirty = true;
  77938. },
  77939. enumerable: true,
  77940. configurable: true
  77941. });
  77942. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  77943. /**
  77944. * Gets the shadows Hue value.
  77945. * 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).
  77946. */
  77947. get: function () {
  77948. return this._shadowsHue;
  77949. },
  77950. /**
  77951. * Sets the shadows Hue value.
  77952. * 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).
  77953. */
  77954. set: function (value) {
  77955. this._shadowsHue = value;
  77956. this._dirty = true;
  77957. },
  77958. enumerable: true,
  77959. configurable: true
  77960. });
  77961. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  77962. /**
  77963. * Gets the shadows Density value.
  77964. * 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.
  77965. * Values less than zero provide a filter of opposite hue.
  77966. */
  77967. get: function () {
  77968. return this._shadowsDensity;
  77969. },
  77970. /**
  77971. * Sets the shadows Density value.
  77972. * 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.
  77973. * Values less than zero provide a filter of opposite hue.
  77974. */
  77975. set: function (value) {
  77976. this._shadowsDensity = value;
  77977. this._dirty = true;
  77978. },
  77979. enumerable: true,
  77980. configurable: true
  77981. });
  77982. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  77983. /**
  77984. * Gets the shadows Saturation value.
  77985. * 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.
  77986. */
  77987. get: function () {
  77988. return this._shadowsSaturation;
  77989. },
  77990. /**
  77991. * Sets the shadows Saturation value.
  77992. * 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.
  77993. */
  77994. set: function (value) {
  77995. this._shadowsSaturation = value;
  77996. this._dirty = true;
  77997. },
  77998. enumerable: true,
  77999. configurable: true
  78000. });
  78001. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78002. /**
  78003. * Gets the shadows Exposure value.
  78004. * 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.
  78005. */
  78006. get: function () {
  78007. return this._shadowsExposure;
  78008. },
  78009. /**
  78010. * Sets the shadows Exposure value.
  78011. * 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.
  78012. */
  78013. set: function (value) {
  78014. this._shadowsExposure = value;
  78015. this._dirty = true;
  78016. },
  78017. enumerable: true,
  78018. configurable: true
  78019. });
  78020. ColorCurves.prototype.getClassName = function () {
  78021. return "ColorCurves";
  78022. };
  78023. /**
  78024. * Binds the color curves to the shader.
  78025. * @param colorCurves The color curve to bind
  78026. * @param effect The effect to bind to
  78027. */
  78028. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78029. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78030. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78031. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78032. if (colorCurves._dirty) {
  78033. colorCurves._dirty = false;
  78034. // Fill in global info.
  78035. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78036. // Compute highlights info.
  78037. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78038. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78039. // Compute midtones info.
  78040. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78041. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78042. // Compute shadows info.
  78043. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78044. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78045. // Compute deltas (neutral is midtones).
  78046. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78047. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78048. }
  78049. if (effect) {
  78050. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78051. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78052. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78053. }
  78054. };
  78055. /**
  78056. * Prepare the list of uniforms associated with the ColorCurves effects.
  78057. * @param uniformsList The list of uniforms used in the effect
  78058. */
  78059. ColorCurves.PrepareUniforms = function (uniformsList) {
  78060. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78061. };
  78062. /**
  78063. * Returns color grading data based on a hue, density, saturation and exposure value.
  78064. * @param filterHue The hue of the color filter.
  78065. * @param filterDensity The density of the color filter.
  78066. * @param saturation The saturation.
  78067. * @param exposure The exposure.
  78068. * @param result The result data container.
  78069. */
  78070. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78071. if (hue == null) {
  78072. return;
  78073. }
  78074. hue = ColorCurves.clamp(hue, 0, 360);
  78075. density = ColorCurves.clamp(density, -100, 100);
  78076. saturation = ColorCurves.clamp(saturation, -100, 100);
  78077. exposure = ColorCurves.clamp(exposure, -100, 100);
  78078. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78079. // so that the maximum filter density is only 50% control. This provides fine control
  78080. // for small values and reasonable range.
  78081. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78082. density *= 0.5;
  78083. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78084. if (density < 0) {
  78085. density *= -1;
  78086. hue = (hue + 180) % 360;
  78087. }
  78088. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78089. result.scaleToRef(2, result);
  78090. result.a = 1 + 0.01 * saturation;
  78091. };
  78092. /**
  78093. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78094. * @param value The input slider value in range [-100,100].
  78095. * @returns Adjusted value.
  78096. */
  78097. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78098. value /= 100;
  78099. var x = Math.abs(value);
  78100. x = Math.pow(x, 2);
  78101. if (value < 0) {
  78102. x *= -1;
  78103. }
  78104. x *= 100;
  78105. return x;
  78106. };
  78107. /**
  78108. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78109. * @param hue The hue (H) input.
  78110. * @param saturation The saturation (S) input.
  78111. * @param brightness The brightness (B) input.
  78112. * @result An RGBA color represented as Vector4.
  78113. */
  78114. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78115. var h = ColorCurves.clamp(hue, 0, 360);
  78116. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78117. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78118. if (s === 0) {
  78119. result.r = v;
  78120. result.g = v;
  78121. result.b = v;
  78122. }
  78123. else {
  78124. // sector 0 to 5
  78125. h /= 60;
  78126. var i = Math.floor(h);
  78127. // fractional part of h
  78128. var f = h - i;
  78129. var p = v * (1 - s);
  78130. var q = v * (1 - s * f);
  78131. var t = v * (1 - s * (1 - f));
  78132. switch (i) {
  78133. case 0:
  78134. result.r = v;
  78135. result.g = t;
  78136. result.b = p;
  78137. break;
  78138. case 1:
  78139. result.r = q;
  78140. result.g = v;
  78141. result.b = p;
  78142. break;
  78143. case 2:
  78144. result.r = p;
  78145. result.g = v;
  78146. result.b = t;
  78147. break;
  78148. case 3:
  78149. result.r = p;
  78150. result.g = q;
  78151. result.b = v;
  78152. break;
  78153. case 4:
  78154. result.r = t;
  78155. result.g = p;
  78156. result.b = v;
  78157. break;
  78158. default: // case 5:
  78159. result.r = v;
  78160. result.g = p;
  78161. result.b = q;
  78162. break;
  78163. }
  78164. }
  78165. result.a = 1;
  78166. };
  78167. /**
  78168. * Returns a value clamped between min and max
  78169. * @param value The value to clamp
  78170. * @param min The minimum of value
  78171. * @param max The maximum of value
  78172. * @returns The clamped value.
  78173. */
  78174. ColorCurves.clamp = function (value, min, max) {
  78175. return Math.min(Math.max(value, min), max);
  78176. };
  78177. /**
  78178. * Clones the current color curve instance.
  78179. * @return The cloned curves
  78180. */
  78181. ColorCurves.prototype.clone = function () {
  78182. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78183. };
  78184. /**
  78185. * Serializes the current color curve instance to a json representation.
  78186. * @return a JSON representation
  78187. */
  78188. ColorCurves.prototype.serialize = function () {
  78189. return BABYLON.SerializationHelper.Serialize(this);
  78190. };
  78191. /**
  78192. * Parses the color curve from a json representation.
  78193. * @param source the JSON source to parse
  78194. * @return The parsed curves
  78195. */
  78196. ColorCurves.Parse = function (source) {
  78197. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78198. };
  78199. __decorate([
  78200. BABYLON.serialize()
  78201. ], ColorCurves.prototype, "_globalHue", void 0);
  78202. __decorate([
  78203. BABYLON.serialize()
  78204. ], ColorCurves.prototype, "_globalDensity", void 0);
  78205. __decorate([
  78206. BABYLON.serialize()
  78207. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78208. __decorate([
  78209. BABYLON.serialize()
  78210. ], ColorCurves.prototype, "_globalExposure", void 0);
  78211. __decorate([
  78212. BABYLON.serialize()
  78213. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78214. __decorate([
  78215. BABYLON.serialize()
  78216. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78217. __decorate([
  78218. BABYLON.serialize()
  78219. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78220. __decorate([
  78221. BABYLON.serialize()
  78222. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78223. __decorate([
  78224. BABYLON.serialize()
  78225. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78226. __decorate([
  78227. BABYLON.serialize()
  78228. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78229. __decorate([
  78230. BABYLON.serialize()
  78231. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78232. __decorate([
  78233. BABYLON.serialize()
  78234. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78235. return ColorCurves;
  78236. }());
  78237. BABYLON.ColorCurves = ColorCurves;
  78238. })(BABYLON || (BABYLON = {}));
  78239. //# sourceMappingURL=babylon.colorCurves.js.map
  78240. var BABYLON;
  78241. (function (BABYLON) {
  78242. var RefractionPostProcess = /** @class */ (function (_super) {
  78243. __extends(RefractionPostProcess, _super);
  78244. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78245. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78246. _this.color = color;
  78247. _this.depth = depth;
  78248. _this.colorLevel = colorLevel;
  78249. _this._ownRefractionTexture = true;
  78250. _this.onActivateObservable.add(function (cam) {
  78251. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78252. });
  78253. _this.onApplyObservable.add(function (effect) {
  78254. effect.setColor3("baseColor", _this.color);
  78255. effect.setFloat("depth", _this.depth);
  78256. effect.setFloat("colorLevel", _this.colorLevel);
  78257. effect.setTexture("refractionSampler", _this._refTexture);
  78258. });
  78259. return _this;
  78260. }
  78261. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78262. /**
  78263. * Gets or sets the refraction texture
  78264. * Please note that you are responsible for disposing the texture if you set it manually
  78265. */
  78266. get: function () {
  78267. return this._refTexture;
  78268. },
  78269. set: function (value) {
  78270. if (this._refTexture && this._ownRefractionTexture) {
  78271. this._refTexture.dispose();
  78272. }
  78273. this._refTexture = value;
  78274. this._ownRefractionTexture = false;
  78275. },
  78276. enumerable: true,
  78277. configurable: true
  78278. });
  78279. // Methods
  78280. RefractionPostProcess.prototype.dispose = function (camera) {
  78281. if (this._refTexture && this._ownRefractionTexture) {
  78282. this._refTexture.dispose();
  78283. this._refTexture = null;
  78284. }
  78285. _super.prototype.dispose.call(this, camera);
  78286. };
  78287. return RefractionPostProcess;
  78288. }(BABYLON.PostProcess));
  78289. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78290. })(BABYLON || (BABYLON = {}));
  78291. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78292. var BABYLON;
  78293. (function (BABYLON) {
  78294. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78295. __extends(BlackAndWhitePostProcess, _super);
  78296. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78297. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78298. _this.degree = 1;
  78299. _this.onApplyObservable.add(function (effect) {
  78300. effect.setFloat("degree", _this.degree);
  78301. });
  78302. return _this;
  78303. }
  78304. return BlackAndWhitePostProcess;
  78305. }(BABYLON.PostProcess));
  78306. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78307. })(BABYLON || (BABYLON = {}));
  78308. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78309. var BABYLON;
  78310. (function (BABYLON) {
  78311. /**
  78312. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78313. * input texture to perform effects such as edge detection or sharpening
  78314. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78315. */
  78316. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78317. __extends(ConvolutionPostProcess, _super);
  78318. /**
  78319. * Creates a new instance ConvolutionPostProcess
  78320. * @param name The name of the effect.
  78321. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78322. * @param options The required width/height ratio to downsize to before computing the render pass.
  78323. * @param camera The camera to apply the render pass to.
  78324. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78325. * @param engine The engine which the post process will be applied. (default: current engine)
  78326. * @param reusable If the post process can be reused on the same frame. (default: false)
  78327. * @param textureType Type of textures used when performing the post process. (default: 0)
  78328. */
  78329. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78330. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78331. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78332. _this.kernel = kernel;
  78333. _this.onApply = function (effect) {
  78334. effect.setFloat2("screenSize", _this.width, _this.height);
  78335. effect.setArray("kernel", _this.kernel);
  78336. };
  78337. return _this;
  78338. }
  78339. // Statics
  78340. /**
  78341. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78342. */
  78343. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78344. /**
  78345. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78346. */
  78347. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78348. /**
  78349. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78350. */
  78351. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78352. /**
  78353. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78354. */
  78355. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78356. /**
  78357. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78358. */
  78359. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78360. /**
  78361. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78362. */
  78363. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78364. return ConvolutionPostProcess;
  78365. }(BABYLON.PostProcess));
  78366. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78367. })(BABYLON || (BABYLON = {}));
  78368. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78369. var BABYLON;
  78370. (function (BABYLON) {
  78371. var FilterPostProcess = /** @class */ (function (_super) {
  78372. __extends(FilterPostProcess, _super);
  78373. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78374. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78375. _this.kernelMatrix = kernelMatrix;
  78376. _this.onApply = function (effect) {
  78377. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78378. };
  78379. return _this;
  78380. }
  78381. return FilterPostProcess;
  78382. }(BABYLON.PostProcess));
  78383. BABYLON.FilterPostProcess = FilterPostProcess;
  78384. })(BABYLON || (BABYLON = {}));
  78385. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78386. var BABYLON;
  78387. (function (BABYLON) {
  78388. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78389. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78390. __extends(VolumetricLightScatteringPostProcess, _super);
  78391. /**
  78392. * @constructor
  78393. * @param {string} name - The post-process name
  78394. * @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)
  78395. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78396. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78397. * @param {number} samples - The post-process quality, default 100
  78398. * @param {number} samplingMode - The post-process filtering mode
  78399. * @param {BABYLON.Engine} engine - The babylon engine
  78400. * @param {boolean} reusable - If the post-process is reusable
  78401. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78402. */
  78403. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78404. if (samples === void 0) { samples = 100; }
  78405. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78406. 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;
  78407. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78408. /**
  78409. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78410. */
  78411. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78412. /**
  78413. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78414. */
  78415. _this.useCustomMeshPosition = false;
  78416. /**
  78417. * If the post-process should inverse the light scattering direction
  78418. */
  78419. _this.invert = true;
  78420. /**
  78421. * Array containing the excluded meshes not rendered in the internal pass
  78422. */
  78423. _this.excludedMeshes = new Array();
  78424. /**
  78425. * Controls the overall intensity of the post-process
  78426. */
  78427. _this.exposure = 0.3;
  78428. /**
  78429. * Dissipates each sample's contribution in range [0, 1]
  78430. */
  78431. _this.decay = 0.96815;
  78432. /**
  78433. * Controls the overall intensity of each sample
  78434. */
  78435. _this.weight = 0.58767;
  78436. /**
  78437. * Controls the density of each sample
  78438. */
  78439. _this.density = 0.926;
  78440. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78441. engine = scene.getEngine();
  78442. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78443. // Configure mesh
  78444. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78445. // Configure
  78446. _this._createPass(scene, ratio.passRatio || ratio);
  78447. _this.onActivate = function (camera) {
  78448. if (!_this.isSupported) {
  78449. _this.dispose(camera);
  78450. }
  78451. _this.onActivate = null;
  78452. };
  78453. _this.onApplyObservable.add(function (effect) {
  78454. _this._updateMeshScreenCoordinates(scene);
  78455. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78456. effect.setFloat("exposure", _this.exposure);
  78457. effect.setFloat("decay", _this.decay);
  78458. effect.setFloat("weight", _this.weight);
  78459. effect.setFloat("density", _this.density);
  78460. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78461. });
  78462. return _this;
  78463. }
  78464. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78465. get: function () {
  78466. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78467. return false;
  78468. },
  78469. set: function (useDiffuseColor) {
  78470. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78471. },
  78472. enumerable: true,
  78473. configurable: true
  78474. });
  78475. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78476. return "VolumetricLightScatteringPostProcess";
  78477. };
  78478. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78479. var mesh = subMesh.getMesh();
  78480. // Render this.mesh as default
  78481. if (mesh === this.mesh && mesh.material) {
  78482. return mesh.material.isReady(mesh);
  78483. }
  78484. var defines = [];
  78485. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78486. var material = subMesh.getMaterial();
  78487. // Alpha test
  78488. if (material) {
  78489. if (material.needAlphaTesting()) {
  78490. defines.push("#define ALPHATEST");
  78491. }
  78492. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78493. attribs.push(BABYLON.VertexBuffer.UVKind);
  78494. defines.push("#define UV1");
  78495. }
  78496. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78497. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78498. defines.push("#define UV2");
  78499. }
  78500. }
  78501. // Bones
  78502. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78503. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78504. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78505. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78506. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78507. }
  78508. else {
  78509. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78510. }
  78511. // Instances
  78512. if (useInstances) {
  78513. defines.push("#define INSTANCES");
  78514. attribs.push("world0");
  78515. attribs.push("world1");
  78516. attribs.push("world2");
  78517. attribs.push("world3");
  78518. }
  78519. // Get correct effect
  78520. var join = defines.join("\n");
  78521. if (this._cachedDefines !== join) {
  78522. this._cachedDefines = join;
  78523. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78524. }
  78525. return this._volumetricLightScatteringPass.isReady();
  78526. };
  78527. /**
  78528. * Sets the new light position for light scattering effect
  78529. * @param {BABYLON.Vector3} The new custom light position
  78530. */
  78531. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78532. this.customMeshPosition = position;
  78533. };
  78534. /**
  78535. * Returns the light position for light scattering effect
  78536. * @return {BABYLON.Vector3} The custom light position
  78537. */
  78538. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78539. return this.customMeshPosition;
  78540. };
  78541. /**
  78542. * Disposes the internal assets and detaches the post-process from the camera
  78543. */
  78544. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78545. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78546. if (rttIndex !== -1) {
  78547. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78548. }
  78549. this._volumetricLightScatteringRTT.dispose();
  78550. _super.prototype.dispose.call(this, camera);
  78551. };
  78552. /**
  78553. * Returns the render target texture used by the post-process
  78554. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78555. */
  78556. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78557. return this._volumetricLightScatteringRTT;
  78558. };
  78559. // Private methods
  78560. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78561. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78562. return true;
  78563. }
  78564. return false;
  78565. };
  78566. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78567. var _this = this;
  78568. var engine = scene.getEngine();
  78569. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78570. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78571. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78572. this._volumetricLightScatteringRTT.renderList = null;
  78573. this._volumetricLightScatteringRTT.renderParticles = false;
  78574. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78575. var camera = this.getCamera();
  78576. if (camera) {
  78577. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78578. }
  78579. else {
  78580. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78581. }
  78582. // Custom render function for submeshes
  78583. var renderSubMesh = function (subMesh) {
  78584. var mesh = subMesh.getRenderingMesh();
  78585. if (_this._meshExcluded(mesh)) {
  78586. return;
  78587. }
  78588. var material = subMesh.getMaterial();
  78589. if (!material) {
  78590. return;
  78591. }
  78592. var scene = mesh.getScene();
  78593. var engine = scene.getEngine();
  78594. // Culling
  78595. engine.setState(material.backFaceCulling);
  78596. // Managing instances
  78597. var batch = mesh._getInstancesRenderList(subMesh._id);
  78598. if (batch.mustReturn) {
  78599. return;
  78600. }
  78601. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78602. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78603. var effect = _this._volumetricLightScatteringPass;
  78604. if (mesh === _this.mesh) {
  78605. if (subMesh.effect) {
  78606. effect = subMesh.effect;
  78607. }
  78608. else {
  78609. effect = material.getEffect();
  78610. }
  78611. }
  78612. engine.enableEffect(effect);
  78613. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78614. if (mesh === _this.mesh) {
  78615. material.bind(mesh.getWorldMatrix(), mesh);
  78616. }
  78617. else {
  78618. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78619. // Alpha test
  78620. if (material && material.needAlphaTesting()) {
  78621. var alphaTexture = material.getAlphaTestTexture();
  78622. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78623. if (alphaTexture) {
  78624. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78625. }
  78626. }
  78627. // Bones
  78628. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78629. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78630. }
  78631. }
  78632. // Draw
  78633. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78634. }
  78635. };
  78636. // Render target texture callbacks
  78637. var savedSceneClearColor;
  78638. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78639. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78640. savedSceneClearColor = scene.clearColor;
  78641. scene.clearColor = sceneClearColor;
  78642. });
  78643. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78644. scene.clearColor = savedSceneClearColor;
  78645. });
  78646. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78647. var engine = scene.getEngine();
  78648. var index;
  78649. if (depthOnlySubMeshes.length) {
  78650. engine.setColorWrite(false);
  78651. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78652. renderSubMesh(depthOnlySubMeshes.data[index]);
  78653. }
  78654. engine.setColorWrite(true);
  78655. }
  78656. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78657. renderSubMesh(opaqueSubMeshes.data[index]);
  78658. }
  78659. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78660. renderSubMesh(alphaTestSubMeshes.data[index]);
  78661. }
  78662. if (transparentSubMeshes.length) {
  78663. // Sort sub meshes
  78664. for (index = 0; index < transparentSubMeshes.length; index++) {
  78665. var submesh = transparentSubMeshes.data[index];
  78666. var boundingInfo = submesh.getBoundingInfo();
  78667. if (boundingInfo && scene.activeCamera) {
  78668. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78669. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78670. }
  78671. }
  78672. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78673. sortedArray.sort(function (a, b) {
  78674. // Alpha index first
  78675. if (a._alphaIndex > b._alphaIndex) {
  78676. return 1;
  78677. }
  78678. if (a._alphaIndex < b._alphaIndex) {
  78679. return -1;
  78680. }
  78681. // Then distance to camera
  78682. if (a._distanceToCamera < b._distanceToCamera) {
  78683. return 1;
  78684. }
  78685. if (a._distanceToCamera > b._distanceToCamera) {
  78686. return -1;
  78687. }
  78688. return 0;
  78689. });
  78690. // Render sub meshes
  78691. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78692. for (index = 0; index < sortedArray.length; index++) {
  78693. renderSubMesh(sortedArray[index]);
  78694. }
  78695. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78696. }
  78697. };
  78698. };
  78699. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78700. var transform = scene.getTransformMatrix();
  78701. var meshPosition;
  78702. if (this.useCustomMeshPosition) {
  78703. meshPosition = this.customMeshPosition;
  78704. }
  78705. else if (this.attachedNode) {
  78706. meshPosition = this.attachedNode.position;
  78707. }
  78708. else {
  78709. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78710. }
  78711. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78712. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78713. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78714. if (this.invert)
  78715. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78716. };
  78717. // Static methods
  78718. /**
  78719. * Creates a default mesh for the Volumeric Light Scattering post-process
  78720. * @param {string} The mesh name
  78721. * @param {BABYLON.Scene} The scene where to create the mesh
  78722. * @return {BABYLON.Mesh} the default mesh
  78723. */
  78724. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78725. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78726. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78727. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78728. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78729. mesh.material = material;
  78730. return mesh;
  78731. };
  78732. __decorate([
  78733. BABYLON.serializeAsVector3()
  78734. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78735. __decorate([
  78736. BABYLON.serialize()
  78737. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78738. __decorate([
  78739. BABYLON.serialize()
  78740. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78741. __decorate([
  78742. BABYLON.serializeAsMeshReference()
  78743. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78744. __decorate([
  78745. BABYLON.serialize()
  78746. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78747. __decorate([
  78748. BABYLON.serialize()
  78749. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78750. __decorate([
  78751. BABYLON.serialize()
  78752. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78753. __decorate([
  78754. BABYLON.serialize()
  78755. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78756. __decorate([
  78757. BABYLON.serialize()
  78758. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78759. return VolumetricLightScatteringPostProcess;
  78760. }(BABYLON.PostProcess));
  78761. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78762. })(BABYLON || (BABYLON = {}));
  78763. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78764. //
  78765. // This post-process allows the modification of rendered colors by using
  78766. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78767. //
  78768. // The object needs to be provided an url to a texture containing the color
  78769. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78770. // Use an image editing software to tweak the LUT to match your needs.
  78771. //
  78772. // For an example of a color LUT, see here:
  78773. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78774. // For explanations on color grading, see here:
  78775. // http://udn.epicgames.com/Three/ColorGrading.html
  78776. //
  78777. var BABYLON;
  78778. (function (BABYLON) {
  78779. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78780. __extends(ColorCorrectionPostProcess, _super);
  78781. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78782. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78783. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78784. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78785. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78786. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78787. _this.onApply = function (effect) {
  78788. effect.setTexture("colorTable", _this._colorTableTexture);
  78789. };
  78790. return _this;
  78791. }
  78792. return ColorCorrectionPostProcess;
  78793. }(BABYLON.PostProcess));
  78794. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78795. })(BABYLON || (BABYLON = {}));
  78796. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78797. var BABYLON;
  78798. (function (BABYLON) {
  78799. /** Defines operator used for tonemapping */
  78800. var TonemappingOperator;
  78801. (function (TonemappingOperator) {
  78802. /** Hable */
  78803. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78804. /** Reinhard */
  78805. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78806. /** HejiDawson */
  78807. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78808. /** Photographic */
  78809. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78810. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78811. ;
  78812. /**
  78813. * Defines a post process to apply tone mapping
  78814. */
  78815. var TonemapPostProcess = /** @class */ (function (_super) {
  78816. __extends(TonemapPostProcess, _super);
  78817. /**
  78818. * Creates a new TonemapPostProcess
  78819. * @param name defines the name of the postprocess
  78820. * @param _operator defines the operator to use
  78821. * @param exposureAdjustment defines the required exposure adjustement
  78822. * @param camera defines the camera to use (can be null)
  78823. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78824. * @param engine defines the hosting engine (can be ignore if camera is set)
  78825. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78826. */
  78827. function TonemapPostProcess(name, _operator,
  78828. /** Defines the required exposure adjustement */
  78829. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  78830. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78831. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78832. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  78833. _this._operator = _operator;
  78834. _this.exposureAdjustment = exposureAdjustment;
  78835. var defines = "#define ";
  78836. if (_this._operator === TonemappingOperator.Hable)
  78837. defines += "HABLE_TONEMAPPING";
  78838. else if (_this._operator === TonemappingOperator.Reinhard)
  78839. defines += "REINHARD_TONEMAPPING";
  78840. else if (_this._operator === TonemappingOperator.HejiDawson)
  78841. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  78842. else if (_this._operator === TonemappingOperator.Photographic)
  78843. defines += "PHOTOGRAPHIC_TONEMAPPING";
  78844. //sadly a second call to create the effect.
  78845. _this.updateEffect(defines);
  78846. _this.onApply = function (effect) {
  78847. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  78848. };
  78849. return _this;
  78850. }
  78851. return TonemapPostProcess;
  78852. }(BABYLON.PostProcess));
  78853. BABYLON.TonemapPostProcess = TonemapPostProcess;
  78854. })(BABYLON || (BABYLON = {}));
  78855. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  78856. var BABYLON;
  78857. (function (BABYLON) {
  78858. var DisplayPassPostProcess = /** @class */ (function (_super) {
  78859. __extends(DisplayPassPostProcess, _super);
  78860. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  78861. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  78862. }
  78863. return DisplayPassPostProcess;
  78864. }(BABYLON.PostProcess));
  78865. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  78866. })(BABYLON || (BABYLON = {}));
  78867. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  78868. var BABYLON;
  78869. (function (BABYLON) {
  78870. var HighlightsPostProcess = /** @class */ (function (_super) {
  78871. __extends(HighlightsPostProcess, _super);
  78872. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  78873. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78874. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78875. }
  78876. return HighlightsPostProcess;
  78877. }(BABYLON.PostProcess));
  78878. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  78879. })(BABYLON || (BABYLON = {}));
  78880. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  78881. var BABYLON;
  78882. (function (BABYLON) {
  78883. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  78884. __extends(ImageProcessingPostProcess, _super);
  78885. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  78886. if (camera === void 0) { camera = null; }
  78887. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78888. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  78889. _this._fromLinearSpace = true;
  78890. /**
  78891. * Defines cache preventing GC.
  78892. */
  78893. _this._defines = {
  78894. IMAGEPROCESSING: false,
  78895. VIGNETTE: false,
  78896. VIGNETTEBLENDMODEMULTIPLY: false,
  78897. VIGNETTEBLENDMODEOPAQUE: false,
  78898. TONEMAPPING: false,
  78899. CONTRAST: false,
  78900. COLORCURVES: false,
  78901. COLORGRADING: false,
  78902. COLORGRADING3D: false,
  78903. FROMLINEARSPACE: false,
  78904. SAMPLER3DGREENDEPTH: false,
  78905. SAMPLER3DBGRMAP: false,
  78906. IMAGEPROCESSINGPOSTPROCESS: false,
  78907. EXPOSURE: false,
  78908. };
  78909. // Setup the configuration as forced by the constructor. This would then not force the
  78910. // scene materials output in linear space and let untouched the default forward pass.
  78911. if (imageProcessingConfiguration) {
  78912. imageProcessingConfiguration.applyByPostProcess = true;
  78913. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  78914. // This will cause the shader to be compiled
  78915. _this.fromLinearSpace = false;
  78916. }
  78917. // Setup the default processing configuration to the scene.
  78918. else {
  78919. _this._attachImageProcessingConfiguration(null, true);
  78920. _this.imageProcessingConfiguration.applyByPostProcess = true;
  78921. }
  78922. _this.onApply = function (effect) {
  78923. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  78924. };
  78925. return _this;
  78926. }
  78927. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  78928. /**
  78929. * Gets the image processing configuration used either in this material.
  78930. */
  78931. get: function () {
  78932. return this._imageProcessingConfiguration;
  78933. },
  78934. /**
  78935. * Sets the Default image processing configuration used either in the this material.
  78936. *
  78937. * If sets to null, the scene one is in use.
  78938. */
  78939. set: function (value) {
  78940. this._attachImageProcessingConfiguration(value);
  78941. },
  78942. enumerable: true,
  78943. configurable: true
  78944. });
  78945. /**
  78946. * Attaches a new image processing configuration to the PBR Material.
  78947. * @param configuration
  78948. */
  78949. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  78950. var _this = this;
  78951. if (doNotBuild === void 0) { doNotBuild = false; }
  78952. if (configuration === this._imageProcessingConfiguration) {
  78953. return;
  78954. }
  78955. // Detaches observer.
  78956. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  78957. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  78958. }
  78959. // Pick the scene configuration if needed.
  78960. if (!configuration) {
  78961. var scene = null;
  78962. var engine = this.getEngine();
  78963. var camera = this.getCamera();
  78964. if (camera) {
  78965. scene = camera.getScene();
  78966. }
  78967. else if (engine && engine.scenes) {
  78968. var scenes = engine.scenes;
  78969. scene = scenes[scenes.length - 1];
  78970. }
  78971. else {
  78972. scene = BABYLON.Engine.LastCreatedScene;
  78973. }
  78974. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  78975. }
  78976. else {
  78977. this._imageProcessingConfiguration = configuration;
  78978. }
  78979. // Attaches observer.
  78980. if (this._imageProcessingConfiguration) {
  78981. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  78982. _this._updateParameters();
  78983. });
  78984. }
  78985. // Ensure the effect will be rebuilt.
  78986. if (!doNotBuild) {
  78987. this._updateParameters();
  78988. }
  78989. };
  78990. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  78991. /**
  78992. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78993. */
  78994. get: function () {
  78995. return this.imageProcessingConfiguration.colorCurves;
  78996. },
  78997. /**
  78998. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  78999. */
  79000. set: function (value) {
  79001. this.imageProcessingConfiguration.colorCurves = value;
  79002. },
  79003. enumerable: true,
  79004. configurable: true
  79005. });
  79006. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79007. /**
  79008. * Gets wether the color curves effect is enabled.
  79009. */
  79010. get: function () {
  79011. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79012. },
  79013. /**
  79014. * Sets wether the color curves effect is enabled.
  79015. */
  79016. set: function (value) {
  79017. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79018. },
  79019. enumerable: true,
  79020. configurable: true
  79021. });
  79022. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79023. /**
  79024. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79025. */
  79026. get: function () {
  79027. return this.imageProcessingConfiguration.colorGradingTexture;
  79028. },
  79029. /**
  79030. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79031. */
  79032. set: function (value) {
  79033. this.imageProcessingConfiguration.colorGradingTexture = value;
  79034. },
  79035. enumerable: true,
  79036. configurable: true
  79037. });
  79038. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79039. /**
  79040. * Gets wether the color grading effect is enabled.
  79041. */
  79042. get: function () {
  79043. return this.imageProcessingConfiguration.colorGradingEnabled;
  79044. },
  79045. /**
  79046. * Gets wether the color grading effect is enabled.
  79047. */
  79048. set: function (value) {
  79049. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79050. },
  79051. enumerable: true,
  79052. configurable: true
  79053. });
  79054. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79055. /**
  79056. * Gets exposure used in the effect.
  79057. */
  79058. get: function () {
  79059. return this.imageProcessingConfiguration.exposure;
  79060. },
  79061. /**
  79062. * Sets exposure used in the effect.
  79063. */
  79064. set: function (value) {
  79065. this.imageProcessingConfiguration.exposure = value;
  79066. },
  79067. enumerable: true,
  79068. configurable: true
  79069. });
  79070. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79071. /**
  79072. * Gets wether tonemapping is enabled or not.
  79073. */
  79074. get: function () {
  79075. return this._imageProcessingConfiguration.toneMappingEnabled;
  79076. },
  79077. /**
  79078. * Sets wether tonemapping is enabled or not
  79079. */
  79080. set: function (value) {
  79081. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79082. },
  79083. enumerable: true,
  79084. configurable: true
  79085. });
  79086. ;
  79087. ;
  79088. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79089. /**
  79090. * Gets contrast used in the effect.
  79091. */
  79092. get: function () {
  79093. return this.imageProcessingConfiguration.contrast;
  79094. },
  79095. /**
  79096. * Sets contrast used in the effect.
  79097. */
  79098. set: function (value) {
  79099. this.imageProcessingConfiguration.contrast = value;
  79100. },
  79101. enumerable: true,
  79102. configurable: true
  79103. });
  79104. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79105. /**
  79106. * Gets Vignette stretch size.
  79107. */
  79108. get: function () {
  79109. return this.imageProcessingConfiguration.vignetteStretch;
  79110. },
  79111. /**
  79112. * Sets Vignette stretch size.
  79113. */
  79114. set: function (value) {
  79115. this.imageProcessingConfiguration.vignetteStretch = value;
  79116. },
  79117. enumerable: true,
  79118. configurable: true
  79119. });
  79120. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79121. /**
  79122. * Gets Vignette centre X Offset.
  79123. */
  79124. get: function () {
  79125. return this.imageProcessingConfiguration.vignetteCentreX;
  79126. },
  79127. /**
  79128. * Sets Vignette centre X Offset.
  79129. */
  79130. set: function (value) {
  79131. this.imageProcessingConfiguration.vignetteCentreX = value;
  79132. },
  79133. enumerable: true,
  79134. configurable: true
  79135. });
  79136. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79137. /**
  79138. * Gets Vignette centre Y Offset.
  79139. */
  79140. get: function () {
  79141. return this.imageProcessingConfiguration.vignetteCentreY;
  79142. },
  79143. /**
  79144. * Sets Vignette centre Y Offset.
  79145. */
  79146. set: function (value) {
  79147. this.imageProcessingConfiguration.vignetteCentreY = value;
  79148. },
  79149. enumerable: true,
  79150. configurable: true
  79151. });
  79152. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79153. /**
  79154. * Gets Vignette weight or intensity of the vignette effect.
  79155. */
  79156. get: function () {
  79157. return this.imageProcessingConfiguration.vignetteWeight;
  79158. },
  79159. /**
  79160. * Sets Vignette weight or intensity of the vignette effect.
  79161. */
  79162. set: function (value) {
  79163. this.imageProcessingConfiguration.vignetteWeight = value;
  79164. },
  79165. enumerable: true,
  79166. configurable: true
  79167. });
  79168. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79169. /**
  79170. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79171. * if vignetteEnabled is set to true.
  79172. */
  79173. get: function () {
  79174. return this.imageProcessingConfiguration.vignetteColor;
  79175. },
  79176. /**
  79177. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79178. * if vignetteEnabled is set to true.
  79179. */
  79180. set: function (value) {
  79181. this.imageProcessingConfiguration.vignetteColor = value;
  79182. },
  79183. enumerable: true,
  79184. configurable: true
  79185. });
  79186. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79187. /**
  79188. * Gets Camera field of view used by the Vignette effect.
  79189. */
  79190. get: function () {
  79191. return this.imageProcessingConfiguration.vignetteCameraFov;
  79192. },
  79193. /**
  79194. * Sets Camera field of view used by the Vignette effect.
  79195. */
  79196. set: function (value) {
  79197. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79198. },
  79199. enumerable: true,
  79200. configurable: true
  79201. });
  79202. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79203. /**
  79204. * Gets the vignette blend mode allowing different kind of effect.
  79205. */
  79206. get: function () {
  79207. return this.imageProcessingConfiguration.vignetteBlendMode;
  79208. },
  79209. /**
  79210. * Sets the vignette blend mode allowing different kind of effect.
  79211. */
  79212. set: function (value) {
  79213. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79214. },
  79215. enumerable: true,
  79216. configurable: true
  79217. });
  79218. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79219. /**
  79220. * Gets wether the vignette effect is enabled.
  79221. */
  79222. get: function () {
  79223. return this.imageProcessingConfiguration.vignetteEnabled;
  79224. },
  79225. /**
  79226. * Sets wether the vignette effect is enabled.
  79227. */
  79228. set: function (value) {
  79229. this.imageProcessingConfiguration.vignetteEnabled = value;
  79230. },
  79231. enumerable: true,
  79232. configurable: true
  79233. });
  79234. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79235. /**
  79236. * Gets wether the input of the processing is in Gamma or Linear Space.
  79237. */
  79238. get: function () {
  79239. return this._fromLinearSpace;
  79240. },
  79241. /**
  79242. * Sets wether the input of the processing is in Gamma or Linear Space.
  79243. */
  79244. set: function (value) {
  79245. if (this._fromLinearSpace === value) {
  79246. return;
  79247. }
  79248. this._fromLinearSpace = value;
  79249. this._updateParameters();
  79250. },
  79251. enumerable: true,
  79252. configurable: true
  79253. });
  79254. ImageProcessingPostProcess.prototype.getClassName = function () {
  79255. return "ImageProcessingPostProcess";
  79256. };
  79257. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79258. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79259. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79260. var defines = "";
  79261. for (var define in this._defines) {
  79262. if (this._defines[define]) {
  79263. defines += "#define " + define + ";\r\n";
  79264. }
  79265. }
  79266. var samplers = ["textureSampler"];
  79267. var uniforms = ["scale"];
  79268. if (BABYLON.ImageProcessingConfiguration) {
  79269. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79270. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79271. }
  79272. this.updateEffect(defines, uniforms, samplers);
  79273. };
  79274. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79275. _super.prototype.dispose.call(this, camera);
  79276. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79277. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79278. }
  79279. if (this._imageProcessingConfiguration) {
  79280. this.imageProcessingConfiguration.applyByPostProcess = false;
  79281. }
  79282. };
  79283. __decorate([
  79284. BABYLON.serialize()
  79285. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79286. return ImageProcessingPostProcess;
  79287. }(BABYLON.PostProcess));
  79288. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79289. })(BABYLON || (BABYLON = {}));
  79290. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79291. var BABYLON;
  79292. (function (BABYLON) {
  79293. /**
  79294. * Class used to store bone information
  79295. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79296. */
  79297. var Bone = /** @class */ (function (_super) {
  79298. __extends(Bone, _super);
  79299. /**
  79300. * Create a new bone
  79301. * @param name defines the bone name
  79302. * @param skeleton defines the parent skeleton
  79303. * @param parentBone defines the parent (can be null if the bone is the root)
  79304. * @param localMatrix defines the local matrix
  79305. * @param restPose defines the rest pose matrix
  79306. * @param baseMatrix defines the base matrix
  79307. * @param index defines index of the bone in the hiearchy
  79308. */
  79309. function Bone(
  79310. /**
  79311. * defines the bone name
  79312. */
  79313. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79314. if (parentBone === void 0) { parentBone = null; }
  79315. if (localMatrix === void 0) { localMatrix = null; }
  79316. if (restPose === void 0) { restPose = null; }
  79317. if (baseMatrix === void 0) { baseMatrix = null; }
  79318. if (index === void 0) { index = null; }
  79319. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79320. _this.name = name;
  79321. /**
  79322. * Gets the list of child bones
  79323. */
  79324. _this.children = new Array();
  79325. /** Gets the animations associated with this bone */
  79326. _this.animations = new Array();
  79327. /**
  79328. * @hidden Internal only
  79329. * Set this value to map this bone to a different index in the transform matrices
  79330. * Set this value to -1 to exclude the bone from the transform matrices
  79331. */
  79332. _this._index = null;
  79333. _this._absoluteTransform = new BABYLON.Matrix();
  79334. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79335. _this._scalingDeterminant = 1;
  79336. _this._worldTransform = new BABYLON.Matrix();
  79337. _this._needToDecompose = true;
  79338. _this._needToCompose = false;
  79339. _this._skeleton = skeleton;
  79340. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79341. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79342. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79343. _this._index = index;
  79344. skeleton.bones.push(_this);
  79345. _this.setParent(parentBone, false);
  79346. if (baseMatrix || localMatrix) {
  79347. _this._updateDifferenceMatrix();
  79348. }
  79349. return _this;
  79350. }
  79351. Object.defineProperty(Bone.prototype, "_matrix", {
  79352. /** @hidden */
  79353. get: function () {
  79354. this._compose();
  79355. return this._localMatrix;
  79356. },
  79357. /** @hidden */
  79358. set: function (value) {
  79359. this._localMatrix.copyFrom(value);
  79360. this._needToDecompose = true;
  79361. },
  79362. enumerable: true,
  79363. configurable: true
  79364. });
  79365. // Members
  79366. /**
  79367. * Gets the parent skeleton
  79368. * @returns a skeleton
  79369. */
  79370. Bone.prototype.getSkeleton = function () {
  79371. return this._skeleton;
  79372. };
  79373. /**
  79374. * Gets parent bone
  79375. * @returns a bone or null if the bone is the root of the bone hierarchy
  79376. */
  79377. Bone.prototype.getParent = function () {
  79378. return this._parent;
  79379. };
  79380. /**
  79381. * Sets the parent bone
  79382. * @param parent defines the parent (can be null if the bone is the root)
  79383. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79384. */
  79385. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79386. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79387. if (this._parent === parent) {
  79388. return;
  79389. }
  79390. if (this._parent) {
  79391. var index = this._parent.children.indexOf(this);
  79392. if (index !== -1) {
  79393. this._parent.children.splice(index, 1);
  79394. }
  79395. }
  79396. this._parent = parent;
  79397. if (this._parent) {
  79398. this._parent.children.push(this);
  79399. }
  79400. if (updateDifferenceMatrix) {
  79401. this._updateDifferenceMatrix();
  79402. }
  79403. this.markAsDirty();
  79404. };
  79405. /**
  79406. * Gets the local matrix
  79407. * @returns a matrix
  79408. */
  79409. Bone.prototype.getLocalMatrix = function () {
  79410. this._compose();
  79411. return this._localMatrix;
  79412. };
  79413. /**
  79414. * Gets the base matrix (initial matrix which remains unchanged)
  79415. * @returns a matrix
  79416. */
  79417. Bone.prototype.getBaseMatrix = function () {
  79418. return this._baseMatrix;
  79419. };
  79420. /**
  79421. * Gets the rest pose matrix
  79422. * @returns a matrix
  79423. */
  79424. Bone.prototype.getRestPose = function () {
  79425. return this._restPose;
  79426. };
  79427. /**
  79428. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79429. */
  79430. Bone.prototype.getWorldMatrix = function () {
  79431. return this._worldTransform;
  79432. };
  79433. /**
  79434. * Sets the local matrix to rest pose matrix
  79435. */
  79436. Bone.prototype.returnToRest = function () {
  79437. this.updateMatrix(this._restPose.clone());
  79438. };
  79439. /**
  79440. * Gets the inverse of the absolute transform matrix.
  79441. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79442. * @returns a matrix
  79443. */
  79444. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79445. return this._invertedAbsoluteTransform;
  79446. };
  79447. /**
  79448. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79449. * @returns a matrix
  79450. */
  79451. Bone.prototype.getAbsoluteTransform = function () {
  79452. return this._absoluteTransform;
  79453. };
  79454. Object.defineProperty(Bone.prototype, "position", {
  79455. // Properties (matches AbstractMesh properties)
  79456. /** Gets or sets current position (in local space) */
  79457. get: function () {
  79458. this._decompose();
  79459. return this._localPosition;
  79460. },
  79461. set: function (newPosition) {
  79462. this._decompose();
  79463. this._localPosition.copyFrom(newPosition);
  79464. this._markAsDirtyAndCompose();
  79465. },
  79466. enumerable: true,
  79467. configurable: true
  79468. });
  79469. Object.defineProperty(Bone.prototype, "rotation", {
  79470. /** Gets or sets current rotation (in local space) */
  79471. get: function () {
  79472. return this.getRotation();
  79473. },
  79474. set: function (newRotation) {
  79475. this.setRotation(newRotation);
  79476. },
  79477. enumerable: true,
  79478. configurable: true
  79479. });
  79480. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79481. /** Gets or sets current rotation quaternion (in local space) */
  79482. get: function () {
  79483. this._decompose();
  79484. return this._localRotation;
  79485. },
  79486. set: function (newRotation) {
  79487. this.setRotationQuaternion(newRotation);
  79488. },
  79489. enumerable: true,
  79490. configurable: true
  79491. });
  79492. Object.defineProperty(Bone.prototype, "scaling", {
  79493. /** Gets or sets current scaling (in local space) */
  79494. get: function () {
  79495. return this.getScale();
  79496. },
  79497. set: function (newScaling) {
  79498. this.setScale(newScaling);
  79499. },
  79500. enumerable: true,
  79501. configurable: true
  79502. });
  79503. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79504. /**
  79505. * Gets the animation properties override
  79506. */
  79507. get: function () {
  79508. return this._skeleton.animationPropertiesOverride;
  79509. },
  79510. enumerable: true,
  79511. configurable: true
  79512. });
  79513. // Methods
  79514. Bone.prototype._decompose = function () {
  79515. if (!this._needToDecompose) {
  79516. return;
  79517. }
  79518. this._needToDecompose = false;
  79519. if (!this._localScaling) {
  79520. this._localScaling = BABYLON.Vector3.Zero();
  79521. this._localRotation = BABYLON.Quaternion.Zero();
  79522. this._localPosition = BABYLON.Vector3.Zero();
  79523. }
  79524. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79525. };
  79526. Bone.prototype._compose = function () {
  79527. if (!this._needToCompose) {
  79528. return;
  79529. }
  79530. this._needToCompose = false;
  79531. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79532. };
  79533. /**
  79534. * Update the base and local matrices
  79535. * @param matrix defines the new base or local matrix
  79536. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79537. * @param updateLocalMatrix defines if the local matrix should be updated
  79538. */
  79539. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79540. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79541. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79542. this._baseMatrix.copyFrom(matrix);
  79543. if (updateDifferenceMatrix) {
  79544. this._updateDifferenceMatrix();
  79545. }
  79546. if (updateLocalMatrix) {
  79547. this._localMatrix.copyFrom(matrix);
  79548. this._markAsDirtyAndDecompose();
  79549. }
  79550. else {
  79551. this.markAsDirty();
  79552. }
  79553. };
  79554. /** @hidden */
  79555. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79556. if (updateChildren === void 0) { updateChildren = true; }
  79557. if (!rootMatrix) {
  79558. rootMatrix = this._baseMatrix;
  79559. }
  79560. if (this._parent) {
  79561. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79562. }
  79563. else {
  79564. this._absoluteTransform.copyFrom(rootMatrix);
  79565. }
  79566. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79567. if (updateChildren) {
  79568. for (var index = 0; index < this.children.length; index++) {
  79569. this.children[index]._updateDifferenceMatrix();
  79570. }
  79571. }
  79572. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79573. };
  79574. /**
  79575. * Flag the bone as dirty (Forcing it to update everything)
  79576. */
  79577. Bone.prototype.markAsDirty = function () {
  79578. this._currentRenderId++;
  79579. this._childRenderId++;
  79580. this._skeleton._markAsDirty();
  79581. };
  79582. Bone.prototype._markAsDirtyAndCompose = function () {
  79583. this.markAsDirty();
  79584. this._needToCompose = true;
  79585. };
  79586. Bone.prototype._markAsDirtyAndDecompose = function () {
  79587. this.markAsDirty();
  79588. this._needToDecompose = true;
  79589. };
  79590. /**
  79591. * Copy an animation range from another bone
  79592. * @param source defines the source bone
  79593. * @param rangeName defines the range name to copy
  79594. * @param frameOffset defines the frame offset
  79595. * @param rescaleAsRequired defines if rescaling must be applied if required
  79596. * @param skelDimensionsRatio defines the scaling ratio
  79597. * @returns true if operation was successful
  79598. */
  79599. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79600. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79601. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79602. // all animation may be coming from a library skeleton, so may need to create animation
  79603. if (this.animations.length === 0) {
  79604. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79605. this.animations[0].setKeys([]);
  79606. }
  79607. // get animation info / verify there is such a range from the source bone
  79608. var sourceRange = source.animations[0].getRange(rangeName);
  79609. if (!sourceRange) {
  79610. return false;
  79611. }
  79612. var from = sourceRange.from;
  79613. var to = sourceRange.to;
  79614. var sourceKeys = source.animations[0].getKeys();
  79615. // rescaling prep
  79616. var sourceBoneLength = source.length;
  79617. var sourceParent = source.getParent();
  79618. var parent = this.getParent();
  79619. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79620. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79621. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79622. var destKeys = this.animations[0].getKeys();
  79623. // loop vars declaration
  79624. var orig;
  79625. var origTranslation;
  79626. var mat;
  79627. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79628. orig = sourceKeys[key];
  79629. if (orig.frame >= from && orig.frame <= to) {
  79630. if (rescaleAsRequired) {
  79631. mat = orig.value.clone();
  79632. // scale based on parent ratio, when bone has parent
  79633. if (parentScalingReqd) {
  79634. origTranslation = mat.getTranslation();
  79635. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79636. // scale based on skeleton dimension ratio when root bone, and value is passed
  79637. }
  79638. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79639. origTranslation = mat.getTranslation();
  79640. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79641. // use original when root bone, and no data for skelDimensionsRatio
  79642. }
  79643. else {
  79644. mat = orig.value;
  79645. }
  79646. }
  79647. else {
  79648. mat = orig.value;
  79649. }
  79650. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79651. }
  79652. }
  79653. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79654. return true;
  79655. };
  79656. /**
  79657. * Translate the bone in local or world space
  79658. * @param vec The amount to translate the bone
  79659. * @param space The space that the translation is in
  79660. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79661. */
  79662. Bone.prototype.translate = function (vec, space, mesh) {
  79663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79664. var lm = this.getLocalMatrix();
  79665. if (space == BABYLON.Space.LOCAL) {
  79666. lm.m[12] += vec.x;
  79667. lm.m[13] += vec.y;
  79668. lm.m[14] += vec.z;
  79669. }
  79670. else {
  79671. var wm = null;
  79672. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79673. if (mesh) {
  79674. wm = mesh.getWorldMatrix();
  79675. }
  79676. this._skeleton.computeAbsoluteTransforms();
  79677. var tmat = Bone._tmpMats[0];
  79678. var tvec = Bone._tmpVecs[0];
  79679. if (this._parent) {
  79680. if (mesh && wm) {
  79681. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79682. tmat.multiplyToRef(wm, tmat);
  79683. }
  79684. else {
  79685. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79686. }
  79687. }
  79688. tmat.m[12] = 0;
  79689. tmat.m[13] = 0;
  79690. tmat.m[14] = 0;
  79691. tmat.invert();
  79692. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79693. lm.m[12] += tvec.x;
  79694. lm.m[13] += tvec.y;
  79695. lm.m[14] += tvec.z;
  79696. }
  79697. this._markAsDirtyAndDecompose();
  79698. };
  79699. /**
  79700. * Set the postion of the bone in local or world space
  79701. * @param position The position to set the bone
  79702. * @param space The space that the position is in
  79703. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79704. */
  79705. Bone.prototype.setPosition = function (position, space, mesh) {
  79706. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79707. var lm = this.getLocalMatrix();
  79708. if (space == BABYLON.Space.LOCAL) {
  79709. lm.m[12] = position.x;
  79710. lm.m[13] = position.y;
  79711. lm.m[14] = position.z;
  79712. }
  79713. else {
  79714. var wm = null;
  79715. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79716. if (mesh) {
  79717. wm = mesh.getWorldMatrix();
  79718. }
  79719. this._skeleton.computeAbsoluteTransforms();
  79720. var tmat = Bone._tmpMats[0];
  79721. var vec = Bone._tmpVecs[0];
  79722. if (this._parent) {
  79723. if (mesh && wm) {
  79724. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79725. tmat.multiplyToRef(wm, tmat);
  79726. }
  79727. else {
  79728. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79729. }
  79730. }
  79731. tmat.invert();
  79732. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79733. lm.m[12] = vec.x;
  79734. lm.m[13] = vec.y;
  79735. lm.m[14] = vec.z;
  79736. }
  79737. this._markAsDirtyAndDecompose();
  79738. };
  79739. /**
  79740. * Set the absolute position of the bone (world space)
  79741. * @param position The position to set the bone
  79742. * @param mesh The mesh that this bone is attached to
  79743. */
  79744. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79745. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79746. };
  79747. /**
  79748. * Scale the bone on the x, y and z axes (in local space)
  79749. * @param x The amount to scale the bone on the x axis
  79750. * @param y The amount to scale the bone on the y axis
  79751. * @param z The amount to scale the bone on the z axis
  79752. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79753. */
  79754. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79755. if (scaleChildren === void 0) { scaleChildren = false; }
  79756. var locMat = this.getLocalMatrix();
  79757. // Apply new scaling on top of current local matrix
  79758. var scaleMat = Bone._tmpMats[0];
  79759. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79760. scaleMat.multiplyToRef(locMat, locMat);
  79761. // Invert scaling matrix and apply the inverse to all children
  79762. scaleMat.invert();
  79763. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79764. var child = _a[_i];
  79765. var cm = child.getLocalMatrix();
  79766. cm.multiplyToRef(scaleMat, cm);
  79767. cm.m[12] *= x;
  79768. cm.m[13] *= y;
  79769. cm.m[14] *= z;
  79770. child._markAsDirtyAndDecompose();
  79771. }
  79772. this._markAsDirtyAndDecompose();
  79773. if (scaleChildren) {
  79774. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79775. var child = _c[_b];
  79776. child.scale(x, y, z, scaleChildren);
  79777. }
  79778. }
  79779. };
  79780. /**
  79781. * Set the bone scaling in local space
  79782. * @param scale defines the scaling vector
  79783. */
  79784. Bone.prototype.setScale = function (scale) {
  79785. this._decompose();
  79786. this._localScaling.copyFrom(scale);
  79787. this._markAsDirtyAndCompose();
  79788. };
  79789. /**
  79790. * Gets the current scaling in local space
  79791. * @returns the current scaling vector
  79792. */
  79793. Bone.prototype.getScale = function () {
  79794. this._decompose();
  79795. return this._localScaling;
  79796. };
  79797. /**
  79798. * Gets the current scaling in local space and stores it in a target vector
  79799. * @param result defines the target vector
  79800. */
  79801. Bone.prototype.getScaleToRef = function (result) {
  79802. this._decompose();
  79803. result.copyFrom(this._localScaling);
  79804. };
  79805. /**
  79806. * Set the yaw, pitch, and roll of the bone in local or world space
  79807. * @param yaw The rotation of the bone on the y axis
  79808. * @param pitch The rotation of the bone on the x axis
  79809. * @param roll The rotation of the bone on the z axis
  79810. * @param space The space that the axes of rotation are in
  79811. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79812. */
  79813. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79814. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79815. if (space === BABYLON.Space.LOCAL) {
  79816. var quat = Bone._tmpQuat;
  79817. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79818. this.setRotationQuaternion(quat, space, mesh);
  79819. return;
  79820. }
  79821. var rotMatInv = Bone._tmpMats[0];
  79822. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79823. return;
  79824. }
  79825. var rotMat = Bone._tmpMats[1];
  79826. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79827. rotMatInv.multiplyToRef(rotMat, rotMat);
  79828. this._rotateWithMatrix(rotMat, space, mesh);
  79829. };
  79830. /**
  79831. * Add a rotation to the bone on an axis in local or world space
  79832. * @param axis The axis to rotate the bone on
  79833. * @param amount The amount to rotate the bone
  79834. * @param space The space that the axis is in
  79835. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79836. */
  79837. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  79838. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79839. var rmat = Bone._tmpMats[0];
  79840. rmat.m[12] = 0;
  79841. rmat.m[13] = 0;
  79842. rmat.m[14] = 0;
  79843. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  79844. this._rotateWithMatrix(rmat, space, mesh);
  79845. };
  79846. /**
  79847. * Set the rotation of the bone to a particular axis angle in local or world space
  79848. * @param axis The axis to rotate the bone on
  79849. * @param angle The angle that the bone should be rotated to
  79850. * @param space The space that the axis is in
  79851. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79852. */
  79853. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  79854. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79855. if (space === BABYLON.Space.LOCAL) {
  79856. var quat = Bone._tmpQuat;
  79857. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  79858. this.setRotationQuaternion(quat, space, mesh);
  79859. return;
  79860. }
  79861. var rotMatInv = Bone._tmpMats[0];
  79862. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79863. return;
  79864. }
  79865. var rotMat = Bone._tmpMats[1];
  79866. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  79867. rotMatInv.multiplyToRef(rotMat, rotMat);
  79868. this._rotateWithMatrix(rotMat, space, mesh);
  79869. };
  79870. /**
  79871. * Set the euler rotation of the bone in local of world space
  79872. * @param rotation The euler rotation that the bone should be set to
  79873. * @param space The space that the rotation is in
  79874. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79875. */
  79876. Bone.prototype.setRotation = function (rotation, space, mesh) {
  79877. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79878. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  79879. };
  79880. /**
  79881. * Set the quaternion rotation of the bone in local of world space
  79882. * @param quat The quaternion rotation that the bone should be set to
  79883. * @param space The space that the rotation is in
  79884. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79885. */
  79886. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  79887. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79888. if (space === BABYLON.Space.LOCAL) {
  79889. this._decompose();
  79890. this._localRotation.copyFrom(quat);
  79891. this._markAsDirtyAndCompose();
  79892. return;
  79893. }
  79894. var rotMatInv = Bone._tmpMats[0];
  79895. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79896. return;
  79897. }
  79898. var rotMat = Bone._tmpMats[1];
  79899. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  79900. rotMatInv.multiplyToRef(rotMat, rotMat);
  79901. this._rotateWithMatrix(rotMat, space, mesh);
  79902. };
  79903. /**
  79904. * Set the rotation matrix of the bone in local of world space
  79905. * @param rotMat The rotation matrix that the bone should be set to
  79906. * @param space The space that the rotation is in
  79907. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79908. */
  79909. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  79910. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79911. if (space === BABYLON.Space.LOCAL) {
  79912. var quat = Bone._tmpQuat;
  79913. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  79914. this.setRotationQuaternion(quat, space, mesh);
  79915. return;
  79916. }
  79917. var rotMatInv = Bone._tmpMats[0];
  79918. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79919. return;
  79920. }
  79921. var rotMat2 = Bone._tmpMats[1];
  79922. rotMat2.copyFrom(rotMat);
  79923. rotMatInv.multiplyToRef(rotMat, rotMat2);
  79924. this._rotateWithMatrix(rotMat2, space, mesh);
  79925. };
  79926. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  79927. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79928. var lmat = this.getLocalMatrix();
  79929. var lx = lmat.m[12];
  79930. var ly = lmat.m[13];
  79931. var lz = lmat.m[14];
  79932. var parent = this.getParent();
  79933. var parentScale = Bone._tmpMats[3];
  79934. var parentScaleInv = Bone._tmpMats[4];
  79935. if (parent && space == BABYLON.Space.WORLD) {
  79936. if (mesh) {
  79937. parentScale.copyFrom(mesh.getWorldMatrix());
  79938. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  79939. }
  79940. else {
  79941. parentScale.copyFrom(parent.getAbsoluteTransform());
  79942. }
  79943. parentScaleInv.copyFrom(parentScale);
  79944. parentScaleInv.invert();
  79945. lmat.multiplyToRef(parentScale, lmat);
  79946. lmat.multiplyToRef(rmat, lmat);
  79947. lmat.multiplyToRef(parentScaleInv, lmat);
  79948. }
  79949. else {
  79950. if (space == BABYLON.Space.WORLD && mesh) {
  79951. parentScale.copyFrom(mesh.getWorldMatrix());
  79952. parentScaleInv.copyFrom(parentScale);
  79953. parentScaleInv.invert();
  79954. lmat.multiplyToRef(parentScale, lmat);
  79955. lmat.multiplyToRef(rmat, lmat);
  79956. lmat.multiplyToRef(parentScaleInv, lmat);
  79957. }
  79958. else {
  79959. lmat.multiplyToRef(rmat, lmat);
  79960. }
  79961. }
  79962. lmat.m[12] = lx;
  79963. lmat.m[13] = ly;
  79964. lmat.m[14] = lz;
  79965. this.computeAbsoluteTransforms();
  79966. this._markAsDirtyAndDecompose();
  79967. };
  79968. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  79969. var scaleMatrix = Bone._tmpMats[2];
  79970. rotMatInv.copyFrom(this.getAbsoluteTransform());
  79971. if (mesh) {
  79972. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  79973. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  79974. }
  79975. rotMatInv.invert();
  79976. if (isNaN(rotMatInv.m[0])) {
  79977. // Matrix failed to invert.
  79978. // This can happen if scale is zero for example.
  79979. return false;
  79980. }
  79981. scaleMatrix.m[0] *= this._scalingDeterminant;
  79982. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  79983. return true;
  79984. };
  79985. /**
  79986. * Get the position of the bone in local or world space
  79987. * @param space The space that the returned position is in
  79988. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79989. * @returns The position of the bone
  79990. */
  79991. Bone.prototype.getPosition = function (space, mesh) {
  79992. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79993. if (mesh === void 0) { mesh = null; }
  79994. var pos = BABYLON.Vector3.Zero();
  79995. this.getPositionToRef(space, mesh, pos);
  79996. return pos;
  79997. };
  79998. /**
  79999. * Copy the position of the bone to a vector3 in local or world space
  80000. * @param space The space that the returned position is in
  80001. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80002. * @param result The vector3 to copy the position to
  80003. */
  80004. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80006. if (space == BABYLON.Space.LOCAL) {
  80007. var lm = this.getLocalMatrix();
  80008. result.x = lm.m[12];
  80009. result.y = lm.m[13];
  80010. result.z = lm.m[14];
  80011. }
  80012. else {
  80013. var wm = null;
  80014. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80015. if (mesh) {
  80016. wm = mesh.getWorldMatrix();
  80017. }
  80018. this._skeleton.computeAbsoluteTransforms();
  80019. var tmat = Bone._tmpMats[0];
  80020. if (mesh && wm) {
  80021. tmat.copyFrom(this.getAbsoluteTransform());
  80022. tmat.multiplyToRef(wm, tmat);
  80023. }
  80024. else {
  80025. tmat = this.getAbsoluteTransform();
  80026. }
  80027. result.x = tmat.m[12];
  80028. result.y = tmat.m[13];
  80029. result.z = tmat.m[14];
  80030. }
  80031. };
  80032. /**
  80033. * Get the absolute position of the bone (world space)
  80034. * @param mesh The mesh that this bone is attached to
  80035. * @returns The absolute position of the bone
  80036. */
  80037. Bone.prototype.getAbsolutePosition = function (mesh) {
  80038. if (mesh === void 0) { mesh = null; }
  80039. var pos = BABYLON.Vector3.Zero();
  80040. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80041. return pos;
  80042. };
  80043. /**
  80044. * Copy the absolute position of the bone (world space) to the result param
  80045. * @param mesh The mesh that this bone is attached to
  80046. * @param result The vector3 to copy the absolute position to
  80047. */
  80048. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80049. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80050. };
  80051. /**
  80052. * Compute the absolute transforms of this bone and its children
  80053. */
  80054. Bone.prototype.computeAbsoluteTransforms = function () {
  80055. this._compose();
  80056. if (this._parent) {
  80057. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80058. }
  80059. else {
  80060. this._absoluteTransform.copyFrom(this._localMatrix);
  80061. var poseMatrix = this._skeleton.getPoseMatrix();
  80062. if (poseMatrix) {
  80063. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80064. }
  80065. }
  80066. var children = this.children;
  80067. var len = children.length;
  80068. for (var i = 0; i < len; i++) {
  80069. children[i].computeAbsoluteTransforms();
  80070. }
  80071. };
  80072. /**
  80073. * Get the world direction from an axis that is in the local space of the bone
  80074. * @param localAxis The local direction that is used to compute the world direction
  80075. * @param mesh The mesh that this bone is attached to
  80076. * @returns The world direction
  80077. */
  80078. Bone.prototype.getDirection = function (localAxis, mesh) {
  80079. if (mesh === void 0) { mesh = null; }
  80080. var result = BABYLON.Vector3.Zero();
  80081. this.getDirectionToRef(localAxis, mesh, result);
  80082. return result;
  80083. };
  80084. /**
  80085. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80086. * @param localAxis The local direction that is used to compute the world direction
  80087. * @param mesh The mesh that this bone is attached to
  80088. * @param result The vector3 that the world direction will be copied to
  80089. */
  80090. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80091. if (mesh === void 0) { mesh = null; }
  80092. var wm = null;
  80093. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80094. if (mesh) {
  80095. wm = mesh.getWorldMatrix();
  80096. }
  80097. this._skeleton.computeAbsoluteTransforms();
  80098. var mat = Bone._tmpMats[0];
  80099. mat.copyFrom(this.getAbsoluteTransform());
  80100. if (mesh && wm) {
  80101. mat.multiplyToRef(wm, mat);
  80102. }
  80103. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80104. result.normalize();
  80105. };
  80106. /**
  80107. * Get the euler rotation of the bone in local or world space
  80108. * @param space The space that the rotation should be in
  80109. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80110. * @returns The euler rotation
  80111. */
  80112. Bone.prototype.getRotation = function (space, mesh) {
  80113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80114. if (mesh === void 0) { mesh = null; }
  80115. var result = BABYLON.Vector3.Zero();
  80116. this.getRotationToRef(space, mesh, result);
  80117. return result;
  80118. };
  80119. /**
  80120. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80121. * @param space The space that the rotation should be in
  80122. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80123. * @param result The vector3 that the rotation should be copied to
  80124. */
  80125. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80126. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80127. if (mesh === void 0) { mesh = null; }
  80128. var quat = Bone._tmpQuat;
  80129. this.getRotationQuaternionToRef(space, mesh, quat);
  80130. quat.toEulerAnglesToRef(result);
  80131. };
  80132. /**
  80133. * Get the quaternion rotation of the bone in either local or world space
  80134. * @param space The space that the rotation should be in
  80135. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80136. * @returns The quaternion rotation
  80137. */
  80138. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80139. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80140. if (mesh === void 0) { mesh = null; }
  80141. var result = BABYLON.Quaternion.Identity();
  80142. this.getRotationQuaternionToRef(space, mesh, result);
  80143. return result;
  80144. };
  80145. /**
  80146. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80147. * @param space The space that the rotation should be in
  80148. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80149. * @param result The quaternion that the rotation should be copied to
  80150. */
  80151. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80152. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80153. if (mesh === void 0) { mesh = null; }
  80154. if (space == BABYLON.Space.LOCAL) {
  80155. this._decompose();
  80156. result.copyFrom(this._localRotation);
  80157. }
  80158. else {
  80159. var mat = Bone._tmpMats[0];
  80160. var amat = this.getAbsoluteTransform();
  80161. if (mesh) {
  80162. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80163. }
  80164. else {
  80165. mat.copyFrom(amat);
  80166. }
  80167. mat.m[0] *= this._scalingDeterminant;
  80168. mat.m[1] *= this._scalingDeterminant;
  80169. mat.m[2] *= this._scalingDeterminant;
  80170. mat.decompose(undefined, result, undefined);
  80171. }
  80172. };
  80173. /**
  80174. * Get the rotation matrix of the bone in local or world space
  80175. * @param space The space that the rotation should be in
  80176. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80177. * @returns The rotation matrix
  80178. */
  80179. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80180. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80181. var result = BABYLON.Matrix.Identity();
  80182. this.getRotationMatrixToRef(space, mesh, result);
  80183. return result;
  80184. };
  80185. /**
  80186. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80187. * @param space The space that the rotation should be in
  80188. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80189. * @param result The quaternion that the rotation should be copied to
  80190. */
  80191. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80192. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80193. if (space == BABYLON.Space.LOCAL) {
  80194. this.getLocalMatrix().getRotationMatrixToRef(result);
  80195. }
  80196. else {
  80197. var mat = Bone._tmpMats[0];
  80198. var amat = this.getAbsoluteTransform();
  80199. if (mesh) {
  80200. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80201. }
  80202. else {
  80203. mat.copyFrom(amat);
  80204. }
  80205. mat.m[0] *= this._scalingDeterminant;
  80206. mat.m[1] *= this._scalingDeterminant;
  80207. mat.m[2] *= this._scalingDeterminant;
  80208. mat.getRotationMatrixToRef(result);
  80209. }
  80210. };
  80211. /**
  80212. * Get the world position of a point that is in the local space of the bone
  80213. * @param position The local position
  80214. * @param mesh The mesh that this bone is attached to
  80215. * @returns The world position
  80216. */
  80217. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80218. if (mesh === void 0) { mesh = null; }
  80219. var result = BABYLON.Vector3.Zero();
  80220. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80221. return result;
  80222. };
  80223. /**
  80224. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80225. * @param position The local position
  80226. * @param mesh The mesh that this bone is attached to
  80227. * @param result The vector3 that the world position should be copied to
  80228. */
  80229. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80230. if (mesh === void 0) { mesh = null; }
  80231. var wm = null;
  80232. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80233. if (mesh) {
  80234. wm = mesh.getWorldMatrix();
  80235. }
  80236. this._skeleton.computeAbsoluteTransforms();
  80237. var tmat = Bone._tmpMats[0];
  80238. if (mesh && wm) {
  80239. tmat.copyFrom(this.getAbsoluteTransform());
  80240. tmat.multiplyToRef(wm, tmat);
  80241. }
  80242. else {
  80243. tmat = this.getAbsoluteTransform();
  80244. }
  80245. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80246. };
  80247. /**
  80248. * Get the local position of a point that is in world space
  80249. * @param position The world position
  80250. * @param mesh The mesh that this bone is attached to
  80251. * @returns The local position
  80252. */
  80253. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80254. if (mesh === void 0) { mesh = null; }
  80255. var result = BABYLON.Vector3.Zero();
  80256. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80257. return result;
  80258. };
  80259. /**
  80260. * Get the local position of a point that is in world space and copy it to the result param
  80261. * @param position The world position
  80262. * @param mesh The mesh that this bone is attached to
  80263. * @param result The vector3 that the local position should be copied to
  80264. */
  80265. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80266. if (mesh === void 0) { mesh = null; }
  80267. var wm = null;
  80268. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80269. if (mesh) {
  80270. wm = mesh.getWorldMatrix();
  80271. }
  80272. this._skeleton.computeAbsoluteTransforms();
  80273. var tmat = Bone._tmpMats[0];
  80274. tmat.copyFrom(this.getAbsoluteTransform());
  80275. if (mesh && wm) {
  80276. tmat.multiplyToRef(wm, tmat);
  80277. }
  80278. tmat.invert();
  80279. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80280. };
  80281. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80282. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80283. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80284. return Bone;
  80285. }(BABYLON.Node));
  80286. BABYLON.Bone = Bone;
  80287. })(BABYLON || (BABYLON = {}));
  80288. //# sourceMappingURL=babylon.bone.js.map
  80289. var BABYLON;
  80290. (function (BABYLON) {
  80291. /**
  80292. * Class used to apply inverse kinematics to bones
  80293. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80294. */
  80295. var BoneIKController = /** @class */ (function () {
  80296. /**
  80297. * Creates a new BoneIKController
  80298. * @param mesh defines the mesh to control
  80299. * @param bone defines the bone to control
  80300. * @param options defines options to set up the controller
  80301. */
  80302. function BoneIKController(mesh, bone, options) {
  80303. /**
  80304. * Gets or sets the target position
  80305. */
  80306. this.targetPosition = BABYLON.Vector3.Zero();
  80307. /**
  80308. * Gets or sets the pole target position
  80309. */
  80310. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80311. /**
  80312. * Gets or sets the pole target local offset
  80313. */
  80314. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80315. /**
  80316. * Gets or sets the pole angle
  80317. */
  80318. this.poleAngle = 0;
  80319. /**
  80320. * 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)
  80321. */
  80322. this.slerpAmount = 1;
  80323. this._bone1Quat = BABYLON.Quaternion.Identity();
  80324. this._bone1Mat = BABYLON.Matrix.Identity();
  80325. this._bone2Ang = Math.PI;
  80326. this._maxAngle = Math.PI;
  80327. this._rightHandedSystem = false;
  80328. this._bendAxis = BABYLON.Vector3.Right();
  80329. this._slerping = false;
  80330. this._adjustRoll = 0;
  80331. this._bone2 = bone;
  80332. this._bone1 = bone.getParent();
  80333. if (!this._bone1) {
  80334. return;
  80335. }
  80336. this.mesh = mesh;
  80337. var bonePos = bone.getPosition();
  80338. if (bone.getAbsoluteTransform().determinant() > 0) {
  80339. this._rightHandedSystem = true;
  80340. this._bendAxis.x = 0;
  80341. this._bendAxis.y = 0;
  80342. this._bendAxis.z = -1;
  80343. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80344. this._adjustRoll = Math.PI * .5;
  80345. this._bendAxis.z = 1;
  80346. }
  80347. }
  80348. if (this._bone1.length) {
  80349. var boneScale1 = this._bone1.getScale();
  80350. var boneScale2 = this._bone2.getScale();
  80351. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80352. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80353. }
  80354. else if (this._bone1.children[0]) {
  80355. mesh.computeWorldMatrix(true);
  80356. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80357. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80358. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80359. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80360. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80361. }
  80362. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80363. this.maxAngle = Math.PI;
  80364. if (options) {
  80365. if (options.targetMesh) {
  80366. this.targetMesh = options.targetMesh;
  80367. this.targetMesh.computeWorldMatrix(true);
  80368. }
  80369. if (options.poleTargetMesh) {
  80370. this.poleTargetMesh = options.poleTargetMesh;
  80371. this.poleTargetMesh.computeWorldMatrix(true);
  80372. }
  80373. else if (options.poleTargetBone) {
  80374. this.poleTargetBone = options.poleTargetBone;
  80375. }
  80376. else if (this._bone1.getParent()) {
  80377. this.poleTargetBone = this._bone1.getParent();
  80378. }
  80379. if (options.poleTargetLocalOffset) {
  80380. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80381. }
  80382. if (options.poleAngle) {
  80383. this.poleAngle = options.poleAngle;
  80384. }
  80385. if (options.bendAxis) {
  80386. this._bendAxis.copyFrom(options.bendAxis);
  80387. }
  80388. if (options.maxAngle) {
  80389. this.maxAngle = options.maxAngle;
  80390. }
  80391. if (options.slerpAmount) {
  80392. this.slerpAmount = options.slerpAmount;
  80393. }
  80394. }
  80395. }
  80396. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80397. /**
  80398. * Gets or sets maximum allowed angle
  80399. */
  80400. get: function () {
  80401. return this._maxAngle;
  80402. },
  80403. set: function (value) {
  80404. this._setMaxAngle(value);
  80405. },
  80406. enumerable: true,
  80407. configurable: true
  80408. });
  80409. BoneIKController.prototype._setMaxAngle = function (ang) {
  80410. if (ang < 0) {
  80411. ang = 0;
  80412. }
  80413. if (ang > Math.PI || ang == undefined) {
  80414. ang = Math.PI;
  80415. }
  80416. this._maxAngle = ang;
  80417. var a = this._bone1Length;
  80418. var b = this._bone2Length;
  80419. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80420. };
  80421. /**
  80422. * Force the controller to update the bones
  80423. */
  80424. BoneIKController.prototype.update = function () {
  80425. var bone1 = this._bone1;
  80426. if (!bone1) {
  80427. return;
  80428. }
  80429. var target = this.targetPosition;
  80430. var poleTarget = this.poleTargetPosition;
  80431. var mat1 = BoneIKController._tmpMats[0];
  80432. var mat2 = BoneIKController._tmpMats[1];
  80433. if (this.targetMesh) {
  80434. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80435. }
  80436. if (this.poleTargetBone) {
  80437. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80438. }
  80439. else if (this.poleTargetMesh) {
  80440. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80441. }
  80442. var bonePos = BoneIKController._tmpVecs[0];
  80443. var zaxis = BoneIKController._tmpVecs[1];
  80444. var xaxis = BoneIKController._tmpVecs[2];
  80445. var yaxis = BoneIKController._tmpVecs[3];
  80446. var upAxis = BoneIKController._tmpVecs[4];
  80447. var _tmpQuat = BoneIKController._tmpQuat;
  80448. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80449. poleTarget.subtractToRef(bonePos, upAxis);
  80450. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80451. upAxis.y = 1;
  80452. }
  80453. else {
  80454. upAxis.normalize();
  80455. }
  80456. target.subtractToRef(bonePos, yaxis);
  80457. yaxis.normalize();
  80458. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80459. zaxis.normalize();
  80460. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80461. xaxis.normalize();
  80462. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80463. var a = this._bone1Length;
  80464. var b = this._bone2Length;
  80465. var c = BABYLON.Vector3.Distance(bonePos, target);
  80466. if (this._maxReach > 0) {
  80467. c = Math.min(this._maxReach, c);
  80468. }
  80469. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80470. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80471. if (acosa > 1) {
  80472. acosa = 1;
  80473. }
  80474. if (acosb > 1) {
  80475. acosb = 1;
  80476. }
  80477. if (acosa < -1) {
  80478. acosa = -1;
  80479. }
  80480. if (acosb < -1) {
  80481. acosb = -1;
  80482. }
  80483. var angA = Math.acos(acosa);
  80484. var angB = Math.acos(acosb);
  80485. var angC = -angA - angB;
  80486. if (this._rightHandedSystem) {
  80487. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80488. mat2.multiplyToRef(mat1, mat1);
  80489. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80490. mat2.multiplyToRef(mat1, mat1);
  80491. }
  80492. else {
  80493. var _tmpVec = BoneIKController._tmpVecs[5];
  80494. _tmpVec.copyFrom(this._bendAxis);
  80495. _tmpVec.x *= -1;
  80496. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80497. mat2.multiplyToRef(mat1, mat1);
  80498. }
  80499. if (this.poleAngle) {
  80500. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80501. mat1.multiplyToRef(mat2, mat1);
  80502. }
  80503. if (this._bone1) {
  80504. if (this.slerpAmount < 1) {
  80505. if (!this._slerping) {
  80506. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80507. }
  80508. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80509. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80510. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80511. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80512. this._slerping = true;
  80513. }
  80514. else {
  80515. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80516. this._bone1Mat.copyFrom(mat1);
  80517. this._slerping = false;
  80518. }
  80519. }
  80520. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80521. this._bone2Ang = angC;
  80522. };
  80523. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80524. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80525. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80526. return BoneIKController;
  80527. }());
  80528. BABYLON.BoneIKController = BoneIKController;
  80529. })(BABYLON || (BABYLON = {}));
  80530. //# sourceMappingURL=babylon.boneIKController.js.map
  80531. var BABYLON;
  80532. (function (BABYLON) {
  80533. /**
  80534. * Class used to make a bone look toward a point in space
  80535. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80536. */
  80537. var BoneLookController = /** @class */ (function () {
  80538. /**
  80539. * Create a BoneLookController
  80540. * @param mesh the mesh that the bone belongs to
  80541. * @param bone the bone that will be looking to the target
  80542. * @param target the target Vector3 to look at
  80543. * @param settings optional settings:
  80544. * * maxYaw: the maximum angle the bone will yaw to
  80545. * * minYaw: the minimum angle the bone will yaw to
  80546. * * maxPitch: the maximum angle the bone will pitch to
  80547. * * minPitch: the minimum angle the bone will yaw to
  80548. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80549. * * upAxis: the up axis of the coordinate system
  80550. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80551. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80552. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80553. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80554. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80555. * * adjustRoll: used to make an adjustment to the roll of the bone
  80556. **/
  80557. function BoneLookController(mesh, bone, target, options) {
  80558. /**
  80559. * The up axis of the coordinate system that is used when the bone is rotated
  80560. */
  80561. this.upAxis = BABYLON.Vector3.Up();
  80562. /**
  80563. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80564. */
  80565. this.upAxisSpace = BABYLON.Space.LOCAL;
  80566. /**
  80567. * Used to make an adjustment to the yaw of the bone
  80568. */
  80569. this.adjustYaw = 0;
  80570. /**
  80571. * Used to make an adjustment to the pitch of the bone
  80572. */
  80573. this.adjustPitch = 0;
  80574. /**
  80575. * Used to make an adjustment to the roll of the bone
  80576. */
  80577. this.adjustRoll = 0;
  80578. /**
  80579. * 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)
  80580. */
  80581. this.slerpAmount = 1;
  80582. this._boneQuat = BABYLON.Quaternion.Identity();
  80583. this._slerping = false;
  80584. this._firstFrameSkipped = false;
  80585. this._fowardAxis = BABYLON.Vector3.Forward();
  80586. this.mesh = mesh;
  80587. this.bone = bone;
  80588. this.target = target;
  80589. if (options) {
  80590. if (options.adjustYaw) {
  80591. this.adjustYaw = options.adjustYaw;
  80592. }
  80593. if (options.adjustPitch) {
  80594. this.adjustPitch = options.adjustPitch;
  80595. }
  80596. if (options.adjustRoll) {
  80597. this.adjustRoll = options.adjustRoll;
  80598. }
  80599. if (options.maxYaw != null) {
  80600. this.maxYaw = options.maxYaw;
  80601. }
  80602. else {
  80603. this.maxYaw = Math.PI;
  80604. }
  80605. if (options.minYaw != null) {
  80606. this.minYaw = options.minYaw;
  80607. }
  80608. else {
  80609. this.minYaw = -Math.PI;
  80610. }
  80611. if (options.maxPitch != null) {
  80612. this.maxPitch = options.maxPitch;
  80613. }
  80614. else {
  80615. this.maxPitch = Math.PI;
  80616. }
  80617. if (options.minPitch != null) {
  80618. this.minPitch = options.minPitch;
  80619. }
  80620. else {
  80621. this.minPitch = -Math.PI;
  80622. }
  80623. if (options.slerpAmount != null) {
  80624. this.slerpAmount = options.slerpAmount;
  80625. }
  80626. if (options.upAxis != null) {
  80627. this.upAxis = options.upAxis;
  80628. }
  80629. if (options.upAxisSpace != null) {
  80630. this.upAxisSpace = options.upAxisSpace;
  80631. }
  80632. if (options.yawAxis != null || options.pitchAxis != null) {
  80633. var newYawAxis = BABYLON.Axis.Y;
  80634. var newPitchAxis = BABYLON.Axis.X;
  80635. if (options.yawAxis != null) {
  80636. newYawAxis = options.yawAxis.clone();
  80637. newYawAxis.normalize();
  80638. }
  80639. if (options.pitchAxis != null) {
  80640. newPitchAxis = options.pitchAxis.clone();
  80641. newPitchAxis.normalize();
  80642. }
  80643. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80644. this._transformYawPitch = BABYLON.Matrix.Identity();
  80645. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80646. this._transformYawPitchInv = this._transformYawPitch.clone();
  80647. this._transformYawPitch.invert();
  80648. }
  80649. }
  80650. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80651. this.upAxisSpace = BABYLON.Space.LOCAL;
  80652. }
  80653. }
  80654. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80655. /**
  80656. * Gets or sets the minimum yaw angle that the bone can look to
  80657. */
  80658. get: function () {
  80659. return this._minYaw;
  80660. },
  80661. set: function (value) {
  80662. this._minYaw = value;
  80663. this._minYawSin = Math.sin(value);
  80664. this._minYawCos = Math.cos(value);
  80665. if (this._maxYaw != null) {
  80666. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80667. this._yawRange = this._maxYaw - this._minYaw;
  80668. }
  80669. },
  80670. enumerable: true,
  80671. configurable: true
  80672. });
  80673. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80674. /**
  80675. * Gets or sets the maximum yaw angle that the bone can look to
  80676. */
  80677. get: function () {
  80678. return this._maxYaw;
  80679. },
  80680. set: function (value) {
  80681. this._maxYaw = value;
  80682. this._maxYawSin = Math.sin(value);
  80683. this._maxYawCos = Math.cos(value);
  80684. if (this._minYaw != null) {
  80685. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80686. this._yawRange = this._maxYaw - this._minYaw;
  80687. }
  80688. },
  80689. enumerable: true,
  80690. configurable: true
  80691. });
  80692. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80693. /**
  80694. * Gets or sets the minimum pitch angle that the bone can look to
  80695. */
  80696. get: function () {
  80697. return this._minPitch;
  80698. },
  80699. set: function (value) {
  80700. this._minPitch = value;
  80701. this._minPitchTan = Math.tan(value);
  80702. },
  80703. enumerable: true,
  80704. configurable: true
  80705. });
  80706. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80707. /**
  80708. * Gets or sets the maximum pitch angle that the bone can look to
  80709. */
  80710. get: function () {
  80711. return this._maxPitch;
  80712. },
  80713. set: function (value) {
  80714. this._maxPitch = value;
  80715. this._maxPitchTan = Math.tan(value);
  80716. },
  80717. enumerable: true,
  80718. configurable: true
  80719. });
  80720. /**
  80721. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80722. */
  80723. BoneLookController.prototype.update = function () {
  80724. //skip the first frame when slerping so that the mesh rotation is correct
  80725. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80726. this._firstFrameSkipped = true;
  80727. return;
  80728. }
  80729. var bone = this.bone;
  80730. var bonePos = BoneLookController._tmpVecs[0];
  80731. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80732. var target = this.target;
  80733. var _tmpMat1 = BoneLookController._tmpMats[0];
  80734. var _tmpMat2 = BoneLookController._tmpMats[1];
  80735. var mesh = this.mesh;
  80736. var parentBone = bone.getParent();
  80737. var upAxis = BoneLookController._tmpVecs[1];
  80738. upAxis.copyFrom(this.upAxis);
  80739. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80740. if (this._transformYawPitch) {
  80741. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80742. }
  80743. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80744. }
  80745. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80746. mesh.getDirectionToRef(upAxis, upAxis);
  80747. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80748. upAxis.normalize();
  80749. }
  80750. }
  80751. var checkYaw = false;
  80752. var checkPitch = false;
  80753. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80754. checkYaw = true;
  80755. }
  80756. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80757. checkPitch = true;
  80758. }
  80759. if (checkYaw || checkPitch) {
  80760. var spaceMat = BoneLookController._tmpMats[2];
  80761. var spaceMatInv = BoneLookController._tmpMats[3];
  80762. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80763. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80764. }
  80765. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80766. spaceMat.copyFrom(mesh.getWorldMatrix());
  80767. }
  80768. else {
  80769. var forwardAxis = BoneLookController._tmpVecs[2];
  80770. forwardAxis.copyFrom(this._fowardAxis);
  80771. if (this._transformYawPitch) {
  80772. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80773. }
  80774. if (parentBone) {
  80775. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80776. }
  80777. else {
  80778. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80779. }
  80780. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80781. rightAxis.normalize();
  80782. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80783. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80784. }
  80785. spaceMat.invertToRef(spaceMatInv);
  80786. var xzlen = null;
  80787. if (checkPitch) {
  80788. var localTarget = BoneLookController._tmpVecs[3];
  80789. target.subtractToRef(bonePos, localTarget);
  80790. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80791. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80792. var pitch = Math.atan2(localTarget.y, xzlen);
  80793. var newPitch = pitch;
  80794. if (pitch > this._maxPitch) {
  80795. localTarget.y = this._maxPitchTan * xzlen;
  80796. newPitch = this._maxPitch;
  80797. }
  80798. else if (pitch < this._minPitch) {
  80799. localTarget.y = this._minPitchTan * xzlen;
  80800. newPitch = this._minPitch;
  80801. }
  80802. if (pitch != newPitch) {
  80803. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80804. localTarget.addInPlace(bonePos);
  80805. target = localTarget;
  80806. }
  80807. }
  80808. if (checkYaw) {
  80809. var localTarget = BoneLookController._tmpVecs[4];
  80810. target.subtractToRef(bonePos, localTarget);
  80811. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80812. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80813. var newYaw = yaw;
  80814. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80815. if (xzlen == null) {
  80816. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80817. }
  80818. if (this._yawRange > Math.PI) {
  80819. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80820. localTarget.z = this._maxYawCos * xzlen;
  80821. localTarget.x = this._maxYawSin * xzlen;
  80822. newYaw = this._maxYaw;
  80823. }
  80824. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80825. localTarget.z = this._minYawCos * xzlen;
  80826. localTarget.x = this._minYawSin * xzlen;
  80827. newYaw = this._minYaw;
  80828. }
  80829. }
  80830. else {
  80831. if (yaw > this._maxYaw) {
  80832. localTarget.z = this._maxYawCos * xzlen;
  80833. localTarget.x = this._maxYawSin * xzlen;
  80834. newYaw = this._maxYaw;
  80835. }
  80836. else if (yaw < this._minYaw) {
  80837. localTarget.z = this._minYawCos * xzlen;
  80838. localTarget.x = this._minYawSin * xzlen;
  80839. newYaw = this._minYaw;
  80840. }
  80841. }
  80842. }
  80843. if (this._slerping && this._yawRange > Math.PI) {
  80844. //are we going to be crossing into the min/max region?
  80845. var boneFwd = BoneLookController._tmpVecs[8];
  80846. boneFwd.copyFrom(BABYLON.Axis.Z);
  80847. if (this._transformYawPitch) {
  80848. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  80849. }
  80850. var boneRotMat = BoneLookController._tmpMats[4];
  80851. this._boneQuat.toRotationMatrix(boneRotMat);
  80852. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  80853. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  80854. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  80855. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  80856. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  80857. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  80858. if (angBtwTar > angBtwMidYaw) {
  80859. if (xzlen == null) {
  80860. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80861. }
  80862. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  80863. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  80864. if (angBtwMin < angBtwMax) {
  80865. newYaw = boneYaw + Math.PI * .75;
  80866. localTarget.z = Math.cos(newYaw) * xzlen;
  80867. localTarget.x = Math.sin(newYaw) * xzlen;
  80868. }
  80869. else {
  80870. newYaw = boneYaw - Math.PI * .75;
  80871. localTarget.z = Math.cos(newYaw) * xzlen;
  80872. localTarget.x = Math.sin(newYaw) * xzlen;
  80873. }
  80874. }
  80875. }
  80876. if (yaw != newYaw) {
  80877. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80878. localTarget.addInPlace(bonePos);
  80879. target = localTarget;
  80880. }
  80881. }
  80882. }
  80883. var zaxis = BoneLookController._tmpVecs[5];
  80884. var xaxis = BoneLookController._tmpVecs[6];
  80885. var yaxis = BoneLookController._tmpVecs[7];
  80886. var _tmpQuat = BoneLookController._tmpQuat;
  80887. target.subtractToRef(bonePos, zaxis);
  80888. zaxis.normalize();
  80889. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  80890. xaxis.normalize();
  80891. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  80892. yaxis.normalize();
  80893. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  80894. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  80895. return;
  80896. }
  80897. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  80898. return;
  80899. }
  80900. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  80901. return;
  80902. }
  80903. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  80904. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  80905. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  80906. }
  80907. if (this.slerpAmount < 1) {
  80908. if (!this._slerping) {
  80909. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  80910. }
  80911. if (this._transformYawPitch) {
  80912. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80913. }
  80914. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  80915. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  80916. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  80917. this._slerping = true;
  80918. }
  80919. else {
  80920. if (this._transformYawPitch) {
  80921. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  80922. }
  80923. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  80924. this._slerping = false;
  80925. }
  80926. };
  80927. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  80928. var angDiff = ang2 - ang1;
  80929. angDiff %= Math.PI * 2;
  80930. if (angDiff > Math.PI) {
  80931. angDiff -= Math.PI * 2;
  80932. }
  80933. else if (angDiff < -Math.PI) {
  80934. angDiff += Math.PI * 2;
  80935. }
  80936. return angDiff;
  80937. };
  80938. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  80939. ang1 %= (2 * Math.PI);
  80940. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80941. ang2 %= (2 * Math.PI);
  80942. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80943. var ab = 0;
  80944. if (ang1 < ang2) {
  80945. ab = ang2 - ang1;
  80946. }
  80947. else {
  80948. ab = ang1 - ang2;
  80949. }
  80950. if (ab > Math.PI) {
  80951. ab = Math.PI * 2 - ab;
  80952. }
  80953. return ab;
  80954. };
  80955. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  80956. ang %= (2 * Math.PI);
  80957. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  80958. ang1 %= (2 * Math.PI);
  80959. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  80960. ang2 %= (2 * Math.PI);
  80961. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  80962. if (ang1 < ang2) {
  80963. if (ang > ang1 && ang < ang2) {
  80964. return true;
  80965. }
  80966. }
  80967. else {
  80968. if (ang > ang2 && ang < ang1) {
  80969. return true;
  80970. }
  80971. }
  80972. return false;
  80973. };
  80974. 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()];
  80975. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  80976. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80977. return BoneLookController;
  80978. }());
  80979. BABYLON.BoneLookController = BoneLookController;
  80980. })(BABYLON || (BABYLON = {}));
  80981. //# sourceMappingURL=babylon.boneLookController.js.map
  80982. var BABYLON;
  80983. (function (BABYLON) {
  80984. /**
  80985. * Class used to handle skinning animations
  80986. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  80987. */
  80988. var Skeleton = /** @class */ (function () {
  80989. /**
  80990. * Creates a new skeleton
  80991. * @param name defines the skeleton name
  80992. * @param id defines the skeleton Id
  80993. * @param scene defines the hosting scene
  80994. */
  80995. function Skeleton(
  80996. /** defines the skeleton name */
  80997. name,
  80998. /** defines the skeleton Id */
  80999. id, scene) {
  81000. this.name = name;
  81001. this.id = id;
  81002. /**
  81003. * Gets the list of child bones
  81004. */
  81005. this.bones = new Array();
  81006. /**
  81007. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81008. */
  81009. this.needInitialSkinMatrix = false;
  81010. this._isDirty = true;
  81011. this._meshesWithPoseMatrix = new Array();
  81012. this._identity = BABYLON.Matrix.Identity();
  81013. this._ranges = {};
  81014. this._lastAbsoluteTransformsUpdateId = -1;
  81015. /**
  81016. * Specifies if the skeleton should be serialized
  81017. */
  81018. this.doNotSerialize = false;
  81019. this._animationPropertiesOverride = null;
  81020. // Events
  81021. /**
  81022. * An observable triggered before computing the skeleton's matrices
  81023. */
  81024. this.onBeforeComputeObservable = new BABYLON.Observable();
  81025. this.bones = [];
  81026. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81027. scene.skeletons.push(this);
  81028. //make sure it will recalculate the matrix next time prepare is called.
  81029. this._isDirty = true;
  81030. }
  81031. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81032. /**
  81033. * Gets or sets the animation properties override
  81034. */
  81035. get: function () {
  81036. if (!this._animationPropertiesOverride) {
  81037. return this._scene.animationPropertiesOverride;
  81038. }
  81039. return this._animationPropertiesOverride;
  81040. },
  81041. set: function (value) {
  81042. this._animationPropertiesOverride = value;
  81043. },
  81044. enumerable: true,
  81045. configurable: true
  81046. });
  81047. // Members
  81048. /**
  81049. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81050. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81051. * @returns a Float32Array containing matrices data
  81052. */
  81053. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81054. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81055. return mesh._bonesTransformMatrices;
  81056. }
  81057. if (!this._transformMatrices) {
  81058. this.prepare();
  81059. }
  81060. return this._transformMatrices;
  81061. };
  81062. /**
  81063. * Gets the current hosting scene
  81064. * @returns a scene object
  81065. */
  81066. Skeleton.prototype.getScene = function () {
  81067. return this._scene;
  81068. };
  81069. // Methods
  81070. /**
  81071. * Gets a string representing the current skeleton data
  81072. * @param fullDetails defines a boolean indicating if we want a verbose version
  81073. * @returns a string representing the current skeleton data
  81074. */
  81075. Skeleton.prototype.toString = function (fullDetails) {
  81076. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81077. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81078. if (fullDetails) {
  81079. ret += ", Ranges: {";
  81080. var first = true;
  81081. for (var name_1 in this._ranges) {
  81082. if (first) {
  81083. ret += ", ";
  81084. first = false;
  81085. }
  81086. ret += name_1;
  81087. }
  81088. ret += "}";
  81089. }
  81090. return ret;
  81091. };
  81092. /**
  81093. * Get bone's index searching by name
  81094. * @param name defines bone's name to search for
  81095. * @return the indice of the bone. Returns -1 if not found
  81096. */
  81097. Skeleton.prototype.getBoneIndexByName = function (name) {
  81098. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81099. if (this.bones[boneIndex].name === name) {
  81100. return boneIndex;
  81101. }
  81102. }
  81103. return -1;
  81104. };
  81105. /**
  81106. * Creater a new animation range
  81107. * @param name defines the name of the range
  81108. * @param from defines the start key
  81109. * @param to defines the end key
  81110. */
  81111. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81112. // check name not already in use
  81113. if (!this._ranges[name]) {
  81114. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81115. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81116. if (this.bones[i].animations[0]) {
  81117. this.bones[i].animations[0].createRange(name, from, to);
  81118. }
  81119. }
  81120. }
  81121. };
  81122. /**
  81123. * Delete a specific animation range
  81124. * @param name defines the name of the range
  81125. * @param deleteFrames defines if frames must be removed as well
  81126. */
  81127. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81128. if (deleteFrames === void 0) { deleteFrames = true; }
  81129. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81130. if (this.bones[i].animations[0]) {
  81131. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81132. }
  81133. }
  81134. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81135. };
  81136. /**
  81137. * Gets a specific animation range
  81138. * @param name defines the name of the range to look for
  81139. * @returns the requested animation range or null if not found
  81140. */
  81141. Skeleton.prototype.getAnimationRange = function (name) {
  81142. return this._ranges[name];
  81143. };
  81144. /**
  81145. * Gets the list of all animation ranges defined on this skeleton
  81146. * @returns an array
  81147. */
  81148. Skeleton.prototype.getAnimationRanges = function () {
  81149. var animationRanges = [];
  81150. var name;
  81151. var i = 0;
  81152. for (name in this._ranges) {
  81153. animationRanges[i] = this._ranges[name];
  81154. i++;
  81155. }
  81156. return animationRanges;
  81157. };
  81158. /**
  81159. * Copy animation range from a source skeleton.
  81160. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81161. * @param source defines the source skeleton
  81162. * @param name defines the name of the range to copy
  81163. * @param rescaleAsRequired defines if rescaling must be applied if required
  81164. * @returns true if operation was successful
  81165. */
  81166. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81167. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81168. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81169. return false;
  81170. }
  81171. var ret = true;
  81172. var frameOffset = this._getHighestAnimationFrame() + 1;
  81173. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81174. var boneDict = {};
  81175. var sourceBones = source.bones;
  81176. var nBones;
  81177. var i;
  81178. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81179. boneDict[sourceBones[i].name] = sourceBones[i];
  81180. }
  81181. if (this.bones.length !== sourceBones.length) {
  81182. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81183. ret = false;
  81184. }
  81185. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81186. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81187. var boneName = this.bones[i].name;
  81188. var sourceBone = boneDict[boneName];
  81189. if (sourceBone) {
  81190. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81191. }
  81192. else {
  81193. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81194. ret = false;
  81195. }
  81196. }
  81197. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81198. var range = source.getAnimationRange(name);
  81199. if (range) {
  81200. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81201. }
  81202. return ret;
  81203. };
  81204. /**
  81205. * Forces the skeleton to go to rest pose
  81206. */
  81207. Skeleton.prototype.returnToRest = function () {
  81208. for (var index = 0; index < this.bones.length; index++) {
  81209. this.bones[index].returnToRest();
  81210. }
  81211. };
  81212. Skeleton.prototype._getHighestAnimationFrame = function () {
  81213. var ret = 0;
  81214. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81215. if (this.bones[i].animations[0]) {
  81216. var highest = this.bones[i].animations[0].getHighestFrame();
  81217. if (ret < highest) {
  81218. ret = highest;
  81219. }
  81220. }
  81221. }
  81222. return ret;
  81223. };
  81224. /**
  81225. * Begin a specific animation range
  81226. * @param name defines the name of the range to start
  81227. * @param loop defines if looping must be turned on (false by default)
  81228. * @param speedRatio defines the speed ratio to apply (1 by default)
  81229. * @param onAnimationEnd defines a callback which will be called when animation will end
  81230. * @returns a new animatable
  81231. */
  81232. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81233. var range = this.getAnimationRange(name);
  81234. if (!range) {
  81235. return null;
  81236. }
  81237. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81238. };
  81239. /** @hidden */
  81240. Skeleton.prototype._markAsDirty = function () {
  81241. this._isDirty = true;
  81242. };
  81243. /** @hidden */
  81244. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81245. this._meshesWithPoseMatrix.push(mesh);
  81246. };
  81247. /** @hidden */
  81248. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81249. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81250. if (index > -1) {
  81251. this._meshesWithPoseMatrix.splice(index, 1);
  81252. }
  81253. };
  81254. /** @hidden */
  81255. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81256. this.onBeforeComputeObservable.notifyObservers(this);
  81257. for (var index = 0; index < this.bones.length; index++) {
  81258. var bone = this.bones[index];
  81259. var parentBone = bone.getParent();
  81260. if (parentBone) {
  81261. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81262. }
  81263. else {
  81264. if (initialSkinMatrix) {
  81265. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81266. }
  81267. else {
  81268. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81269. }
  81270. }
  81271. if (bone._index !== -1) {
  81272. var mappedIndex = bone._index === null ? index : bone._index;
  81273. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81274. }
  81275. }
  81276. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81277. };
  81278. /**
  81279. * Build all resources required to render a skeleton
  81280. */
  81281. Skeleton.prototype.prepare = function () {
  81282. if (!this._isDirty) {
  81283. return;
  81284. }
  81285. if (this.needInitialSkinMatrix) {
  81286. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81287. var mesh = this._meshesWithPoseMatrix[index];
  81288. var poseMatrix = mesh.getPoseMatrix();
  81289. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81290. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81291. }
  81292. if (this._synchronizedWithMesh !== mesh) {
  81293. this._synchronizedWithMesh = mesh;
  81294. // Prepare bones
  81295. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81296. var bone = this.bones[boneIndex];
  81297. if (!bone.getParent()) {
  81298. var matrix = bone.getBaseMatrix();
  81299. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81300. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81301. }
  81302. }
  81303. }
  81304. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81305. }
  81306. }
  81307. else {
  81308. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81309. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81310. }
  81311. this._computeTransformMatrices(this._transformMatrices, null);
  81312. }
  81313. this._isDirty = false;
  81314. this._scene._activeBones.addCount(this.bones.length, false);
  81315. };
  81316. /**
  81317. * Gets the list of animatables currently running for this skeleton
  81318. * @returns an array of animatables
  81319. */
  81320. Skeleton.prototype.getAnimatables = function () {
  81321. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81322. this._animatables = [];
  81323. for (var index = 0; index < this.bones.length; index++) {
  81324. this._animatables.push(this.bones[index]);
  81325. }
  81326. }
  81327. return this._animatables;
  81328. };
  81329. /**
  81330. * Clone the current skeleton
  81331. * @param name defines the name of the new skeleton
  81332. * @param id defines the id of the enw skeleton
  81333. * @returns the new skeleton
  81334. */
  81335. Skeleton.prototype.clone = function (name, id) {
  81336. var result = new Skeleton(name, id || name, this._scene);
  81337. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81338. for (var index = 0; index < this.bones.length; index++) {
  81339. var source = this.bones[index];
  81340. var parentBone = null;
  81341. var parent_1 = source.getParent();
  81342. if (parent_1) {
  81343. var parentIndex = this.bones.indexOf(parent_1);
  81344. parentBone = result.bones[parentIndex];
  81345. }
  81346. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81347. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81348. }
  81349. if (this._ranges) {
  81350. result._ranges = {};
  81351. for (var rangeName in this._ranges) {
  81352. var range = this._ranges[rangeName];
  81353. if (range) {
  81354. result._ranges[rangeName] = range.clone();
  81355. }
  81356. }
  81357. }
  81358. this._isDirty = true;
  81359. return result;
  81360. };
  81361. /**
  81362. * Enable animation blending for this skeleton
  81363. * @param blendingSpeed defines the blending speed to apply
  81364. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81365. */
  81366. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81367. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81368. this.bones.forEach(function (bone) {
  81369. bone.animations.forEach(function (animation) {
  81370. animation.enableBlending = true;
  81371. animation.blendingSpeed = blendingSpeed;
  81372. });
  81373. });
  81374. };
  81375. /**
  81376. * Releases all resources associated with the current skeleton
  81377. */
  81378. Skeleton.prototype.dispose = function () {
  81379. this._meshesWithPoseMatrix = [];
  81380. // Animations
  81381. this.getScene().stopAnimation(this);
  81382. // Remove from scene
  81383. this.getScene().removeSkeleton(this);
  81384. };
  81385. /**
  81386. * Serialize the skeleton in a JSON object
  81387. * @returns a JSON object
  81388. */
  81389. Skeleton.prototype.serialize = function () {
  81390. var serializationObject = {};
  81391. serializationObject.name = this.name;
  81392. serializationObject.id = this.id;
  81393. if (this.dimensionsAtRest) {
  81394. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81395. }
  81396. serializationObject.bones = [];
  81397. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81398. for (var index = 0; index < this.bones.length; index++) {
  81399. var bone = this.bones[index];
  81400. var parent_2 = bone.getParent();
  81401. var serializedBone = {
  81402. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81403. name: bone.name,
  81404. matrix: bone.getBaseMatrix().toArray(),
  81405. rest: bone.getRestPose().toArray()
  81406. };
  81407. serializationObject.bones.push(serializedBone);
  81408. if (bone.length) {
  81409. serializedBone.length = bone.length;
  81410. }
  81411. if (bone.metadata) {
  81412. serializedBone.metadata = bone.metadata;
  81413. }
  81414. if (bone.animations && bone.animations.length > 0) {
  81415. serializedBone.animation = bone.animations[0].serialize();
  81416. }
  81417. serializationObject.ranges = [];
  81418. for (var name in this._ranges) {
  81419. var source = this._ranges[name];
  81420. if (!source) {
  81421. continue;
  81422. }
  81423. var range = {};
  81424. range.name = name;
  81425. range.from = source.from;
  81426. range.to = source.to;
  81427. serializationObject.ranges.push(range);
  81428. }
  81429. }
  81430. return serializationObject;
  81431. };
  81432. /**
  81433. * Creates a new skeleton from serialized data
  81434. * @param parsedSkeleton defines the serialized data
  81435. * @param scene defines the hosting scene
  81436. * @returns a new skeleton
  81437. */
  81438. Skeleton.Parse = function (parsedSkeleton, scene) {
  81439. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81440. if (parsedSkeleton.dimensionsAtRest) {
  81441. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81442. }
  81443. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81444. var index;
  81445. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81446. var parsedBone = parsedSkeleton.bones[index];
  81447. var parentBone = null;
  81448. if (parsedBone.parentBoneIndex > -1) {
  81449. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81450. }
  81451. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81452. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81453. if (parsedBone.length) {
  81454. bone.length = parsedBone.length;
  81455. }
  81456. if (parsedBone.metadata) {
  81457. bone.metadata = parsedBone.metadata;
  81458. }
  81459. if (parsedBone.animation) {
  81460. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81461. }
  81462. }
  81463. // placed after bones, so createAnimationRange can cascade down
  81464. if (parsedSkeleton.ranges) {
  81465. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81466. var data = parsedSkeleton.ranges[index];
  81467. skeleton.createAnimationRange(data.name, data.from, data.to);
  81468. }
  81469. }
  81470. return skeleton;
  81471. };
  81472. /**
  81473. * Compute all node absolute transforms
  81474. * @param forceUpdate defines if computation must be done even if cache is up to date
  81475. */
  81476. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81477. if (forceUpdate === void 0) { forceUpdate = false; }
  81478. var renderId = this._scene.getRenderId();
  81479. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81480. this.bones[0].computeAbsoluteTransforms();
  81481. this._lastAbsoluteTransformsUpdateId = renderId;
  81482. }
  81483. };
  81484. /**
  81485. * Gets the root pose matrix
  81486. * @returns a matrix
  81487. */
  81488. Skeleton.prototype.getPoseMatrix = function () {
  81489. var poseMatrix = null;
  81490. if (this._meshesWithPoseMatrix.length > 0) {
  81491. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81492. }
  81493. return poseMatrix;
  81494. };
  81495. /**
  81496. * Sorts bones per internal index
  81497. */
  81498. Skeleton.prototype.sortBones = function () {
  81499. var bones = new Array();
  81500. var visited = new Array(this.bones.length);
  81501. for (var index = 0; index < this.bones.length; index++) {
  81502. this._sortBones(index, bones, visited);
  81503. }
  81504. this.bones = bones;
  81505. };
  81506. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81507. if (visited[index]) {
  81508. return;
  81509. }
  81510. visited[index] = true;
  81511. var bone = this.bones[index];
  81512. if (bone._index === undefined) {
  81513. bone._index = index;
  81514. }
  81515. var parentBone = bone.getParent();
  81516. if (parentBone) {
  81517. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81518. }
  81519. bones.push(bone);
  81520. };
  81521. return Skeleton;
  81522. }());
  81523. BABYLON.Skeleton = Skeleton;
  81524. })(BABYLON || (BABYLON = {}));
  81525. //# sourceMappingURL=babylon.skeleton.js.map
  81526. var BABYLON;
  81527. (function (BABYLON) {
  81528. var SphericalPolynomial = /** @class */ (function () {
  81529. function SphericalPolynomial() {
  81530. this.x = BABYLON.Vector3.Zero();
  81531. this.y = BABYLON.Vector3.Zero();
  81532. this.z = BABYLON.Vector3.Zero();
  81533. this.xx = BABYLON.Vector3.Zero();
  81534. this.yy = BABYLON.Vector3.Zero();
  81535. this.zz = BABYLON.Vector3.Zero();
  81536. this.xy = BABYLON.Vector3.Zero();
  81537. this.yz = BABYLON.Vector3.Zero();
  81538. this.zx = BABYLON.Vector3.Zero();
  81539. }
  81540. SphericalPolynomial.prototype.addAmbient = function (color) {
  81541. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81542. this.xx = this.xx.add(colorVector);
  81543. this.yy = this.yy.add(colorVector);
  81544. this.zz = this.zz.add(colorVector);
  81545. };
  81546. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81547. var result = new SphericalPolynomial();
  81548. result.x = harmonics.L11.scale(1.02333);
  81549. result.y = harmonics.L1_1.scale(1.02333);
  81550. result.z = harmonics.L10.scale(1.02333);
  81551. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81552. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81553. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81554. result.yz = harmonics.L2_1.scale(0.858086);
  81555. result.zx = harmonics.L21.scale(0.858086);
  81556. result.xy = harmonics.L2_2.scale(0.858086);
  81557. result.scale(1.0 / Math.PI);
  81558. return result;
  81559. };
  81560. SphericalPolynomial.prototype.scale = function (scale) {
  81561. this.x = this.x.scale(scale);
  81562. this.y = this.y.scale(scale);
  81563. this.z = this.z.scale(scale);
  81564. this.xx = this.xx.scale(scale);
  81565. this.yy = this.yy.scale(scale);
  81566. this.zz = this.zz.scale(scale);
  81567. this.yz = this.yz.scale(scale);
  81568. this.zx = this.zx.scale(scale);
  81569. this.xy = this.xy.scale(scale);
  81570. };
  81571. return SphericalPolynomial;
  81572. }());
  81573. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81574. var SphericalHarmonics = /** @class */ (function () {
  81575. function SphericalHarmonics() {
  81576. this.L00 = BABYLON.Vector3.Zero();
  81577. this.L1_1 = BABYLON.Vector3.Zero();
  81578. this.L10 = BABYLON.Vector3.Zero();
  81579. this.L11 = BABYLON.Vector3.Zero();
  81580. this.L2_2 = BABYLON.Vector3.Zero();
  81581. this.L2_1 = BABYLON.Vector3.Zero();
  81582. this.L20 = BABYLON.Vector3.Zero();
  81583. this.L21 = BABYLON.Vector3.Zero();
  81584. this.L22 = BABYLON.Vector3.Zero();
  81585. }
  81586. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81587. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81588. var c = colorVector.scale(deltaSolidAngle);
  81589. this.L00 = this.L00.add(c.scale(0.282095));
  81590. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81591. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81592. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81593. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81594. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81595. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81596. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81597. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81598. };
  81599. SphericalHarmonics.prototype.scale = function (scale) {
  81600. this.L00 = this.L00.scale(scale);
  81601. this.L1_1 = this.L1_1.scale(scale);
  81602. this.L10 = this.L10.scale(scale);
  81603. this.L11 = this.L11.scale(scale);
  81604. this.L2_2 = this.L2_2.scale(scale);
  81605. this.L2_1 = this.L2_1.scale(scale);
  81606. this.L20 = this.L20.scale(scale);
  81607. this.L21 = this.L21.scale(scale);
  81608. this.L22 = this.L22.scale(scale);
  81609. };
  81610. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81611. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81612. //
  81613. // E_lm = A_l * L_lm
  81614. //
  81615. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81616. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81617. // the scaling factors are given in equation 9.
  81618. // Constant (Band 0)
  81619. this.L00 = this.L00.scale(3.141593);
  81620. // Linear (Band 1)
  81621. this.L1_1 = this.L1_1.scale(2.094395);
  81622. this.L10 = this.L10.scale(2.094395);
  81623. this.L11 = this.L11.scale(2.094395);
  81624. // Quadratic (Band 2)
  81625. this.L2_2 = this.L2_2.scale(0.785398);
  81626. this.L2_1 = this.L2_1.scale(0.785398);
  81627. this.L20 = this.L20.scale(0.785398);
  81628. this.L21 = this.L21.scale(0.785398);
  81629. this.L22 = this.L22.scale(0.785398);
  81630. };
  81631. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81632. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81633. // L = (1/pi) * E * rho
  81634. //
  81635. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81636. this.scale(1.0 / Math.PI);
  81637. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81638. // (The pixel shader must apply albedo after texture fetches, etc).
  81639. };
  81640. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81641. var result = new SphericalHarmonics();
  81642. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81643. result.L1_1 = polynomial.y.scale(0.977204);
  81644. result.L10 = polynomial.z.scale(0.977204);
  81645. result.L11 = polynomial.x.scale(0.977204);
  81646. result.L2_2 = polynomial.xy.scale(1.16538);
  81647. result.L2_1 = polynomial.yz.scale(1.16538);
  81648. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81649. result.L21 = polynomial.zx.scale(1.16538);
  81650. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81651. result.scale(Math.PI);
  81652. return result;
  81653. };
  81654. return SphericalHarmonics;
  81655. }());
  81656. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81657. })(BABYLON || (BABYLON = {}));
  81658. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81659. var BABYLON;
  81660. (function (BABYLON) {
  81661. var FileFaceOrientation = /** @class */ (function () {
  81662. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81663. this.name = name;
  81664. this.worldAxisForNormal = worldAxisForNormal;
  81665. this.worldAxisForFileX = worldAxisForFileX;
  81666. this.worldAxisForFileY = worldAxisForFileY;
  81667. }
  81668. return FileFaceOrientation;
  81669. }());
  81670. ;
  81671. /**
  81672. * Helper class dealing with the extraction of spherical polynomial dataArray
  81673. * from a cube map.
  81674. */
  81675. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81676. function CubeMapToSphericalPolynomialTools() {
  81677. }
  81678. /**
  81679. * Converts a texture to the according Spherical Polynomial data.
  81680. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81681. *
  81682. * @param texture The texture to extract the information from.
  81683. * @return The Spherical Polynomial data.
  81684. */
  81685. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81686. if (!texture.isCube) {
  81687. // Only supports cube Textures currently.
  81688. return null;
  81689. }
  81690. var size = texture.getSize().width;
  81691. var right = texture.readPixels(0);
  81692. var left = texture.readPixels(1);
  81693. var up;
  81694. var down;
  81695. if (texture.isRenderTarget) {
  81696. up = texture.readPixels(3);
  81697. down = texture.readPixels(2);
  81698. }
  81699. else {
  81700. up = texture.readPixels(2);
  81701. down = texture.readPixels(3);
  81702. }
  81703. var front = texture.readPixels(4);
  81704. var back = texture.readPixels(5);
  81705. var gammaSpace = texture.gammaSpace;
  81706. // Always read as RGBA.
  81707. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81708. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81709. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81710. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81711. }
  81712. var cubeInfo = {
  81713. size: size,
  81714. right: right,
  81715. left: left,
  81716. up: up,
  81717. down: down,
  81718. front: front,
  81719. back: back,
  81720. format: format,
  81721. type: type,
  81722. gammaSpace: gammaSpace,
  81723. };
  81724. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81725. };
  81726. /**
  81727. * Converts a cubemap to the according Spherical Polynomial data.
  81728. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81729. *
  81730. * @param cubeInfo The Cube map to extract the information from.
  81731. * @return The Spherical Polynomial data.
  81732. */
  81733. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81734. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81735. var totalSolidAngle = 0.0;
  81736. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81737. var du = 2.0 / cubeInfo.size;
  81738. var dv = du;
  81739. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81740. var minUV = du * 0.5 - 1.0;
  81741. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81742. var fileFace = this.FileFaces[faceIndex];
  81743. var dataArray = cubeInfo[fileFace.name];
  81744. var v = minUV;
  81745. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81746. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81747. // Because SP is still linear, so summation is fine in that basis.
  81748. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81749. for (var y = 0; y < cubeInfo.size; y++) {
  81750. var u = minUV;
  81751. for (var x = 0; x < cubeInfo.size; x++) {
  81752. // World direction (not normalised)
  81753. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81754. worldDirection.normalize();
  81755. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81756. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81757. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81758. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81759. // Handle Integer types.
  81760. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81761. r /= 255;
  81762. g /= 255;
  81763. b /= 255;
  81764. }
  81765. // Handle Gamma space textures.
  81766. if (cubeInfo.gammaSpace) {
  81767. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81768. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81769. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81770. }
  81771. var color = new BABYLON.Color3(r, g, b);
  81772. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81773. totalSolidAngle += deltaSolidAngle;
  81774. u += du;
  81775. }
  81776. v += dv;
  81777. }
  81778. }
  81779. // Solid angle for entire sphere is 4*pi
  81780. var sphereSolidAngle = 4.0 * Math.PI;
  81781. // Adjust the solid angle to allow for how many faces we processed.
  81782. var facesProcessed = 6.0;
  81783. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81784. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81785. // This is needed because the numerical integration over the cube uses a
  81786. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81787. // and also to compensate for accumulative error due to float precision in the summation.
  81788. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81789. sphericalHarmonics.scale(correctionFactor);
  81790. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81791. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81792. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81793. };
  81794. CubeMapToSphericalPolynomialTools.FileFaces = [
  81795. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81796. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81797. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81798. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81799. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81800. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81801. ];
  81802. return CubeMapToSphericalPolynomialTools;
  81803. }());
  81804. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81805. })(BABYLON || (BABYLON = {}));
  81806. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81807. var BABYLON;
  81808. (function (BABYLON) {
  81809. /**
  81810. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81811. */
  81812. var PanoramaToCubeMapTools = /** @class */ (function () {
  81813. function PanoramaToCubeMapTools() {
  81814. }
  81815. /**
  81816. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81817. *
  81818. * @param float32Array The source data.
  81819. * @param inputWidth The width of the input panorama.
  81820. * @param inputhHeight The height of the input panorama.
  81821. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81822. * @return The cubemap data
  81823. */
  81824. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81825. if (!float32Array) {
  81826. throw "ConvertPanoramaToCubemap: input cannot be null";
  81827. }
  81828. if (float32Array.length != inputWidth * inputHeight * 3) {
  81829. throw "ConvertPanoramaToCubemap: input size is wrong";
  81830. }
  81831. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  81832. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  81833. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  81834. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  81835. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  81836. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  81837. return {
  81838. front: textureFront,
  81839. back: textureBack,
  81840. left: textureLeft,
  81841. right: textureRight,
  81842. up: textureUp,
  81843. down: textureDown,
  81844. size: size,
  81845. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  81846. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  81847. gammaSpace: false,
  81848. };
  81849. };
  81850. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  81851. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  81852. var textureArray = new Float32Array(buffer);
  81853. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  81854. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  81855. var dy = 1 / texSize;
  81856. var fy = 0;
  81857. for (var y = 0; y < texSize; y++) {
  81858. var xv1 = faceData[0];
  81859. var xv2 = faceData[2];
  81860. for (var x = 0; x < texSize; x++) {
  81861. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  81862. v.normalize();
  81863. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  81864. // 3 channels per pixels
  81865. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  81866. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  81867. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  81868. xv1 = xv1.add(rotDX1);
  81869. xv2 = xv2.add(rotDX2);
  81870. }
  81871. fy += dy;
  81872. }
  81873. return textureArray;
  81874. };
  81875. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  81876. var theta = Math.atan2(vDir.z, vDir.x);
  81877. var phi = Math.acos(vDir.y);
  81878. while (theta < -Math.PI)
  81879. theta += 2 * Math.PI;
  81880. while (theta > Math.PI)
  81881. theta -= 2 * Math.PI;
  81882. var dx = theta / Math.PI;
  81883. var dy = phi / Math.PI;
  81884. // recenter.
  81885. dx = dx * 0.5 + 0.5;
  81886. var px = Math.round(dx * inputWidth);
  81887. if (px < 0)
  81888. px = 0;
  81889. else if (px >= inputWidth)
  81890. px = inputWidth - 1;
  81891. var py = Math.round(dy * inputHeight);
  81892. if (py < 0)
  81893. py = 0;
  81894. else if (py >= inputHeight)
  81895. py = inputHeight - 1;
  81896. var inputY = (inputHeight - py - 1);
  81897. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  81898. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  81899. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  81900. return {
  81901. r: r,
  81902. g: g,
  81903. b: b
  81904. };
  81905. };
  81906. PanoramaToCubeMapTools.FACE_FRONT = [
  81907. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81908. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81909. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81910. new BABYLON.Vector3(1.0, 1.0, -1.0)
  81911. ];
  81912. PanoramaToCubeMapTools.FACE_BACK = [
  81913. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81914. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81915. new BABYLON.Vector3(1.0, 1.0, 1.0),
  81916. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  81917. ];
  81918. PanoramaToCubeMapTools.FACE_RIGHT = [
  81919. new BABYLON.Vector3(1.0, -1.0, -1.0),
  81920. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81921. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81922. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81923. ];
  81924. PanoramaToCubeMapTools.FACE_LEFT = [
  81925. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81926. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81927. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81928. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  81929. ];
  81930. PanoramaToCubeMapTools.FACE_DOWN = [
  81931. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  81932. new BABYLON.Vector3(1.0, 1.0, -1.0),
  81933. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  81934. new BABYLON.Vector3(1.0, 1.0, 1.0)
  81935. ];
  81936. PanoramaToCubeMapTools.FACE_UP = [
  81937. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  81938. new BABYLON.Vector3(1.0, -1.0, 1.0),
  81939. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  81940. new BABYLON.Vector3(1.0, -1.0, -1.0)
  81941. ];
  81942. return PanoramaToCubeMapTools;
  81943. }());
  81944. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  81945. })(BABYLON || (BABYLON = {}));
  81946. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  81947. var BABYLON;
  81948. (function (BABYLON) {
  81949. ;
  81950. /**
  81951. * This groups tools to convert HDR texture to native colors array.
  81952. */
  81953. var HDRTools = /** @class */ (function () {
  81954. function HDRTools() {
  81955. }
  81956. HDRTools.Ldexp = function (mantissa, exponent) {
  81957. if (exponent > 1023) {
  81958. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  81959. }
  81960. if (exponent < -1074) {
  81961. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  81962. }
  81963. return mantissa * Math.pow(2, exponent);
  81964. };
  81965. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  81966. if (exponent > 0) { /*nonzero pixel*/
  81967. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  81968. float32array[index + 0] = red * exponent;
  81969. float32array[index + 1] = green * exponent;
  81970. float32array[index + 2] = blue * exponent;
  81971. }
  81972. else {
  81973. float32array[index + 0] = 0;
  81974. float32array[index + 1] = 0;
  81975. float32array[index + 2] = 0;
  81976. }
  81977. };
  81978. HDRTools.readStringLine = function (uint8array, startIndex) {
  81979. var line = "";
  81980. var character = "";
  81981. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  81982. character = String.fromCharCode(uint8array[i]);
  81983. if (character == "\n") {
  81984. break;
  81985. }
  81986. line += character;
  81987. }
  81988. return line;
  81989. };
  81990. /**
  81991. * Reads header information from an RGBE texture stored in a native array.
  81992. * More information on this format are available here:
  81993. * https://en.wikipedia.org/wiki/RGBE_image_format
  81994. *
  81995. * @param uint8array The binary file stored in native array.
  81996. * @return The header information.
  81997. */
  81998. HDRTools.RGBE_ReadHeader = function (uint8array) {
  81999. var height = 0;
  82000. var width = 0;
  82001. var line = this.readStringLine(uint8array, 0);
  82002. if (line[0] != '#' || line[1] != '?') {
  82003. throw "Bad HDR Format.";
  82004. }
  82005. var endOfHeader = false;
  82006. var findFormat = false;
  82007. var lineIndex = 0;
  82008. do {
  82009. lineIndex += (line.length + 1);
  82010. line = this.readStringLine(uint8array, lineIndex);
  82011. if (line == "FORMAT=32-bit_rle_rgbe") {
  82012. findFormat = true;
  82013. }
  82014. else if (line.length == 0) {
  82015. endOfHeader = true;
  82016. }
  82017. } while (!endOfHeader);
  82018. if (!findFormat) {
  82019. throw "HDR Bad header format, unsupported FORMAT";
  82020. }
  82021. lineIndex += (line.length + 1);
  82022. line = this.readStringLine(uint8array, lineIndex);
  82023. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82024. var match = sizeRegexp.exec(line);
  82025. // TODO. Support +Y and -X if needed.
  82026. if (!match || match.length < 3) {
  82027. throw "HDR Bad header format, no size";
  82028. }
  82029. width = parseInt(match[2]);
  82030. height = parseInt(match[1]);
  82031. if (width < 8 || width > 0x7fff) {
  82032. throw "HDR Bad header format, unsupported size";
  82033. }
  82034. lineIndex += (line.length + 1);
  82035. return {
  82036. height: height,
  82037. width: width,
  82038. dataPosition: lineIndex
  82039. };
  82040. };
  82041. /**
  82042. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82043. * This RGBE texture needs to store the information as a panorama.
  82044. *
  82045. * More information on this format are available here:
  82046. * https://en.wikipedia.org/wiki/RGBE_image_format
  82047. *
  82048. * @param buffer The binary file stored in an array buffer.
  82049. * @param size The expected size of the extracted cubemap.
  82050. * @return The Cube Map information.
  82051. */
  82052. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82053. var uint8array = new Uint8Array(buffer);
  82054. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82055. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82056. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82057. return cubeMapData;
  82058. };
  82059. /**
  82060. * Returns the pixels data extracted from an RGBE texture.
  82061. * This pixels will be stored left to right up to down in the R G B order in one array.
  82062. *
  82063. * More information on this format are available here:
  82064. * https://en.wikipedia.org/wiki/RGBE_image_format
  82065. *
  82066. * @param uint8array The binary file stored in an array buffer.
  82067. * @param hdrInfo The header information of the file.
  82068. * @return The pixels data in RGB right to left up to down order.
  82069. */
  82070. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82071. // Keep for multi format supports.
  82072. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82073. };
  82074. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82075. var num_scanlines = hdrInfo.height;
  82076. var scanline_width = hdrInfo.width;
  82077. var a, b, c, d, count;
  82078. var dataIndex = hdrInfo.dataPosition;
  82079. var index = 0, endIndex = 0, i = 0;
  82080. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82081. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82082. // 3 channels of 4 bytes per pixel in float.
  82083. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82084. var resultArray = new Float32Array(resultBuffer);
  82085. // read in each successive scanline
  82086. while (num_scanlines > 0) {
  82087. a = uint8array[dataIndex++];
  82088. b = uint8array[dataIndex++];
  82089. c = uint8array[dataIndex++];
  82090. d = uint8array[dataIndex++];
  82091. if (a != 2 || b != 2 || (c & 0x80)) {
  82092. // this file is not run length encoded
  82093. throw "HDR Bad header format, not RLE";
  82094. }
  82095. if (((c << 8) | d) != scanline_width) {
  82096. throw "HDR Bad header format, wrong scan line width";
  82097. }
  82098. index = 0;
  82099. // read each of the four channels for the scanline into the buffer
  82100. for (i = 0; i < 4; i++) {
  82101. endIndex = (i + 1) * scanline_width;
  82102. while (index < endIndex) {
  82103. a = uint8array[dataIndex++];
  82104. b = uint8array[dataIndex++];
  82105. if (a > 128) {
  82106. // a run of the same value
  82107. count = a - 128;
  82108. if ((count == 0) || (count > endIndex - index)) {
  82109. throw "HDR Bad Format, bad scanline data (run)";
  82110. }
  82111. while (count-- > 0) {
  82112. scanLineArray[index++] = b;
  82113. }
  82114. }
  82115. else {
  82116. // a non-run
  82117. count = a;
  82118. if ((count == 0) || (count > endIndex - index)) {
  82119. throw "HDR Bad Format, bad scanline data (non-run)";
  82120. }
  82121. scanLineArray[index++] = b;
  82122. if (--count > 0) {
  82123. for (var j = 0; j < count; j++) {
  82124. scanLineArray[index++] = uint8array[dataIndex++];
  82125. }
  82126. }
  82127. }
  82128. }
  82129. }
  82130. // now convert data from buffer into floats
  82131. for (i = 0; i < scanline_width; i++) {
  82132. a = scanLineArray[i];
  82133. b = scanLineArray[i + scanline_width];
  82134. c = scanLineArray[i + 2 * scanline_width];
  82135. d = scanLineArray[i + 3 * scanline_width];
  82136. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82137. }
  82138. num_scanlines--;
  82139. }
  82140. return resultArray;
  82141. };
  82142. return HDRTools;
  82143. }());
  82144. BABYLON.HDRTools = HDRTools;
  82145. })(BABYLON || (BABYLON = {}));
  82146. //# sourceMappingURL=babylon.hdr.js.map
  82147. var BABYLON;
  82148. (function (BABYLON) {
  82149. /**
  82150. * Sets of helpers addressing the serialization and deserialization of environment texture
  82151. * stored in a BabylonJS env file.
  82152. * Those files are usually stored as .env files.
  82153. */
  82154. var EnvironmentTextureTools = /** @class */ (function () {
  82155. function EnvironmentTextureTools() {
  82156. }
  82157. /**
  82158. * Gets the environment info from an env file.
  82159. * @param data The array buffer containing the .env bytes.
  82160. * @returns the environment file info (the json header) if successfully parsed.
  82161. */
  82162. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82163. var dataView = new DataView(data);
  82164. var pos = 0;
  82165. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82166. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82167. BABYLON.Tools.Error('Not a babylon environment map');
  82168. return null;
  82169. }
  82170. }
  82171. // Read json manifest - collect characters up to null terminator
  82172. var manifestString = '';
  82173. var charCode = 0x00;
  82174. while ((charCode = dataView.getUint8(pos++))) {
  82175. manifestString += String.fromCharCode(charCode);
  82176. }
  82177. var manifest = JSON.parse(manifestString);
  82178. if (manifest.specular) {
  82179. // Extend the header with the position of the payload.
  82180. manifest.specular.specularDataPosition = pos;
  82181. }
  82182. return manifest;
  82183. };
  82184. /**
  82185. * Creates an environment texture from a loaded cube texture.
  82186. * @param texture defines the cube texture to convert in env file
  82187. * @return a promise containing the environment data if succesfull.
  82188. */
  82189. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82190. var _this = this;
  82191. var internalTexture = texture.getInternalTexture();
  82192. if (!internalTexture) {
  82193. return Promise.reject("The cube texture is invalid.");
  82194. }
  82195. if (!texture._prefiltered) {
  82196. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82197. }
  82198. var engine = internalTexture.getEngine();
  82199. if (engine && engine.premultipliedAlpha) {
  82200. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82201. }
  82202. var canvas = engine.getRenderingCanvas();
  82203. if (!canvas) {
  82204. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82205. }
  82206. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82207. if (!engine.getCaps().textureFloatRender) {
  82208. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82209. if (!engine.getCaps().textureHalfFloatRender) {
  82210. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82211. }
  82212. }
  82213. var cubeWidth = internalTexture.width;
  82214. var hostingScene = new BABYLON.Scene(engine);
  82215. var specularTextures = {};
  82216. var promises = [];
  82217. // Read and collect all mipmaps data from the cube.
  82218. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82219. mipmapsCount = Math.round(mipmapsCount);
  82220. var _loop_1 = function (i) {
  82221. var faceWidth = Math.pow(2, mipmapsCount - i);
  82222. var _loop_2 = function (face) {
  82223. var data = texture.readPixels(face, i);
  82224. // Creates a temp texture with the face data.
  82225. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82226. // And rgbdEncode them.
  82227. var promise = new Promise(function (resolve, reject) {
  82228. 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);
  82229. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82230. rgbdPostProcess.onApply = function (effect) {
  82231. effect._bindTexture("textureSampler", tempTexture);
  82232. };
  82233. // As the process needs to happen on the main canvas, keep track of the current size
  82234. var currentW = engine.getRenderWidth();
  82235. var currentH = engine.getRenderHeight();
  82236. // Set the desired size for the texture
  82237. engine.setSize(faceWidth, faceWidth);
  82238. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82239. // Reading datas from WebGL
  82240. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82241. var fileReader = new FileReader();
  82242. fileReader.onload = function (event) {
  82243. var arrayBuffer = event.target.result;
  82244. specularTextures[i * 6 + face] = arrayBuffer;
  82245. resolve();
  82246. };
  82247. fileReader.readAsArrayBuffer(blob);
  82248. });
  82249. // Reapply the previous canvas size
  82250. engine.setSize(currentW, currentH);
  82251. });
  82252. });
  82253. promises.push(promise);
  82254. };
  82255. // All faces of the cube.
  82256. for (var face = 0; face < 6; face++) {
  82257. _loop_2(face);
  82258. }
  82259. };
  82260. for (var i = 0; i <= mipmapsCount; i++) {
  82261. _loop_1(i);
  82262. }
  82263. // Once all the textures haves been collected as RGBD stored in PNGs
  82264. return Promise.all(promises).then(function () {
  82265. // We can delete the hosting scene keeping track of all the creation objects
  82266. hostingScene.dispose();
  82267. // Creates the json header for the env texture
  82268. var info = {
  82269. version: 1,
  82270. width: cubeWidth,
  82271. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82272. specular: {
  82273. mipmaps: []
  82274. }
  82275. };
  82276. // Sets the specular image data information
  82277. var position = 0;
  82278. for (var i = 0; i <= mipmapsCount; i++) {
  82279. for (var face = 0; face < 6; face++) {
  82280. var byteLength = specularTextures[i * 6 + face].byteLength;
  82281. info.specular.mipmaps.push({
  82282. length: byteLength,
  82283. position: position
  82284. });
  82285. position += byteLength;
  82286. }
  82287. }
  82288. // Encode the JSON as an array buffer
  82289. var infoString = JSON.stringify(info);
  82290. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82291. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82292. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82293. infoView[i] = infoString.charCodeAt(i);
  82294. }
  82295. // Ends up with a null terminator for easier parsing
  82296. infoView[infoString.length] = 0x00;
  82297. // Computes the final required size and creates the storage
  82298. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82299. var finalBuffer = new ArrayBuffer(totalSize);
  82300. var finalBufferView = new Uint8Array(finalBuffer);
  82301. var dataView = new DataView(finalBuffer);
  82302. // Copy the magic bytes identifying the file in
  82303. var pos = 0;
  82304. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82305. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82306. }
  82307. // Add the json info
  82308. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82309. pos += infoBuffer.byteLength;
  82310. // Finally inserts the texture data
  82311. for (var i = 0; i <= mipmapsCount; i++) {
  82312. for (var face = 0; face < 6; face++) {
  82313. var dataBuffer = specularTextures[i * 6 + face];
  82314. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82315. pos += dataBuffer.byteLength;
  82316. }
  82317. }
  82318. // Voila
  82319. return finalBuffer;
  82320. });
  82321. };
  82322. /**
  82323. * Creates a JSON representation of the spherical data.
  82324. * @param texture defines the texture containing the polynomials
  82325. * @return the JSON representation of the spherical info
  82326. */
  82327. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82328. var polynmials = texture.sphericalPolynomial;
  82329. if (polynmials == null) {
  82330. return null;
  82331. }
  82332. return {
  82333. polynomials: true,
  82334. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82335. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82336. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82337. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82338. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82339. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82340. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82341. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82342. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82343. };
  82344. };
  82345. /**
  82346. * Uploads the texture info contained in the env file to te GPU.
  82347. * @param texture defines the internal texture to upload to
  82348. * @param arrayBuffer defines the buffer cotaining the data to load
  82349. * @param info defines the texture info retrieved through the GetEnvInfo method
  82350. * @returns a promise
  82351. */
  82352. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82353. if (info.version !== 1) {
  82354. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82355. }
  82356. var specularInfo = info.specular;
  82357. if (!specularInfo) {
  82358. // Nothing else parsed so far
  82359. return Promise.resolve();
  82360. }
  82361. // Double checks the enclosed info
  82362. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82363. mipmapsCount = Math.round(mipmapsCount) + 1;
  82364. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82365. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82366. }
  82367. // Gets everything ready.
  82368. var engine = texture.getEngine();
  82369. var expandTexture = false;
  82370. var generateNonLODTextures = false;
  82371. var rgbdPostProcess = null;
  82372. var cubeRtt = null;
  82373. var lodTextures = null;
  82374. var caps = engine.getCaps();
  82375. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82376. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82377. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82378. // Add extra process if texture lod is not supported
  82379. if (!caps.textureLOD) {
  82380. expandTexture = false;
  82381. generateNonLODTextures = true;
  82382. lodTextures = {};
  82383. }
  82384. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82385. else if (engine.webGLVersion < 2) {
  82386. expandTexture = false;
  82387. }
  82388. // If half float available we can uncompress the texture
  82389. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82390. expandTexture = true;
  82391. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82392. }
  82393. // If full float available we can uncompress the texture
  82394. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82395. expandTexture = true;
  82396. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82397. }
  82398. // Expand the texture if possible
  82399. if (expandTexture) {
  82400. // Simply run through the decode PP
  82401. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82402. texture._isRGBD = false;
  82403. texture.invertY = false;
  82404. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82405. generateDepthBuffer: false,
  82406. generateMipMaps: true,
  82407. generateStencilBuffer: false,
  82408. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82409. type: texture.type,
  82410. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82411. });
  82412. }
  82413. else {
  82414. texture._isRGBD = true;
  82415. texture.invertY = true;
  82416. // In case of missing support, applies the same patch than DDS files.
  82417. if (generateNonLODTextures) {
  82418. var mipSlices = 3;
  82419. var scale = texture._lodGenerationScale;
  82420. var offset = texture._lodGenerationOffset;
  82421. for (var i = 0; i < mipSlices; i++) {
  82422. //compute LOD from even spacing in smoothness (matching shader calculation)
  82423. var smoothness = i / (mipSlices - 1);
  82424. var roughness = 1 - smoothness;
  82425. var minLODIndex = offset; // roughness = 0
  82426. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82427. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82428. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82429. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82430. glTextureFromLod.isCube = true;
  82431. glTextureFromLod.invertY = true;
  82432. glTextureFromLod.generateMipMaps = false;
  82433. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82434. // Wrap in a base texture for easy binding.
  82435. var lodTexture = new BABYLON.BaseTexture(null);
  82436. lodTexture.isCube = true;
  82437. lodTexture._texture = glTextureFromLod;
  82438. lodTextures[mipmapIndex] = lodTexture;
  82439. switch (i) {
  82440. case 0:
  82441. texture._lodTextureLow = lodTexture;
  82442. break;
  82443. case 1:
  82444. texture._lodTextureMid = lodTexture;
  82445. break;
  82446. case 2:
  82447. texture._lodTextureHigh = lodTexture;
  82448. break;
  82449. }
  82450. }
  82451. }
  82452. }
  82453. var promises = [];
  82454. var _loop_3 = function (i) {
  82455. var _loop_4 = function (face) {
  82456. // Retrieves the face data
  82457. var imageData = specularInfo.mipmaps[i * 6 + face];
  82458. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82459. // Constructs an image element from bytes
  82460. var blob = new Blob([bytes], { type: 'image/png' });
  82461. var url = URL.createObjectURL(blob);
  82462. var image = new Image();
  82463. image.src = url;
  82464. // Enqueue promise to upload to the texture.
  82465. var promise = new Promise(function (resolve, reject) {
  82466. ;
  82467. image.onload = function () {
  82468. if (expandTexture) {
  82469. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82470. reject(message);
  82471. }, image);
  82472. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82473. // Uncompress the data to a RTT
  82474. rgbdPostProcess.onApply = function (effect) {
  82475. effect._bindTexture("textureSampler", tempTexture_1);
  82476. effect.setFloat2("scale", 1, 1);
  82477. };
  82478. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82479. // Cleanup
  82480. engine.restoreDefaultFramebuffer();
  82481. tempTexture_1.dispose();
  82482. window.URL.revokeObjectURL(url);
  82483. resolve();
  82484. });
  82485. }
  82486. else {
  82487. engine._uploadImageToTexture(texture, face, i, image);
  82488. // Upload the face to the none lod texture support
  82489. if (generateNonLODTextures) {
  82490. var lodTexture = lodTextures[i];
  82491. if (lodTexture) {
  82492. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82493. }
  82494. }
  82495. resolve();
  82496. }
  82497. };
  82498. image.onerror = function (error) {
  82499. reject(error);
  82500. };
  82501. });
  82502. promises.push(promise);
  82503. };
  82504. // All faces
  82505. for (var face = 0; face < 6; face++) {
  82506. _loop_4(face);
  82507. }
  82508. };
  82509. // All mipmaps
  82510. for (var i = 0; i < mipmapsCount; i++) {
  82511. _loop_3(i);
  82512. }
  82513. // Once all done, finishes the cleanup and return
  82514. return Promise.all(promises).then(function () {
  82515. // Relase temp RTT.
  82516. if (cubeRtt) {
  82517. engine._releaseFramebufferObjects(cubeRtt);
  82518. cubeRtt._swapAndDie(texture);
  82519. }
  82520. // Relase temp Post Process.
  82521. if (rgbdPostProcess) {
  82522. rgbdPostProcess.dispose();
  82523. }
  82524. // Flag internal texture as ready in case they are in use.
  82525. if (generateNonLODTextures) {
  82526. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82527. texture._lodTextureHigh._texture.isReady = true;
  82528. }
  82529. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82530. texture._lodTextureMid._texture.isReady = true;
  82531. }
  82532. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82533. texture._lodTextureLow._texture.isReady = true;
  82534. }
  82535. }
  82536. });
  82537. };
  82538. /**
  82539. * Uploads spherical polynomials information to the texture.
  82540. * @param texture defines the texture we are trying to upload the information to
  82541. * @param arrayBuffer defines the array buffer holding the data
  82542. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82543. */
  82544. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82545. if (info.version !== 1) {
  82546. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82547. }
  82548. var irradianceInfo = info.irradiance;
  82549. if (!irradianceInfo) {
  82550. return;
  82551. }
  82552. //harmonics now represent radiance
  82553. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82554. if (irradianceInfo.polynomials) {
  82555. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82556. }
  82557. else {
  82558. // convert From SH to SP.
  82559. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82560. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82561. }
  82562. };
  82563. /**
  82564. * Upload spherical polynomial coefficients to the texture
  82565. * @param polynmials Spherical polynmial coefficients (9)
  82566. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82567. */
  82568. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82569. outPolynomialCoefficents.x.x = polynmials.x[0];
  82570. outPolynomialCoefficents.x.y = polynmials.x[1];
  82571. outPolynomialCoefficents.x.z = polynmials.x[2];
  82572. outPolynomialCoefficents.y.x = polynmials.y[0];
  82573. outPolynomialCoefficents.y.y = polynmials.y[1];
  82574. outPolynomialCoefficents.y.z = polynmials.y[2];
  82575. outPolynomialCoefficents.z.x = polynmials.z[0];
  82576. outPolynomialCoefficents.z.y = polynmials.z[1];
  82577. outPolynomialCoefficents.z.z = polynmials.z[2];
  82578. //xx
  82579. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82580. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82581. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82582. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82583. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82584. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82585. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82586. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82587. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82588. //yz
  82589. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82590. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82591. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82592. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82593. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82594. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82595. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82596. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82597. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82598. };
  82599. /**
  82600. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82601. * L = (1/pi) * E * rho
  82602. *
  82603. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82604. * @param harmonics Spherical harmonic coefficients (9)
  82605. */
  82606. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82607. var scaleFactor = 1 / Math.PI;
  82608. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82609. // (The pixel shader must apply albedo after texture fetches, etc).
  82610. harmonics.l00[0] *= scaleFactor;
  82611. harmonics.l00[1] *= scaleFactor;
  82612. harmonics.l00[2] *= scaleFactor;
  82613. harmonics.l1_1[0] *= scaleFactor;
  82614. harmonics.l1_1[1] *= scaleFactor;
  82615. harmonics.l1_1[2] *= scaleFactor;
  82616. harmonics.l10[0] *= scaleFactor;
  82617. harmonics.l10[1] *= scaleFactor;
  82618. harmonics.l10[2] *= scaleFactor;
  82619. harmonics.l11[0] *= scaleFactor;
  82620. harmonics.l11[1] *= scaleFactor;
  82621. harmonics.l11[2] *= scaleFactor;
  82622. harmonics.l2_2[0] *= scaleFactor;
  82623. harmonics.l2_2[1] *= scaleFactor;
  82624. harmonics.l2_2[2] *= scaleFactor;
  82625. harmonics.l2_1[0] *= scaleFactor;
  82626. harmonics.l2_1[1] *= scaleFactor;
  82627. harmonics.l2_1[2] *= scaleFactor;
  82628. harmonics.l20[0] *= scaleFactor;
  82629. harmonics.l20[1] *= scaleFactor;
  82630. harmonics.l20[2] *= scaleFactor;
  82631. harmonics.l21[0] *= scaleFactor;
  82632. harmonics.l21[1] *= scaleFactor;
  82633. harmonics.l21[2] *= scaleFactor;
  82634. harmonics.l22[0] *= scaleFactor;
  82635. harmonics.l22[1] *= scaleFactor;
  82636. harmonics.l22[2] *= scaleFactor;
  82637. };
  82638. /**
  82639. * Convert spherical harmonics to spherical polynomial coefficients
  82640. * @param harmonics Spherical harmonic coefficients (9)
  82641. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82642. */
  82643. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82644. var rPi = 1 / Math.PI;
  82645. //x
  82646. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82647. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82648. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82649. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82650. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82651. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82652. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82653. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82654. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82655. //xx
  82656. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82657. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82658. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82659. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82660. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82661. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82662. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82663. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82664. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82665. //yz
  82666. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82667. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82668. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82669. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82670. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82671. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82672. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82673. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82674. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82675. };
  82676. /**
  82677. * Magic number identifying the env file.
  82678. */
  82679. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82680. return EnvironmentTextureTools;
  82681. }());
  82682. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82683. })(BABYLON || (BABYLON = {}));
  82684. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82685. var BABYLON;
  82686. (function (BABYLON) {
  82687. /**
  82688. * This represents a texture coming from an HDR input.
  82689. *
  82690. * The only supported format is currently panorama picture stored in RGBE format.
  82691. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82692. */
  82693. var HDRCubeTexture = /** @class */ (function (_super) {
  82694. __extends(HDRCubeTexture, _super);
  82695. /**
  82696. * Instantiates an HDRTexture from the following parameters.
  82697. *
  82698. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82699. * @param scene The scene the texture will be used in
  82700. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82701. * @param noMipmap Forces to not generate the mipmap if true
  82702. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82703. * @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)
  82704. * @param reserved Reserved flag for internal use.
  82705. */
  82706. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82707. if (noMipmap === void 0) { noMipmap = false; }
  82708. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82709. if (gammaSpace === void 0) { gammaSpace = false; }
  82710. if (reserved === void 0) { reserved = false; }
  82711. if (onLoad === void 0) { onLoad = null; }
  82712. if (onError === void 0) { onError = null; }
  82713. var _this = _super.call(this, scene) || this;
  82714. _this._generateHarmonics = true;
  82715. _this._onLoad = null;
  82716. _this._onError = null;
  82717. /**
  82718. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82719. */
  82720. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82721. _this._isBlocking = true;
  82722. _this._rotationY = 0;
  82723. /**
  82724. * Gets or sets the center of the bounding box associated with the cube texture
  82725. * It must define where the camera used to render the texture was set
  82726. */
  82727. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82728. if (!url) {
  82729. return _this;
  82730. }
  82731. _this.name = url;
  82732. _this.url = url;
  82733. _this.hasAlpha = false;
  82734. _this.isCube = true;
  82735. _this._textureMatrix = BABYLON.Matrix.Identity();
  82736. _this._onLoad = onLoad;
  82737. _this._onError = onError;
  82738. _this.gammaSpace = gammaSpace;
  82739. _this._noMipmap = noMipmap;
  82740. _this._size = size;
  82741. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82742. if (!_this._texture) {
  82743. if (!scene.useDelayedTextureLoading) {
  82744. _this.loadTexture();
  82745. }
  82746. else {
  82747. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82748. }
  82749. }
  82750. return _this;
  82751. }
  82752. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82753. /**
  82754. * Gets wether or not the texture is blocking during loading.
  82755. */
  82756. get: function () {
  82757. return this._isBlocking;
  82758. },
  82759. /**
  82760. * Sets wether or not the texture is blocking during loading.
  82761. */
  82762. set: function (value) {
  82763. this._isBlocking = value;
  82764. },
  82765. enumerable: true,
  82766. configurable: true
  82767. });
  82768. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82769. /**
  82770. * Gets texture matrix rotation angle around Y axis radians.
  82771. */
  82772. get: function () {
  82773. return this._rotationY;
  82774. },
  82775. /**
  82776. * Sets texture matrix rotation angle around Y axis in radians.
  82777. */
  82778. set: function (value) {
  82779. this._rotationY = value;
  82780. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82781. },
  82782. enumerable: true,
  82783. configurable: true
  82784. });
  82785. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82786. get: function () {
  82787. return this._boundingBoxSize;
  82788. },
  82789. /**
  82790. * Gets or sets the size of the bounding box associated with the cube texture
  82791. * When defined, the cubemap will switch to local mode
  82792. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82793. * @example https://www.babylonjs-playground.com/#RNASML
  82794. */
  82795. set: function (value) {
  82796. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82797. return;
  82798. }
  82799. this._boundingBoxSize = value;
  82800. var scene = this.getScene();
  82801. if (scene) {
  82802. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82803. }
  82804. },
  82805. enumerable: true,
  82806. configurable: true
  82807. });
  82808. /**
  82809. * Occurs when the file is raw .hdr file.
  82810. */
  82811. HDRCubeTexture.prototype.loadTexture = function () {
  82812. var _this = this;
  82813. var callback = function (buffer) {
  82814. _this.lodGenerationOffset = 0.0;
  82815. _this.lodGenerationScale = 0.8;
  82816. var scene = _this.getScene();
  82817. if (!scene) {
  82818. return null;
  82819. }
  82820. // Extract the raw linear data.
  82821. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82822. // Generate harmonics if needed.
  82823. if (_this._generateHarmonics) {
  82824. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82825. _this.sphericalPolynomial = sphericalPolynomial;
  82826. }
  82827. var results = [];
  82828. var byteArray = null;
  82829. // Push each faces.
  82830. for (var j = 0; j < 6; j++) {
  82831. // Create uintarray fallback.
  82832. if (!scene.getEngine().getCaps().textureFloat) {
  82833. // 3 channels of 1 bytes per pixel in bytes.
  82834. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  82835. byteArray = new Uint8Array(byteBuffer);
  82836. }
  82837. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  82838. // If special cases.
  82839. if (_this.gammaSpace || byteArray) {
  82840. for (var i = 0; i < _this._size * _this._size; i++) {
  82841. // Put in gamma space if requested.
  82842. if (_this.gammaSpace) {
  82843. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  82844. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  82845. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  82846. }
  82847. // Convert to int texture for fallback.
  82848. if (byteArray) {
  82849. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  82850. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  82851. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  82852. // May use luminance instead if the result is not accurate.
  82853. var max = Math.max(Math.max(r, g), b);
  82854. if (max > 255) {
  82855. var scale = 255 / max;
  82856. r *= scale;
  82857. g *= scale;
  82858. b *= scale;
  82859. }
  82860. byteArray[(i * 3) + 0] = r;
  82861. byteArray[(i * 3) + 1] = g;
  82862. byteArray[(i * 3) + 2] = b;
  82863. }
  82864. }
  82865. }
  82866. if (byteArray) {
  82867. results.push(byteArray);
  82868. }
  82869. else {
  82870. results.push(dataFace);
  82871. }
  82872. }
  82873. return results;
  82874. };
  82875. var scene = this.getScene();
  82876. if (scene) {
  82877. 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);
  82878. }
  82879. };
  82880. HDRCubeTexture.prototype.clone = function () {
  82881. var scene = this.getScene();
  82882. if (!scene) {
  82883. return this;
  82884. }
  82885. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  82886. // Base texture
  82887. newTexture.level = this.level;
  82888. newTexture.wrapU = this.wrapU;
  82889. newTexture.wrapV = this.wrapV;
  82890. newTexture.coordinatesIndex = this.coordinatesIndex;
  82891. newTexture.coordinatesMode = this.coordinatesMode;
  82892. return newTexture;
  82893. };
  82894. // Methods
  82895. HDRCubeTexture.prototype.delayLoad = function () {
  82896. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  82897. return;
  82898. }
  82899. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  82900. this._texture = this._getFromCache(this.url, this._noMipmap);
  82901. if (!this._texture) {
  82902. this.loadTexture();
  82903. }
  82904. };
  82905. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  82906. return this._textureMatrix;
  82907. };
  82908. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  82909. this._textureMatrix = value;
  82910. };
  82911. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  82912. var texture = null;
  82913. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  82914. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  82915. texture.name = parsedTexture.name;
  82916. texture.hasAlpha = parsedTexture.hasAlpha;
  82917. texture.level = parsedTexture.level;
  82918. texture.coordinatesMode = parsedTexture.coordinatesMode;
  82919. texture.isBlocking = parsedTexture.isBlocking;
  82920. }
  82921. if (texture) {
  82922. if (parsedTexture.boundingBoxPosition) {
  82923. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  82924. }
  82925. if (parsedTexture.boundingBoxSize) {
  82926. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  82927. }
  82928. if (parsedTexture.rotationY) {
  82929. texture.rotationY = parsedTexture.rotationY;
  82930. }
  82931. }
  82932. return texture;
  82933. };
  82934. HDRCubeTexture.prototype.serialize = function () {
  82935. if (!this.name) {
  82936. return null;
  82937. }
  82938. var serializationObject = {};
  82939. serializationObject.name = this.name;
  82940. serializationObject.hasAlpha = this.hasAlpha;
  82941. serializationObject.isCube = true;
  82942. serializationObject.level = this.level;
  82943. serializationObject.size = this._size;
  82944. serializationObject.coordinatesMode = this.coordinatesMode;
  82945. serializationObject.useInGammaSpace = this.gammaSpace;
  82946. serializationObject.generateHarmonics = this._generateHarmonics;
  82947. serializationObject.customType = "BABYLON.HDRCubeTexture";
  82948. serializationObject.noMipmap = this._noMipmap;
  82949. serializationObject.isBlocking = this._isBlocking;
  82950. serializationObject.rotationY = this._rotationY;
  82951. return serializationObject;
  82952. };
  82953. HDRCubeTexture._facesMapping = [
  82954. "right",
  82955. "left",
  82956. "up",
  82957. "down",
  82958. "front",
  82959. "back"
  82960. ];
  82961. return HDRCubeTexture;
  82962. }(BABYLON.BaseTexture));
  82963. BABYLON.HDRCubeTexture = HDRCubeTexture;
  82964. })(BABYLON || (BABYLON = {}));
  82965. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  82966. var BABYLON;
  82967. (function (BABYLON) {
  82968. var IndexedVector2 = /** @class */ (function (_super) {
  82969. __extends(IndexedVector2, _super);
  82970. function IndexedVector2(original, index) {
  82971. var _this = _super.call(this, original.x, original.y) || this;
  82972. _this.index = index;
  82973. return _this;
  82974. }
  82975. return IndexedVector2;
  82976. }(BABYLON.Vector2));
  82977. var PolygonPoints = /** @class */ (function () {
  82978. function PolygonPoints() {
  82979. this.elements = new Array();
  82980. }
  82981. PolygonPoints.prototype.add = function (originalPoints) {
  82982. var _this = this;
  82983. var result = new Array();
  82984. originalPoints.forEach(function (point) {
  82985. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  82986. var newPoint = new IndexedVector2(point, _this.elements.length);
  82987. result.push(newPoint);
  82988. _this.elements.push(newPoint);
  82989. }
  82990. });
  82991. return result;
  82992. };
  82993. PolygonPoints.prototype.computeBounds = function () {
  82994. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82995. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  82996. this.elements.forEach(function (point) {
  82997. // x
  82998. if (point.x < lmin.x) {
  82999. lmin.x = point.x;
  83000. }
  83001. else if (point.x > lmax.x) {
  83002. lmax.x = point.x;
  83003. }
  83004. // y
  83005. if (point.y < lmin.y) {
  83006. lmin.y = point.y;
  83007. }
  83008. else if (point.y > lmax.y) {
  83009. lmax.y = point.y;
  83010. }
  83011. });
  83012. return {
  83013. min: lmin,
  83014. max: lmax,
  83015. width: lmax.x - lmin.x,
  83016. height: lmax.y - lmin.y
  83017. };
  83018. };
  83019. return PolygonPoints;
  83020. }());
  83021. var Polygon = /** @class */ (function () {
  83022. function Polygon() {
  83023. }
  83024. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83025. return [
  83026. new BABYLON.Vector2(xmin, ymin),
  83027. new BABYLON.Vector2(xmax, ymin),
  83028. new BABYLON.Vector2(xmax, ymax),
  83029. new BABYLON.Vector2(xmin, ymax)
  83030. ];
  83031. };
  83032. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83033. if (cx === void 0) { cx = 0; }
  83034. if (cy === void 0) { cy = 0; }
  83035. if (numberOfSides === void 0) { numberOfSides = 32; }
  83036. var result = new Array();
  83037. var angle = 0;
  83038. var increment = (Math.PI * 2) / numberOfSides;
  83039. for (var i = 0; i < numberOfSides; i++) {
  83040. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83041. angle -= increment;
  83042. }
  83043. return result;
  83044. };
  83045. Polygon.Parse = function (input) {
  83046. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83047. var i, result = [];
  83048. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83049. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83050. }
  83051. return result;
  83052. };
  83053. Polygon.StartingAt = function (x, y) {
  83054. return BABYLON.Path2.StartingAt(x, y);
  83055. };
  83056. return Polygon;
  83057. }());
  83058. BABYLON.Polygon = Polygon;
  83059. var PolygonMeshBuilder = /** @class */ (function () {
  83060. function PolygonMeshBuilder(name, contours, scene) {
  83061. this._points = new PolygonPoints();
  83062. this._outlinepoints = new PolygonPoints();
  83063. this._holes = new Array();
  83064. this._epoints = new Array();
  83065. this._eholes = new Array();
  83066. this._name = name;
  83067. this._scene = scene;
  83068. var points;
  83069. if (contours instanceof BABYLON.Path2) {
  83070. points = contours.getPoints();
  83071. }
  83072. else {
  83073. points = contours;
  83074. }
  83075. this._addToepoint(points);
  83076. this._points.add(points);
  83077. this._outlinepoints.add(points);
  83078. if (typeof earcut === 'undefined') {
  83079. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83080. }
  83081. }
  83082. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83083. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83084. var p = points_1[_i];
  83085. this._epoints.push(p.x, p.y);
  83086. }
  83087. };
  83088. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83089. this._points.add(hole);
  83090. var holepoints = new PolygonPoints();
  83091. holepoints.add(hole);
  83092. this._holes.push(holepoints);
  83093. this._eholes.push(this._epoints.length / 2);
  83094. this._addToepoint(hole);
  83095. return this;
  83096. };
  83097. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83098. var _this = this;
  83099. if (updatable === void 0) { updatable = false; }
  83100. if (depth === void 0) { depth = 0; }
  83101. var result = new BABYLON.Mesh(this._name, this._scene);
  83102. var normals = new Array();
  83103. var positions = new Array();
  83104. var uvs = new Array();
  83105. var bounds = this._points.computeBounds();
  83106. this._points.elements.forEach(function (p) {
  83107. normals.push(0, 1.0, 0);
  83108. positions.push(p.x, 0, p.y);
  83109. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83110. });
  83111. var indices = new Array();
  83112. var res = earcut(this._epoints, this._eholes, 2);
  83113. for (var i = 0; i < res.length; i++) {
  83114. indices.push(res[i]);
  83115. }
  83116. if (depth > 0) {
  83117. var positionscount = (positions.length / 3); //get the current pointcount
  83118. this._points.elements.forEach(function (p) {
  83119. normals.push(0, -1.0, 0);
  83120. positions.push(p.x, -depth, p.y);
  83121. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83122. });
  83123. var totalCount = indices.length;
  83124. for (var i = 0; i < totalCount; i += 3) {
  83125. var i0 = indices[i + 0];
  83126. var i1 = indices[i + 1];
  83127. var i2 = indices[i + 2];
  83128. indices.push(i2 + positionscount);
  83129. indices.push(i1 + positionscount);
  83130. indices.push(i0 + positionscount);
  83131. }
  83132. //Add the sides
  83133. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83134. this._holes.forEach(function (hole) {
  83135. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83136. });
  83137. }
  83138. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83139. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83140. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83141. result.setIndices(indices);
  83142. return result;
  83143. };
  83144. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83145. var StartIndex = positions.length / 3;
  83146. var ulength = 0;
  83147. for (var i = 0; i < points.elements.length; i++) {
  83148. var p = points.elements[i];
  83149. var p1;
  83150. if ((i + 1) > points.elements.length - 1) {
  83151. p1 = points.elements[0];
  83152. }
  83153. else {
  83154. p1 = points.elements[i + 1];
  83155. }
  83156. positions.push(p.x, 0, p.y);
  83157. positions.push(p.x, -depth, p.y);
  83158. positions.push(p1.x, 0, p1.y);
  83159. positions.push(p1.x, -depth, p1.y);
  83160. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83161. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83162. var v3 = v2.subtract(v1);
  83163. var v4 = new BABYLON.Vector3(0, 1, 0);
  83164. var vn = BABYLON.Vector3.Cross(v3, v4);
  83165. vn = vn.normalize();
  83166. uvs.push(ulength / bounds.width, 0);
  83167. uvs.push(ulength / bounds.width, 1);
  83168. ulength += v3.length();
  83169. uvs.push((ulength / bounds.width), 0);
  83170. uvs.push((ulength / bounds.width), 1);
  83171. if (!flip) {
  83172. normals.push(-vn.x, -vn.y, -vn.z);
  83173. normals.push(-vn.x, -vn.y, -vn.z);
  83174. normals.push(-vn.x, -vn.y, -vn.z);
  83175. normals.push(-vn.x, -vn.y, -vn.z);
  83176. indices.push(StartIndex);
  83177. indices.push(StartIndex + 1);
  83178. indices.push(StartIndex + 2);
  83179. indices.push(StartIndex + 1);
  83180. indices.push(StartIndex + 3);
  83181. indices.push(StartIndex + 2);
  83182. }
  83183. else {
  83184. normals.push(vn.x, vn.y, vn.z);
  83185. normals.push(vn.x, vn.y, vn.z);
  83186. normals.push(vn.x, vn.y, vn.z);
  83187. normals.push(vn.x, vn.y, vn.z);
  83188. indices.push(StartIndex);
  83189. indices.push(StartIndex + 2);
  83190. indices.push(StartIndex + 1);
  83191. indices.push(StartIndex + 1);
  83192. indices.push(StartIndex + 2);
  83193. indices.push(StartIndex + 3);
  83194. }
  83195. StartIndex += 4;
  83196. }
  83197. ;
  83198. };
  83199. return PolygonMeshBuilder;
  83200. }());
  83201. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83202. })(BABYLON || (BABYLON = {}));
  83203. //# sourceMappingURL=babylon.polygonMesh.js.map
  83204. var BABYLON;
  83205. (function (BABYLON) {
  83206. // Unique ID when we import meshes from Babylon to CSG
  83207. var currentCSGMeshId = 0;
  83208. // # class Vertex
  83209. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83210. // one to provide additional features like texture coordinates and vertex
  83211. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83212. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83213. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83214. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83215. // is not used anywhere else.
  83216. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83217. var Vertex = /** @class */ (function () {
  83218. function Vertex(pos, normal, uv) {
  83219. this.pos = pos;
  83220. this.normal = normal;
  83221. this.uv = uv;
  83222. }
  83223. Vertex.prototype.clone = function () {
  83224. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83225. };
  83226. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83227. // orientation of a polygon is flipped.
  83228. Vertex.prototype.flip = function () {
  83229. this.normal = this.normal.scale(-1);
  83230. };
  83231. // Create a new vertex between this vertex and `other` by linearly
  83232. // interpolating all properties using a parameter of `t`. Subclasses should
  83233. // override this to interpolate additional properties.
  83234. Vertex.prototype.interpolate = function (other, t) {
  83235. 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));
  83236. };
  83237. return Vertex;
  83238. }());
  83239. // # class Plane
  83240. // Represents a plane in 3D space.
  83241. var Plane = /** @class */ (function () {
  83242. function Plane(normal, w) {
  83243. this.normal = normal;
  83244. this.w = w;
  83245. }
  83246. Plane.FromPoints = function (a, b, c) {
  83247. var v0 = c.subtract(a);
  83248. var v1 = b.subtract(a);
  83249. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83250. return null;
  83251. }
  83252. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83253. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83254. };
  83255. Plane.prototype.clone = function () {
  83256. return new Plane(this.normal.clone(), this.w);
  83257. };
  83258. Plane.prototype.flip = function () {
  83259. this.normal.scaleInPlace(-1);
  83260. this.w = -this.w;
  83261. };
  83262. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83263. // fragments in the appropriate lists. Coplanar polygons go into either
  83264. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83265. // respect to this plane. Polygons in front or in back of this plane go into
  83266. // either `front` or `back`.
  83267. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83268. var COPLANAR = 0;
  83269. var FRONT = 1;
  83270. var BACK = 2;
  83271. var SPANNING = 3;
  83272. // Classify each point as well as the entire polygon into one of the above
  83273. // four classes.
  83274. var polygonType = 0;
  83275. var types = [];
  83276. var i;
  83277. var t;
  83278. for (i = 0; i < polygon.vertices.length; i++) {
  83279. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83280. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83281. polygonType |= type;
  83282. types.push(type);
  83283. }
  83284. // Put the polygon in the correct list, splitting it when necessary.
  83285. switch (polygonType) {
  83286. case COPLANAR:
  83287. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83288. break;
  83289. case FRONT:
  83290. front.push(polygon);
  83291. break;
  83292. case BACK:
  83293. back.push(polygon);
  83294. break;
  83295. case SPANNING:
  83296. var f = [], b = [];
  83297. for (i = 0; i < polygon.vertices.length; i++) {
  83298. var j = (i + 1) % polygon.vertices.length;
  83299. var ti = types[i], tj = types[j];
  83300. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83301. if (ti !== BACK)
  83302. f.push(vi);
  83303. if (ti !== FRONT)
  83304. b.push(ti !== BACK ? vi.clone() : vi);
  83305. if ((ti | tj) === SPANNING) {
  83306. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83307. var v = vi.interpolate(vj, t);
  83308. f.push(v);
  83309. b.push(v.clone());
  83310. }
  83311. }
  83312. var poly;
  83313. if (f.length >= 3) {
  83314. poly = new Polygon(f, polygon.shared);
  83315. if (poly.plane)
  83316. front.push(poly);
  83317. }
  83318. if (b.length >= 3) {
  83319. poly = new Polygon(b, polygon.shared);
  83320. if (poly.plane)
  83321. back.push(poly);
  83322. }
  83323. break;
  83324. }
  83325. };
  83326. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83327. // point is on the plane.
  83328. Plane.EPSILON = 1e-5;
  83329. return Plane;
  83330. }());
  83331. // # class Polygon
  83332. // Represents a convex polygon. The vertices used to initialize a polygon must
  83333. // be coplanar and form a convex loop.
  83334. //
  83335. // Each convex polygon has a `shared` property, which is shared between all
  83336. // polygons that are clones of each other or were split from the same polygon.
  83337. // This can be used to define per-polygon properties (such as surface color).
  83338. var Polygon = /** @class */ (function () {
  83339. function Polygon(vertices, shared) {
  83340. this.vertices = vertices;
  83341. this.shared = shared;
  83342. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83343. }
  83344. Polygon.prototype.clone = function () {
  83345. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83346. return new Polygon(vertices, this.shared);
  83347. };
  83348. Polygon.prototype.flip = function () {
  83349. this.vertices.reverse().map(function (v) { v.flip(); });
  83350. this.plane.flip();
  83351. };
  83352. return Polygon;
  83353. }());
  83354. // # class Node
  83355. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83356. // by picking a polygon to split along. That polygon (and all other coplanar
  83357. // polygons) are added directly to that node and the other polygons are added to
  83358. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83359. // no distinction between internal and leaf nodes.
  83360. var Node = /** @class */ (function () {
  83361. function Node(polygons) {
  83362. this.plane = null;
  83363. this.front = null;
  83364. this.back = null;
  83365. this.polygons = new Array();
  83366. if (polygons) {
  83367. this.build(polygons);
  83368. }
  83369. }
  83370. Node.prototype.clone = function () {
  83371. var node = new Node();
  83372. node.plane = this.plane && this.plane.clone();
  83373. node.front = this.front && this.front.clone();
  83374. node.back = this.back && this.back.clone();
  83375. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83376. return node;
  83377. };
  83378. // Convert solid space to empty space and empty space to solid space.
  83379. Node.prototype.invert = function () {
  83380. for (var i = 0; i < this.polygons.length; i++) {
  83381. this.polygons[i].flip();
  83382. }
  83383. if (this.plane) {
  83384. this.plane.flip();
  83385. }
  83386. if (this.front) {
  83387. this.front.invert();
  83388. }
  83389. if (this.back) {
  83390. this.back.invert();
  83391. }
  83392. var temp = this.front;
  83393. this.front = this.back;
  83394. this.back = temp;
  83395. };
  83396. // Recursively remove all polygons in `polygons` that are inside this BSP
  83397. // tree.
  83398. Node.prototype.clipPolygons = function (polygons) {
  83399. if (!this.plane)
  83400. return polygons.slice();
  83401. var front = new Array(), back = new Array();
  83402. for (var i = 0; i < polygons.length; i++) {
  83403. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83404. }
  83405. if (this.front) {
  83406. front = this.front.clipPolygons(front);
  83407. }
  83408. if (this.back) {
  83409. back = this.back.clipPolygons(back);
  83410. }
  83411. else {
  83412. back = [];
  83413. }
  83414. return front.concat(back);
  83415. };
  83416. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83417. // `bsp`.
  83418. Node.prototype.clipTo = function (bsp) {
  83419. this.polygons = bsp.clipPolygons(this.polygons);
  83420. if (this.front)
  83421. this.front.clipTo(bsp);
  83422. if (this.back)
  83423. this.back.clipTo(bsp);
  83424. };
  83425. // Return a list of all polygons in this BSP tree.
  83426. Node.prototype.allPolygons = function () {
  83427. var polygons = this.polygons.slice();
  83428. if (this.front)
  83429. polygons = polygons.concat(this.front.allPolygons());
  83430. if (this.back)
  83431. polygons = polygons.concat(this.back.allPolygons());
  83432. return polygons;
  83433. };
  83434. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83435. // new polygons are filtered down to the bottom of the tree and become new
  83436. // nodes there. Each set of polygons is partitioned using the first polygon
  83437. // (no heuristic is used to pick a good split).
  83438. Node.prototype.build = function (polygons) {
  83439. if (!polygons.length)
  83440. return;
  83441. if (!this.plane)
  83442. this.plane = polygons[0].plane.clone();
  83443. var front = new Array(), back = new Array();
  83444. for (var i = 0; i < polygons.length; i++) {
  83445. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83446. }
  83447. if (front.length) {
  83448. if (!this.front)
  83449. this.front = new Node();
  83450. this.front.build(front);
  83451. }
  83452. if (back.length) {
  83453. if (!this.back)
  83454. this.back = new Node();
  83455. this.back.build(back);
  83456. }
  83457. };
  83458. return Node;
  83459. }());
  83460. var CSG = /** @class */ (function () {
  83461. function CSG() {
  83462. this.polygons = new Array();
  83463. }
  83464. // Convert BABYLON.Mesh to BABYLON.CSG
  83465. CSG.FromMesh = function (mesh) {
  83466. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83467. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83468. if (mesh instanceof BABYLON.Mesh) {
  83469. mesh.computeWorldMatrix(true);
  83470. matrix = mesh.getWorldMatrix();
  83471. meshPosition = mesh.position.clone();
  83472. meshRotation = mesh.rotation.clone();
  83473. if (mesh.rotationQuaternion) {
  83474. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83475. }
  83476. meshScaling = mesh.scaling.clone();
  83477. }
  83478. else {
  83479. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83480. }
  83481. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83482. var subMeshes = mesh.subMeshes;
  83483. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83484. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83485. vertices = [];
  83486. for (var j = 0; j < 3; j++) {
  83487. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83488. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83489. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83490. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83491. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83492. vertex = new Vertex(position, normal, uv);
  83493. vertices.push(vertex);
  83494. }
  83495. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83496. // To handle the case of degenerated triangle
  83497. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83498. if (polygon.plane)
  83499. polygons.push(polygon);
  83500. }
  83501. }
  83502. var csg = CSG.FromPolygons(polygons);
  83503. csg.matrix = matrix;
  83504. csg.position = meshPosition;
  83505. csg.rotation = meshRotation;
  83506. csg.scaling = meshScaling;
  83507. csg.rotationQuaternion = meshRotationQuaternion;
  83508. currentCSGMeshId++;
  83509. return csg;
  83510. };
  83511. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83512. CSG.FromPolygons = function (polygons) {
  83513. var csg = new CSG();
  83514. csg.polygons = polygons;
  83515. return csg;
  83516. };
  83517. CSG.prototype.clone = function () {
  83518. var csg = new CSG();
  83519. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83520. csg.copyTransformAttributes(this);
  83521. return csg;
  83522. };
  83523. CSG.prototype.union = function (csg) {
  83524. var a = new Node(this.clone().polygons);
  83525. var b = new Node(csg.clone().polygons);
  83526. a.clipTo(b);
  83527. b.clipTo(a);
  83528. b.invert();
  83529. b.clipTo(a);
  83530. b.invert();
  83531. a.build(b.allPolygons());
  83532. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83533. };
  83534. CSG.prototype.unionInPlace = function (csg) {
  83535. var a = new Node(this.polygons);
  83536. var b = new Node(csg.polygons);
  83537. a.clipTo(b);
  83538. b.clipTo(a);
  83539. b.invert();
  83540. b.clipTo(a);
  83541. b.invert();
  83542. a.build(b.allPolygons());
  83543. this.polygons = a.allPolygons();
  83544. };
  83545. CSG.prototype.subtract = function (csg) {
  83546. var a = new Node(this.clone().polygons);
  83547. var b = new Node(csg.clone().polygons);
  83548. a.invert();
  83549. a.clipTo(b);
  83550. b.clipTo(a);
  83551. b.invert();
  83552. b.clipTo(a);
  83553. b.invert();
  83554. a.build(b.allPolygons());
  83555. a.invert();
  83556. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83557. };
  83558. CSG.prototype.subtractInPlace = function (csg) {
  83559. var a = new Node(this.polygons);
  83560. var b = new Node(csg.polygons);
  83561. a.invert();
  83562. a.clipTo(b);
  83563. b.clipTo(a);
  83564. b.invert();
  83565. b.clipTo(a);
  83566. b.invert();
  83567. a.build(b.allPolygons());
  83568. a.invert();
  83569. this.polygons = a.allPolygons();
  83570. };
  83571. CSG.prototype.intersect = function (csg) {
  83572. var a = new Node(this.clone().polygons);
  83573. var b = new Node(csg.clone().polygons);
  83574. a.invert();
  83575. b.clipTo(a);
  83576. b.invert();
  83577. a.clipTo(b);
  83578. b.clipTo(a);
  83579. a.build(b.allPolygons());
  83580. a.invert();
  83581. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83582. };
  83583. CSG.prototype.intersectInPlace = function (csg) {
  83584. var a = new Node(this.polygons);
  83585. var b = new Node(csg.polygons);
  83586. a.invert();
  83587. b.clipTo(a);
  83588. b.invert();
  83589. a.clipTo(b);
  83590. b.clipTo(a);
  83591. a.build(b.allPolygons());
  83592. a.invert();
  83593. this.polygons = a.allPolygons();
  83594. };
  83595. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83596. // not modified.
  83597. CSG.prototype.inverse = function () {
  83598. var csg = this.clone();
  83599. csg.inverseInPlace();
  83600. return csg;
  83601. };
  83602. CSG.prototype.inverseInPlace = function () {
  83603. this.polygons.map(function (p) { p.flip(); });
  83604. };
  83605. // This is used to keep meshes transformations so they can be restored
  83606. // when we build back a Babylon Mesh
  83607. // NB : All CSG operations are performed in world coordinates
  83608. CSG.prototype.copyTransformAttributes = function (csg) {
  83609. this.matrix = csg.matrix;
  83610. this.position = csg.position;
  83611. this.rotation = csg.rotation;
  83612. this.scaling = csg.scaling;
  83613. this.rotationQuaternion = csg.rotationQuaternion;
  83614. return this;
  83615. };
  83616. // Build Raw mesh from CSG
  83617. // Coordinates here are in world space
  83618. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83619. var matrix = this.matrix.clone();
  83620. matrix.invert();
  83621. 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;
  83622. if (keepSubMeshes) {
  83623. // Sort Polygons, since subMeshes are indices range
  83624. polygons.sort(function (a, b) {
  83625. if (a.shared.meshId === b.shared.meshId) {
  83626. return a.shared.subMeshId - b.shared.subMeshId;
  83627. }
  83628. else {
  83629. return a.shared.meshId - b.shared.meshId;
  83630. }
  83631. });
  83632. }
  83633. for (var i = 0, il = polygons.length; i < il; i++) {
  83634. polygon = polygons[i];
  83635. // Building SubMeshes
  83636. if (!subMesh_dict[polygon.shared.meshId]) {
  83637. subMesh_dict[polygon.shared.meshId] = {};
  83638. }
  83639. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83640. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83641. indexStart: +Infinity,
  83642. indexEnd: -Infinity,
  83643. materialIndex: polygon.shared.materialIndex
  83644. };
  83645. }
  83646. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83647. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83648. polygonIndices[0] = 0;
  83649. polygonIndices[1] = j - 1;
  83650. polygonIndices[2] = j;
  83651. for (var k = 0; k < 3; k++) {
  83652. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83653. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83654. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83655. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83656. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83657. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83658. // Check if 2 points can be merged
  83659. if (!(typeof vertex_idx !== 'undefined' &&
  83660. normals[vertex_idx * 3] === localNormal.x &&
  83661. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83662. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83663. uvs[vertex_idx * 2] === uv.x &&
  83664. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83665. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83666. uvs.push(uv.x, uv.y);
  83667. normals.push(normal.x, normal.y, normal.z);
  83668. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83669. }
  83670. indices.push(vertex_idx);
  83671. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83672. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83673. currentIndex++;
  83674. }
  83675. }
  83676. }
  83677. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83678. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83679. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83680. mesh.setIndices(indices, null);
  83681. if (keepSubMeshes) {
  83682. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83683. var materialIndexOffset = 0, materialMaxIndex;
  83684. mesh.subMeshes = new Array();
  83685. for (var m in subMesh_dict) {
  83686. materialMaxIndex = -1;
  83687. for (var sm in subMesh_dict[m]) {
  83688. subMesh_obj = subMesh_dict[m][sm];
  83689. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83690. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83691. }
  83692. materialIndexOffset += ++materialMaxIndex;
  83693. }
  83694. }
  83695. return mesh;
  83696. };
  83697. // Build Mesh from CSG taking material and transforms into account
  83698. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83699. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83700. mesh.material = material;
  83701. mesh.position.copyFrom(this.position);
  83702. mesh.rotation.copyFrom(this.rotation);
  83703. if (this.rotationQuaternion) {
  83704. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83705. }
  83706. mesh.scaling.copyFrom(this.scaling);
  83707. mesh.computeWorldMatrix(true);
  83708. return mesh;
  83709. };
  83710. return CSG;
  83711. }());
  83712. BABYLON.CSG = CSG;
  83713. })(BABYLON || (BABYLON = {}));
  83714. //# sourceMappingURL=babylon.csg.js.map
  83715. var BABYLON;
  83716. (function (BABYLON) {
  83717. var LensFlare = /** @class */ (function () {
  83718. function LensFlare(size, position, color, imgUrl, system) {
  83719. this.size = size;
  83720. this.position = position;
  83721. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83722. this.color = color || new BABYLON.Color3(1, 1, 1);
  83723. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83724. this._system = system;
  83725. system.lensFlares.push(this);
  83726. }
  83727. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83728. return new LensFlare(size, position, color, imgUrl, system);
  83729. };
  83730. LensFlare.prototype.dispose = function () {
  83731. if (this.texture) {
  83732. this.texture.dispose();
  83733. }
  83734. // Remove from scene
  83735. var index = this._system.lensFlares.indexOf(this);
  83736. this._system.lensFlares.splice(index, 1);
  83737. };
  83738. ;
  83739. return LensFlare;
  83740. }());
  83741. BABYLON.LensFlare = LensFlare;
  83742. })(BABYLON || (BABYLON = {}));
  83743. //# sourceMappingURL=babylon.lensFlare.js.map
  83744. var BABYLON;
  83745. (function (BABYLON) {
  83746. var LensFlareSystem = /** @class */ (function () {
  83747. function LensFlareSystem(name, emitter, scene) {
  83748. this.name = name;
  83749. this.lensFlares = new Array();
  83750. this.borderLimit = 300;
  83751. this.viewportBorder = 0;
  83752. this.layerMask = 0x0FFFFFFF;
  83753. this._vertexBuffers = {};
  83754. this._isEnabled = true;
  83755. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83756. this._emitter = emitter;
  83757. this.id = name;
  83758. scene.lensFlareSystems.push(this);
  83759. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83760. var engine = scene.getEngine();
  83761. // VBO
  83762. var vertices = [];
  83763. vertices.push(1, 1);
  83764. vertices.push(-1, 1);
  83765. vertices.push(-1, -1);
  83766. vertices.push(1, -1);
  83767. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83768. // Indices
  83769. var indices = [];
  83770. indices.push(0);
  83771. indices.push(1);
  83772. indices.push(2);
  83773. indices.push(0);
  83774. indices.push(2);
  83775. indices.push(3);
  83776. this._indexBuffer = engine.createIndexBuffer(indices);
  83777. // Effects
  83778. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83779. }
  83780. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83781. get: function () {
  83782. return this._isEnabled;
  83783. },
  83784. set: function (value) {
  83785. this._isEnabled = value;
  83786. },
  83787. enumerable: true,
  83788. configurable: true
  83789. });
  83790. LensFlareSystem.prototype.getScene = function () {
  83791. return this._scene;
  83792. };
  83793. LensFlareSystem.prototype.getEmitter = function () {
  83794. return this._emitter;
  83795. };
  83796. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83797. this._emitter = newEmitter;
  83798. };
  83799. LensFlareSystem.prototype.getEmitterPosition = function () {
  83800. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83801. };
  83802. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83803. var position = this.getEmitterPosition();
  83804. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83805. this._positionX = position.x;
  83806. this._positionY = position.y;
  83807. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83808. if (this.viewportBorder > 0) {
  83809. globalViewport.x -= this.viewportBorder;
  83810. globalViewport.y -= this.viewportBorder;
  83811. globalViewport.width += this.viewportBorder * 2;
  83812. globalViewport.height += this.viewportBorder * 2;
  83813. position.x += this.viewportBorder;
  83814. position.y += this.viewportBorder;
  83815. this._positionX += this.viewportBorder;
  83816. this._positionY += this.viewportBorder;
  83817. }
  83818. if (position.z > 0) {
  83819. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83820. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83821. return true;
  83822. }
  83823. return true;
  83824. }
  83825. return false;
  83826. };
  83827. LensFlareSystem.prototype._isVisible = function () {
  83828. if (!this._isEnabled || !this._scene.activeCamera) {
  83829. return false;
  83830. }
  83831. var emitterPosition = this.getEmitterPosition();
  83832. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  83833. var distance = direction.length();
  83834. direction.normalize();
  83835. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  83836. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  83837. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  83838. };
  83839. LensFlareSystem.prototype.render = function () {
  83840. if (!this._effect.isReady() || !this._scene.activeCamera)
  83841. return false;
  83842. var engine = this._scene.getEngine();
  83843. var viewport = this._scene.activeCamera.viewport;
  83844. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  83845. // Position
  83846. if (!this.computeEffectivePosition(globalViewport)) {
  83847. return false;
  83848. }
  83849. // Visibility
  83850. if (!this._isVisible()) {
  83851. return false;
  83852. }
  83853. // Intensity
  83854. var awayX;
  83855. var awayY;
  83856. if (this._positionX < this.borderLimit + globalViewport.x) {
  83857. awayX = this.borderLimit + globalViewport.x - this._positionX;
  83858. }
  83859. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  83860. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  83861. }
  83862. else {
  83863. awayX = 0;
  83864. }
  83865. if (this._positionY < this.borderLimit + globalViewport.y) {
  83866. awayY = this.borderLimit + globalViewport.y - this._positionY;
  83867. }
  83868. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  83869. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  83870. }
  83871. else {
  83872. awayY = 0;
  83873. }
  83874. var away = (awayX > awayY) ? awayX : awayY;
  83875. away -= this.viewportBorder;
  83876. if (away > this.borderLimit) {
  83877. away = this.borderLimit;
  83878. }
  83879. var intensity = 1.0 - (away / this.borderLimit);
  83880. if (intensity < 0) {
  83881. return false;
  83882. }
  83883. if (intensity > 1.0) {
  83884. intensity = 1.0;
  83885. }
  83886. if (this.viewportBorder > 0) {
  83887. globalViewport.x += this.viewportBorder;
  83888. globalViewport.y += this.viewportBorder;
  83889. globalViewport.width -= this.viewportBorder * 2;
  83890. globalViewport.height -= this.viewportBorder * 2;
  83891. this._positionX -= this.viewportBorder;
  83892. this._positionY -= this.viewportBorder;
  83893. }
  83894. // Position
  83895. var centerX = globalViewport.x + globalViewport.width / 2;
  83896. var centerY = globalViewport.y + globalViewport.height / 2;
  83897. var distX = centerX - this._positionX;
  83898. var distY = centerY - this._positionY;
  83899. // Effects
  83900. engine.enableEffect(this._effect);
  83901. engine.setState(false);
  83902. engine.setDepthBuffer(false);
  83903. // VBOs
  83904. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  83905. // Flares
  83906. for (var index = 0; index < this.lensFlares.length; index++) {
  83907. var flare = this.lensFlares[index];
  83908. engine.setAlphaMode(flare.alphaMode);
  83909. var x = centerX - (distX * flare.position);
  83910. var y = centerY - (distY * flare.position);
  83911. var cw = flare.size;
  83912. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  83913. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  83914. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  83915. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  83916. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  83917. // Texture
  83918. this._effect.setTexture("textureSampler", flare.texture);
  83919. // Color
  83920. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  83921. // Draw order
  83922. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  83923. }
  83924. engine.setDepthBuffer(true);
  83925. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  83926. return true;
  83927. };
  83928. LensFlareSystem.prototype.dispose = function () {
  83929. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83930. if (vertexBuffer) {
  83931. vertexBuffer.dispose();
  83932. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83933. }
  83934. if (this._indexBuffer) {
  83935. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83936. this._indexBuffer = null;
  83937. }
  83938. while (this.lensFlares.length) {
  83939. this.lensFlares[0].dispose();
  83940. }
  83941. // Remove from scene
  83942. var index = this._scene.lensFlareSystems.indexOf(this);
  83943. this._scene.lensFlareSystems.splice(index, 1);
  83944. };
  83945. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  83946. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  83947. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  83948. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  83949. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  83950. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  83951. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  83952. var parsedFlare = parsedLensFlareSystem.flares[index];
  83953. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  83954. }
  83955. return lensFlareSystem;
  83956. };
  83957. LensFlareSystem.prototype.serialize = function () {
  83958. var serializationObject = {};
  83959. serializationObject.id = this.id;
  83960. serializationObject.name = this.name;
  83961. serializationObject.emitterId = this.getEmitter().id;
  83962. serializationObject.borderLimit = this.borderLimit;
  83963. serializationObject.flares = [];
  83964. for (var index = 0; index < this.lensFlares.length; index++) {
  83965. var flare = this.lensFlares[index];
  83966. serializationObject.flares.push({
  83967. size: flare.size,
  83968. position: flare.position,
  83969. color: flare.color.asArray(),
  83970. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  83971. });
  83972. }
  83973. return serializationObject;
  83974. };
  83975. return LensFlareSystem;
  83976. }());
  83977. BABYLON.LensFlareSystem = LensFlareSystem;
  83978. })(BABYLON || (BABYLON = {}));
  83979. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  83980. var BABYLON;
  83981. (function (BABYLON) {
  83982. /**
  83983. * This is a holder class for the physics joint created by the physics plugin.
  83984. * It holds a set of functions to control the underlying joint.
  83985. */
  83986. var PhysicsJoint = /** @class */ (function () {
  83987. function PhysicsJoint(type, jointData) {
  83988. this.type = type;
  83989. this.jointData = jointData;
  83990. jointData.nativeParams = jointData.nativeParams || {};
  83991. }
  83992. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  83993. get: function () {
  83994. return this._physicsJoint;
  83995. },
  83996. set: function (newJoint) {
  83997. if (this._physicsJoint) {
  83998. //remove from the wolrd
  83999. }
  84000. this._physicsJoint = newJoint;
  84001. },
  84002. enumerable: true,
  84003. configurable: true
  84004. });
  84005. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84006. set: function (physicsPlugin) {
  84007. this._physicsPlugin = physicsPlugin;
  84008. },
  84009. enumerable: true,
  84010. configurable: true
  84011. });
  84012. /**
  84013. * Execute a function that is physics-plugin specific.
  84014. * @param {Function} func the function that will be executed.
  84015. * It accepts two parameters: the physics world and the physics joint.
  84016. */
  84017. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84018. func(this._physicsPlugin.world, this._physicsJoint);
  84019. };
  84020. //TODO check if the native joints are the same
  84021. //Joint Types
  84022. PhysicsJoint.DistanceJoint = 0;
  84023. PhysicsJoint.HingeJoint = 1;
  84024. PhysicsJoint.BallAndSocketJoint = 2;
  84025. PhysicsJoint.WheelJoint = 3;
  84026. PhysicsJoint.SliderJoint = 4;
  84027. //OIMO
  84028. PhysicsJoint.PrismaticJoint = 5;
  84029. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84030. PhysicsJoint.UniversalJoint = 6;
  84031. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84032. //Cannon
  84033. //Similar to a Ball-Joint. Different in params
  84034. PhysicsJoint.PointToPointJoint = 8;
  84035. //Cannon only at the moment
  84036. PhysicsJoint.SpringJoint = 9;
  84037. PhysicsJoint.LockJoint = 10;
  84038. return PhysicsJoint;
  84039. }());
  84040. BABYLON.PhysicsJoint = PhysicsJoint;
  84041. /**
  84042. * A class representing a physics distance joint.
  84043. */
  84044. var DistanceJoint = /** @class */ (function (_super) {
  84045. __extends(DistanceJoint, _super);
  84046. function DistanceJoint(jointData) {
  84047. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84048. }
  84049. /**
  84050. * Update the predefined distance.
  84051. */
  84052. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84053. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84054. };
  84055. return DistanceJoint;
  84056. }(PhysicsJoint));
  84057. BABYLON.DistanceJoint = DistanceJoint;
  84058. var MotorEnabledJoint = /** @class */ (function (_super) {
  84059. __extends(MotorEnabledJoint, _super);
  84060. function MotorEnabledJoint(type, jointData) {
  84061. return _super.call(this, type, jointData) || this;
  84062. }
  84063. /**
  84064. * Set the motor values.
  84065. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84066. * @param {number} force the force to apply
  84067. * @param {number} maxForce max force for this motor.
  84068. */
  84069. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84070. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84071. };
  84072. /**
  84073. * Set the motor's limits.
  84074. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84075. */
  84076. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84077. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84078. };
  84079. return MotorEnabledJoint;
  84080. }(PhysicsJoint));
  84081. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84082. /**
  84083. * This class represents a single hinge physics joint
  84084. */
  84085. var HingeJoint = /** @class */ (function (_super) {
  84086. __extends(HingeJoint, _super);
  84087. function HingeJoint(jointData) {
  84088. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84089. }
  84090. /**
  84091. * Set the motor values.
  84092. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84093. * @param {number} force the force to apply
  84094. * @param {number} maxForce max force for this motor.
  84095. */
  84096. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84097. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84098. };
  84099. /**
  84100. * Set the motor's limits.
  84101. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84102. */
  84103. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84104. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84105. };
  84106. return HingeJoint;
  84107. }(MotorEnabledJoint));
  84108. BABYLON.HingeJoint = HingeJoint;
  84109. /**
  84110. * This class represents a dual hinge physics joint (same as wheel joint)
  84111. */
  84112. var Hinge2Joint = /** @class */ (function (_super) {
  84113. __extends(Hinge2Joint, _super);
  84114. function Hinge2Joint(jointData) {
  84115. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84116. }
  84117. /**
  84118. * Set the motor values.
  84119. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84120. * @param {number} force the force to apply
  84121. * @param {number} maxForce max force for this motor.
  84122. * @param {motorIndex} the motor's index, 0 or 1.
  84123. */
  84124. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84125. if (motorIndex === void 0) { motorIndex = 0; }
  84126. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84127. };
  84128. /**
  84129. * Set the motor limits.
  84130. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84131. * @param {number} upperLimit the upper limit
  84132. * @param {number} lowerLimit lower limit
  84133. * @param {motorIndex} the motor's index, 0 or 1.
  84134. */
  84135. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84136. if (motorIndex === void 0) { motorIndex = 0; }
  84137. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84138. };
  84139. return Hinge2Joint;
  84140. }(MotorEnabledJoint));
  84141. BABYLON.Hinge2Joint = Hinge2Joint;
  84142. })(BABYLON || (BABYLON = {}));
  84143. //# sourceMappingURL=babylon.physicsJoint.js.map
  84144. var BABYLON;
  84145. (function (BABYLON) {
  84146. var PhysicsImpostor = /** @class */ (function () {
  84147. function PhysicsImpostor(object, type, _options, _scene) {
  84148. if (_options === void 0) { _options = { mass: 0 }; }
  84149. var _this = this;
  84150. this.object = object;
  84151. this.type = type;
  84152. this._options = _options;
  84153. this._scene = _scene;
  84154. this._bodyUpdateRequired = false;
  84155. this._onBeforePhysicsStepCallbacks = new Array();
  84156. this._onAfterPhysicsStepCallbacks = new Array();
  84157. this._onPhysicsCollideCallbacks = [];
  84158. this._deltaPosition = BABYLON.Vector3.Zero();
  84159. this._isDisposed = false;
  84160. //temp variables for parent rotation calculations
  84161. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84162. this._tmpQuat = new BABYLON.Quaternion();
  84163. this._tmpQuat2 = new BABYLON.Quaternion();
  84164. /**
  84165. * this function is executed by the physics engine.
  84166. */
  84167. this.beforeStep = function () {
  84168. if (!_this._physicsEngine) {
  84169. return;
  84170. }
  84171. _this.object.translate(_this._deltaPosition, -1);
  84172. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84173. _this.object.computeWorldMatrix(false);
  84174. if (_this.object.parent && _this.object.rotationQuaternion) {
  84175. _this.getParentsRotation();
  84176. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84177. }
  84178. else {
  84179. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84180. }
  84181. if (!_this._options.disableBidirectionalTransformation) {
  84182. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84183. }
  84184. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84185. func(_this);
  84186. });
  84187. };
  84188. /**
  84189. * this function is executed by the physics engine.
  84190. */
  84191. this.afterStep = function () {
  84192. if (!_this._physicsEngine) {
  84193. return;
  84194. }
  84195. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84196. func(_this);
  84197. });
  84198. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84199. // object has now its world rotation. needs to be converted to local.
  84200. if (_this.object.parent && _this.object.rotationQuaternion) {
  84201. _this.getParentsRotation();
  84202. _this._tmpQuat.conjugateInPlace();
  84203. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84204. }
  84205. // take the position set and make it the absolute position of this object.
  84206. _this.object.setAbsolutePosition(_this.object.position);
  84207. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84208. _this.object.translate(_this._deltaPosition, 1);
  84209. };
  84210. /**
  84211. * Legacy collision detection event support
  84212. */
  84213. this.onCollideEvent = null;
  84214. //event and body object due to cannon's event-based architecture.
  84215. this.onCollide = function (e) {
  84216. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84217. return;
  84218. }
  84219. if (!_this._physicsEngine) {
  84220. return;
  84221. }
  84222. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84223. if (otherImpostor) {
  84224. // Legacy collision detection event support
  84225. if (_this.onCollideEvent) {
  84226. _this.onCollideEvent(_this, otherImpostor);
  84227. }
  84228. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84229. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84230. }).forEach(function (obj) {
  84231. obj.callback(_this, otherImpostor);
  84232. });
  84233. }
  84234. };
  84235. //sanity check!
  84236. if (!this.object) {
  84237. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84238. return;
  84239. }
  84240. //legacy support for old syntax.
  84241. if (!this._scene && object.getScene) {
  84242. this._scene = object.getScene();
  84243. }
  84244. if (!this._scene) {
  84245. return;
  84246. }
  84247. this._physicsEngine = this._scene.getPhysicsEngine();
  84248. if (!this._physicsEngine) {
  84249. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84250. }
  84251. else {
  84252. //set the object's quaternion, if not set
  84253. if (!this.object.rotationQuaternion) {
  84254. if (this.object.rotation) {
  84255. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84256. }
  84257. else {
  84258. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84259. }
  84260. }
  84261. //default options params
  84262. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84263. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84264. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84265. this._joints = [];
  84266. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84267. if (!this.object.parent || this._options.ignoreParent) {
  84268. this._init();
  84269. }
  84270. else if (this.object.parent.physicsImpostor) {
  84271. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84272. }
  84273. }
  84274. }
  84275. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84276. get: function () {
  84277. return this._isDisposed;
  84278. },
  84279. enumerable: true,
  84280. configurable: true
  84281. });
  84282. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84283. get: function () {
  84284. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84285. },
  84286. set: function (value) {
  84287. this.setMass(value);
  84288. },
  84289. enumerable: true,
  84290. configurable: true
  84291. });
  84292. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84293. get: function () {
  84294. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84295. },
  84296. set: function (value) {
  84297. if (!this._physicsEngine) {
  84298. return;
  84299. }
  84300. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84301. },
  84302. enumerable: true,
  84303. configurable: true
  84304. });
  84305. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84306. get: function () {
  84307. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84308. },
  84309. set: function (value) {
  84310. if (!this._physicsEngine) {
  84311. return;
  84312. }
  84313. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84314. },
  84315. enumerable: true,
  84316. configurable: true
  84317. });
  84318. /**
  84319. * This function will completly initialize this impostor.
  84320. * It will create a new body - but only if this mesh has no parent.
  84321. * If it has, this impostor will not be used other than to define the impostor
  84322. * of the child mesh.
  84323. */
  84324. PhysicsImpostor.prototype._init = function () {
  84325. if (!this._physicsEngine) {
  84326. return;
  84327. }
  84328. this._physicsEngine.removeImpostor(this);
  84329. this.physicsBody = null;
  84330. this._parent = this._parent || this._getPhysicsParent();
  84331. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84332. this._physicsEngine.addImpostor(this);
  84333. }
  84334. };
  84335. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84336. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84337. var parentMesh = this.object.parent;
  84338. return parentMesh.physicsImpostor;
  84339. }
  84340. return null;
  84341. };
  84342. /**
  84343. * Should a new body be generated.
  84344. */
  84345. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84346. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84347. };
  84348. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84349. this.forceUpdate();
  84350. };
  84351. /**
  84352. * Force a regeneration of this or the parent's impostor's body.
  84353. * Use under cautious - This will remove all joints already implemented.
  84354. */
  84355. PhysicsImpostor.prototype.forceUpdate = function () {
  84356. this._init();
  84357. if (this.parent && !this._options.ignoreParent) {
  84358. this.parent.forceUpdate();
  84359. }
  84360. };
  84361. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84362. /*public get mesh(): AbstractMesh {
  84363. return this._mesh;
  84364. }*/
  84365. /**
  84366. * Gets the body that holds this impostor. Either its own, or its parent.
  84367. */
  84368. get: function () {
  84369. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84370. },
  84371. /**
  84372. * Set the physics body. Used mainly by the physics engine/plugin
  84373. */
  84374. set: function (physicsBody) {
  84375. if (this._physicsBody && this._physicsEngine) {
  84376. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84377. }
  84378. this._physicsBody = physicsBody;
  84379. this.resetUpdateFlags();
  84380. },
  84381. enumerable: true,
  84382. configurable: true
  84383. });
  84384. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84385. get: function () {
  84386. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84387. },
  84388. set: function (value) {
  84389. this._parent = value;
  84390. },
  84391. enumerable: true,
  84392. configurable: true
  84393. });
  84394. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84395. this._bodyUpdateRequired = false;
  84396. };
  84397. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84398. if (this.object.getBoundingInfo) {
  84399. var q = this.object.rotationQuaternion;
  84400. //reset rotation
  84401. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84402. //calculate the world matrix with no rotation
  84403. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84404. var boundingInfo = this.object.getBoundingInfo();
  84405. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84406. //bring back the rotation
  84407. this.object.rotationQuaternion = q;
  84408. //calculate the world matrix with the new rotation
  84409. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84410. return size;
  84411. }
  84412. else {
  84413. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84414. }
  84415. };
  84416. PhysicsImpostor.prototype.getObjectCenter = function () {
  84417. if (this.object.getBoundingInfo) {
  84418. var boundingInfo = this.object.getBoundingInfo();
  84419. return boundingInfo.boundingBox.centerWorld;
  84420. }
  84421. else {
  84422. return this.object.position;
  84423. }
  84424. };
  84425. /**
  84426. * Get a specific parametes from the options parameter.
  84427. */
  84428. PhysicsImpostor.prototype.getParam = function (paramName) {
  84429. return this._options[paramName];
  84430. };
  84431. /**
  84432. * Sets a specific parameter in the options given to the physics plugin
  84433. */
  84434. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84435. this._options[paramName] = value;
  84436. this._bodyUpdateRequired = true;
  84437. };
  84438. /**
  84439. * Specifically change the body's mass option. Won't recreate the physics body object
  84440. */
  84441. PhysicsImpostor.prototype.setMass = function (mass) {
  84442. if (this.getParam("mass") !== mass) {
  84443. this.setParam("mass", mass);
  84444. }
  84445. if (this._physicsEngine) {
  84446. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84447. }
  84448. };
  84449. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84450. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84451. };
  84452. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84453. if (this._physicsEngine) {
  84454. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84455. }
  84456. };
  84457. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84458. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84459. };
  84460. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84461. if (this._physicsEngine) {
  84462. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84463. }
  84464. };
  84465. /**
  84466. * Execute a function with the physics plugin native code.
  84467. * Provide a function the will have two variables - the world object and the physics body object.
  84468. */
  84469. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84470. if (this._physicsEngine) {
  84471. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84472. }
  84473. };
  84474. /**
  84475. * Register a function that will be executed before the physics world is stepping forward.
  84476. */
  84477. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84478. this._onBeforePhysicsStepCallbacks.push(func);
  84479. };
  84480. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84481. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84482. if (index > -1) {
  84483. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84484. }
  84485. else {
  84486. BABYLON.Tools.Warn("Function to remove was not found");
  84487. }
  84488. };
  84489. /**
  84490. * Register a function that will be executed after the physics step
  84491. */
  84492. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84493. this._onAfterPhysicsStepCallbacks.push(func);
  84494. };
  84495. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84496. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84497. if (index > -1) {
  84498. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84499. }
  84500. else {
  84501. BABYLON.Tools.Warn("Function to remove was not found");
  84502. }
  84503. };
  84504. /**
  84505. * register a function that will be executed when this impostor collides against a different body.
  84506. */
  84507. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84508. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84509. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84510. };
  84511. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84512. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84513. var index = -1;
  84514. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84515. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84516. // chcek the arrays match
  84517. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84518. return collidedAgainstList.indexOf(impostor) > -1;
  84519. });
  84520. if (sameList) {
  84521. index = idx;
  84522. }
  84523. return sameList;
  84524. }
  84525. return false;
  84526. });
  84527. if (found) {
  84528. this._onPhysicsCollideCallbacks.splice(index, 1);
  84529. }
  84530. else {
  84531. BABYLON.Tools.Warn("Function to remove was not found");
  84532. }
  84533. };
  84534. PhysicsImpostor.prototype.getParentsRotation = function () {
  84535. var parent = this.object.parent;
  84536. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84537. while (parent) {
  84538. if (parent.rotationQuaternion) {
  84539. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84540. }
  84541. else {
  84542. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84543. }
  84544. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84545. parent = parent.parent;
  84546. }
  84547. return this._tmpQuat;
  84548. };
  84549. /**
  84550. * Apply a force
  84551. */
  84552. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84553. if (this._physicsEngine) {
  84554. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84555. }
  84556. return this;
  84557. };
  84558. /**
  84559. * Apply an impulse
  84560. */
  84561. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84562. if (this._physicsEngine) {
  84563. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84564. }
  84565. return this;
  84566. };
  84567. /**
  84568. * A help function to create a joint.
  84569. */
  84570. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84571. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84572. this.addJoint(otherImpostor, joint);
  84573. return this;
  84574. };
  84575. /**
  84576. * Add a joint to this impostor with a different impostor.
  84577. */
  84578. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84579. this._joints.push({
  84580. otherImpostor: otherImpostor,
  84581. joint: joint
  84582. });
  84583. if (this._physicsEngine) {
  84584. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84585. }
  84586. return this;
  84587. };
  84588. /**
  84589. * Will keep this body still, in a sleep mode.
  84590. */
  84591. PhysicsImpostor.prototype.sleep = function () {
  84592. if (this._physicsEngine) {
  84593. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84594. }
  84595. return this;
  84596. };
  84597. /**
  84598. * Wake the body up.
  84599. */
  84600. PhysicsImpostor.prototype.wakeUp = function () {
  84601. if (this._physicsEngine) {
  84602. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84603. }
  84604. return this;
  84605. };
  84606. PhysicsImpostor.prototype.clone = function (newObject) {
  84607. if (!newObject)
  84608. return null;
  84609. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84610. };
  84611. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84612. var _this = this;
  84613. //no dispose if no physics engine is available.
  84614. if (!this._physicsEngine) {
  84615. return;
  84616. }
  84617. this._joints.forEach(function (j) {
  84618. if (_this._physicsEngine) {
  84619. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84620. }
  84621. });
  84622. //dispose the physics body
  84623. this._physicsEngine.removeImpostor(this);
  84624. if (this.parent) {
  84625. this.parent.forceUpdate();
  84626. }
  84627. else {
  84628. /*this._object.getChildMeshes().forEach(function(mesh) {
  84629. if (mesh.physicsImpostor) {
  84630. if (disposeChildren) {
  84631. mesh.physicsImpostor.dispose();
  84632. mesh.physicsImpostor = null;
  84633. }
  84634. }
  84635. })*/
  84636. }
  84637. this._isDisposed = true;
  84638. };
  84639. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84640. this._deltaPosition.copyFrom(position);
  84641. };
  84642. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84643. if (!this._deltaRotation) {
  84644. this._deltaRotation = new BABYLON.Quaternion();
  84645. }
  84646. this._deltaRotation.copyFrom(rotation);
  84647. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84648. };
  84649. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84650. if (this._physicsEngine) {
  84651. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84652. }
  84653. return this;
  84654. };
  84655. PhysicsImpostor.prototype.getRadius = function () {
  84656. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84657. };
  84658. /**
  84659. * Sync a bone with this impostor
  84660. * @param bone The bone to sync to the impostor.
  84661. * @param boneMesh The mesh that the bone is influencing.
  84662. * @param jointPivot The pivot of the joint / bone in local space.
  84663. * @param distToJoint Optional distance from the impostor to the joint.
  84664. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84665. */
  84666. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84667. var tempVec = PhysicsImpostor._tmpVecs[0];
  84668. var mesh = this.object;
  84669. if (mesh.rotationQuaternion) {
  84670. if (adjustRotation) {
  84671. var tempQuat = PhysicsImpostor._tmpQuat;
  84672. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84673. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84674. }
  84675. else {
  84676. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84677. }
  84678. }
  84679. tempVec.x = 0;
  84680. tempVec.y = 0;
  84681. tempVec.z = 0;
  84682. if (jointPivot) {
  84683. tempVec.x = jointPivot.x;
  84684. tempVec.y = jointPivot.y;
  84685. tempVec.z = jointPivot.z;
  84686. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84687. if (distToJoint === undefined || distToJoint === null) {
  84688. distToJoint = jointPivot.length();
  84689. }
  84690. tempVec.x *= distToJoint;
  84691. tempVec.y *= distToJoint;
  84692. tempVec.z *= distToJoint;
  84693. }
  84694. if (bone.getParent()) {
  84695. tempVec.addInPlace(mesh.getAbsolutePosition());
  84696. bone.setAbsolutePosition(tempVec, boneMesh);
  84697. }
  84698. else {
  84699. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84700. boneMesh.position.x -= tempVec.x;
  84701. boneMesh.position.y -= tempVec.y;
  84702. boneMesh.position.z -= tempVec.z;
  84703. }
  84704. };
  84705. /**
  84706. * Sync impostor to a bone
  84707. * @param bone The bone that the impostor will be synced to.
  84708. * @param boneMesh The mesh that the bone is influencing.
  84709. * @param jointPivot The pivot of the joint / bone in local space.
  84710. * @param distToJoint Optional distance from the impostor to the joint.
  84711. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84712. * @param boneAxis Optional vector3 axis the bone is aligned with
  84713. */
  84714. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84715. var mesh = this.object;
  84716. if (mesh.rotationQuaternion) {
  84717. if (adjustRotation) {
  84718. var tempQuat = PhysicsImpostor._tmpQuat;
  84719. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84720. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84721. }
  84722. else {
  84723. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84724. }
  84725. }
  84726. var pos = PhysicsImpostor._tmpVecs[0];
  84727. var boneDir = PhysicsImpostor._tmpVecs[1];
  84728. if (!boneAxis) {
  84729. boneAxis = PhysicsImpostor._tmpVecs[2];
  84730. boneAxis.x = 0;
  84731. boneAxis.y = 1;
  84732. boneAxis.z = 0;
  84733. }
  84734. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84735. bone.getAbsolutePositionToRef(boneMesh, pos);
  84736. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84737. distToJoint = jointPivot.length();
  84738. }
  84739. if (distToJoint !== undefined && distToJoint !== null) {
  84740. pos.x += boneDir.x * distToJoint;
  84741. pos.y += boneDir.y * distToJoint;
  84742. pos.z += boneDir.z * distToJoint;
  84743. }
  84744. mesh.setAbsolutePosition(pos);
  84745. };
  84746. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84747. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84748. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84749. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84750. //Impostor types
  84751. PhysicsImpostor.NoImpostor = 0;
  84752. PhysicsImpostor.SphereImpostor = 1;
  84753. PhysicsImpostor.BoxImpostor = 2;
  84754. PhysicsImpostor.PlaneImpostor = 3;
  84755. PhysicsImpostor.MeshImpostor = 4;
  84756. PhysicsImpostor.CylinderImpostor = 7;
  84757. PhysicsImpostor.ParticleImpostor = 8;
  84758. PhysicsImpostor.HeightmapImpostor = 9;
  84759. return PhysicsImpostor;
  84760. }());
  84761. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84762. })(BABYLON || (BABYLON = {}));
  84763. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84764. var BABYLON;
  84765. (function (BABYLON) {
  84766. var PhysicsEngine = /** @class */ (function () {
  84767. function PhysicsEngine(gravity, _physicsPlugin) {
  84768. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84769. this._physicsPlugin = _physicsPlugin;
  84770. //new methods and parameters
  84771. this._impostors = [];
  84772. this._joints = [];
  84773. if (!this._physicsPlugin.isSupported()) {
  84774. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84775. + "Please make sure it is included.");
  84776. }
  84777. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84778. this.setGravity(gravity);
  84779. this.setTimeStep();
  84780. }
  84781. PhysicsEngine.prototype.setGravity = function (gravity) {
  84782. this.gravity = gravity;
  84783. this._physicsPlugin.setGravity(this.gravity);
  84784. };
  84785. /**
  84786. * Set the time step of the physics engine.
  84787. * default is 1/60.
  84788. * To slow it down, enter 1/600 for example.
  84789. * To speed it up, 1/30
  84790. * @param {number} newTimeStep the new timestep to apply to this world.
  84791. */
  84792. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84793. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84794. this._physicsPlugin.setTimeStep(newTimeStep);
  84795. };
  84796. /**
  84797. * Get the time step of the physics engine.
  84798. */
  84799. PhysicsEngine.prototype.getTimeStep = function () {
  84800. return this._physicsPlugin.getTimeStep();
  84801. };
  84802. PhysicsEngine.prototype.dispose = function () {
  84803. this._impostors.forEach(function (impostor) {
  84804. impostor.dispose();
  84805. });
  84806. this._physicsPlugin.dispose();
  84807. };
  84808. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84809. return this._physicsPlugin.name;
  84810. };
  84811. /**
  84812. * Adding a new impostor for the impostor tracking.
  84813. * This will be done by the impostor itself.
  84814. * @param {PhysicsImpostor} impostor the impostor to add
  84815. */
  84816. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84817. impostor.uniqueId = this._impostors.push(impostor);
  84818. //if no parent, generate the body
  84819. if (!impostor.parent) {
  84820. this._physicsPlugin.generatePhysicsBody(impostor);
  84821. }
  84822. };
  84823. /**
  84824. * Remove an impostor from the engine.
  84825. * This impostor and its mesh will not longer be updated by the physics engine.
  84826. * @param {PhysicsImpostor} impostor the impostor to remove
  84827. */
  84828. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  84829. var index = this._impostors.indexOf(impostor);
  84830. if (index > -1) {
  84831. var removed = this._impostors.splice(index, 1);
  84832. //Is it needed?
  84833. if (removed.length) {
  84834. //this will also remove it from the world.
  84835. removed[0].physicsBody = null;
  84836. }
  84837. }
  84838. };
  84839. /**
  84840. * Add a joint to the physics engine
  84841. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  84842. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  84843. * @param {PhysicsJoint} the joint that will connect both impostors.
  84844. */
  84845. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  84846. var impostorJoint = {
  84847. mainImpostor: mainImpostor,
  84848. connectedImpostor: connectedImpostor,
  84849. joint: joint
  84850. };
  84851. joint.physicsPlugin = this._physicsPlugin;
  84852. this._joints.push(impostorJoint);
  84853. this._physicsPlugin.generateJoint(impostorJoint);
  84854. };
  84855. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  84856. var matchingJoints = this._joints.filter(function (impostorJoint) {
  84857. return (impostorJoint.connectedImpostor === connectedImpostor
  84858. && impostorJoint.joint === joint
  84859. && impostorJoint.mainImpostor === mainImpostor);
  84860. });
  84861. if (matchingJoints.length) {
  84862. this._physicsPlugin.removeJoint(matchingJoints[0]);
  84863. //TODO remove it from the list as well
  84864. }
  84865. };
  84866. /**
  84867. * Called by the scene. no need to call it.
  84868. */
  84869. PhysicsEngine.prototype._step = function (delta) {
  84870. var _this = this;
  84871. //check if any mesh has no body / requires an update
  84872. this._impostors.forEach(function (impostor) {
  84873. if (impostor.isBodyInitRequired()) {
  84874. _this._physicsPlugin.generatePhysicsBody(impostor);
  84875. }
  84876. });
  84877. if (delta > 0.1) {
  84878. delta = 0.1;
  84879. }
  84880. else if (delta <= 0) {
  84881. delta = 1.0 / 60.0;
  84882. }
  84883. this._physicsPlugin.executeStep(delta, this._impostors);
  84884. };
  84885. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  84886. return this._physicsPlugin;
  84887. };
  84888. PhysicsEngine.prototype.getImpostors = function () {
  84889. return this._impostors;
  84890. };
  84891. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  84892. for (var i = 0; i < this._impostors.length; ++i) {
  84893. if (this._impostors[i].object === object) {
  84894. return this._impostors[i];
  84895. }
  84896. }
  84897. return null;
  84898. };
  84899. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  84900. for (var i = 0; i < this._impostors.length; ++i) {
  84901. if (this._impostors[i].physicsBody === body) {
  84902. return this._impostors[i];
  84903. }
  84904. }
  84905. return null;
  84906. };
  84907. // Statics
  84908. PhysicsEngine.Epsilon = 0.001;
  84909. return PhysicsEngine;
  84910. }());
  84911. BABYLON.PhysicsEngine = PhysicsEngine;
  84912. })(BABYLON || (BABYLON = {}));
  84913. //# sourceMappingURL=babylon.physicsEngine.js.map
  84914. var BABYLON;
  84915. (function (BABYLON) {
  84916. var PhysicsHelper = /** @class */ (function () {
  84917. function PhysicsHelper(scene) {
  84918. this._scene = scene;
  84919. this._physicsEngine = this._scene.getPhysicsEngine();
  84920. if (!this._physicsEngine) {
  84921. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  84922. }
  84923. }
  84924. /**
  84925. * @param {Vector3} origin the origin of the explosion
  84926. * @param {number} radius the explosion radius
  84927. * @param {number} strength the explosion strength
  84928. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84929. */
  84930. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  84931. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84932. if (!this._physicsEngine) {
  84933. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  84934. return null;
  84935. }
  84936. var impostors = this._physicsEngine.getImpostors();
  84937. if (impostors.length === 0) {
  84938. return null;
  84939. }
  84940. var event = new PhysicsRadialExplosionEvent(this._scene);
  84941. impostors.forEach(function (impostor) {
  84942. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84943. if (!impostorForceAndContactPoint) {
  84944. return;
  84945. }
  84946. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84947. });
  84948. event.dispose(false);
  84949. return event;
  84950. };
  84951. /**
  84952. * @param {Vector3} origin the origin of the explosion
  84953. * @param {number} radius the explosion radius
  84954. * @param {number} strength the explosion strength
  84955. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84956. */
  84957. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  84958. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84959. if (!this._physicsEngine) {
  84960. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84961. return null;
  84962. }
  84963. var impostors = this._physicsEngine.getImpostors();
  84964. if (impostors.length === 0) {
  84965. return null;
  84966. }
  84967. var event = new PhysicsRadialExplosionEvent(this._scene);
  84968. impostors.forEach(function (impostor) {
  84969. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  84970. if (!impostorForceAndContactPoint) {
  84971. return;
  84972. }
  84973. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  84974. });
  84975. event.dispose(false);
  84976. return event;
  84977. };
  84978. /**
  84979. * @param {Vector3} origin the origin of the explosion
  84980. * @param {number} radius the explosion radius
  84981. * @param {number} strength the explosion strength
  84982. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  84983. */
  84984. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  84985. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  84986. if (!this._physicsEngine) {
  84987. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  84988. return null;
  84989. }
  84990. var impostors = this._physicsEngine.getImpostors();
  84991. if (impostors.length === 0) {
  84992. return null;
  84993. }
  84994. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  84995. event.dispose(false);
  84996. return event;
  84997. };
  84998. /**
  84999. * @param {Vector3} origin the origin of the updraft
  85000. * @param {number} radius the radius of the updraft
  85001. * @param {number} strength the strength of the updraft
  85002. * @param {number} height the height of the updraft
  85003. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85004. */
  85005. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85006. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85007. if (!this._physicsEngine) {
  85008. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85009. return null;
  85010. }
  85011. if (this._physicsEngine.getImpostors().length === 0) {
  85012. return null;
  85013. }
  85014. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85015. event.dispose(false);
  85016. return event;
  85017. };
  85018. /**
  85019. * @param {Vector3} origin the of the vortex
  85020. * @param {number} radius the radius of the vortex
  85021. * @param {number} strength the strength of the vortex
  85022. * @param {number} height the height of the vortex
  85023. */
  85024. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85025. if (!this._physicsEngine) {
  85026. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85027. return null;
  85028. }
  85029. if (this._physicsEngine.getImpostors().length === 0) {
  85030. return null;
  85031. }
  85032. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85033. event.dispose(false);
  85034. return event;
  85035. };
  85036. return PhysicsHelper;
  85037. }());
  85038. BABYLON.PhysicsHelper = PhysicsHelper;
  85039. /***** Radial explosion *****/
  85040. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85041. function PhysicsRadialExplosionEvent(scene) {
  85042. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85043. this._rays = [];
  85044. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85045. this._scene = scene;
  85046. }
  85047. /**
  85048. * Returns the data related to the radial explosion event (sphere & rays).
  85049. * @returns {PhysicsRadialExplosionEventData}
  85050. */
  85051. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85052. this._dataFetched = true;
  85053. return {
  85054. sphere: this._sphere,
  85055. rays: this._rays,
  85056. };
  85057. };
  85058. /**
  85059. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85060. * @param impostor
  85061. * @param {Vector3} origin the origin of the explosion
  85062. * @param {number} radius the explosion radius
  85063. * @param {number} strength the explosion strength
  85064. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85065. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85066. */
  85067. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85068. if (impostor.mass === 0) {
  85069. return null;
  85070. }
  85071. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85072. return null;
  85073. }
  85074. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85075. return null;
  85076. }
  85077. var impostorObjectCenter = impostor.getObjectCenter();
  85078. var direction = impostorObjectCenter.subtract(origin);
  85079. var ray = new BABYLON.Ray(origin, direction, radius);
  85080. this._rays.push(ray);
  85081. var hit = ray.intersectsMesh(impostor.object);
  85082. var contactPoint = hit.pickedPoint;
  85083. if (!contactPoint) {
  85084. return null;
  85085. }
  85086. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85087. if (distanceFromOrigin > radius) {
  85088. return null;
  85089. }
  85090. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85091. ? strength
  85092. : strength * (1 - (distanceFromOrigin / radius));
  85093. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85094. return { force: force, contactPoint: contactPoint };
  85095. };
  85096. /**
  85097. * Disposes the sphere.
  85098. * @param {bolean} force
  85099. */
  85100. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85101. var _this = this;
  85102. if (force === void 0) { force = true; }
  85103. if (force) {
  85104. this._sphere.dispose();
  85105. }
  85106. else {
  85107. setTimeout(function () {
  85108. if (!_this._dataFetched) {
  85109. _this._sphere.dispose();
  85110. }
  85111. }, 0);
  85112. }
  85113. };
  85114. /*** Helpers ***/
  85115. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85116. if (!this._sphere) {
  85117. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85118. this._sphere.isVisible = false;
  85119. }
  85120. };
  85121. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85122. var impostorObject = impostor.object;
  85123. this._prepareSphere();
  85124. this._sphere.position = origin;
  85125. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85126. this._sphere._updateBoundingInfo();
  85127. this._sphere.computeWorldMatrix(true);
  85128. return this._sphere.intersectsMesh(impostorObject, true);
  85129. };
  85130. return PhysicsRadialExplosionEvent;
  85131. }());
  85132. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85133. /***** Gravitational Field *****/
  85134. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85135. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85136. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85137. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85138. this._physicsHelper = physicsHelper;
  85139. this._scene = scene;
  85140. this._origin = origin;
  85141. this._radius = radius;
  85142. this._strength = strength;
  85143. this._falloff = falloff;
  85144. this._tickCallback = this._tick.bind(this);
  85145. }
  85146. /**
  85147. * Returns the data related to the gravitational field event (sphere).
  85148. * @returns {PhysicsGravitationalFieldEventData}
  85149. */
  85150. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85151. this._dataFetched = true;
  85152. return {
  85153. sphere: this._sphere,
  85154. };
  85155. };
  85156. /**
  85157. * Enables the gravitational field.
  85158. */
  85159. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85160. this._tickCallback.call(this);
  85161. this._scene.registerBeforeRender(this._tickCallback);
  85162. };
  85163. /**
  85164. * Disables the gravitational field.
  85165. */
  85166. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85167. this._scene.unregisterBeforeRender(this._tickCallback);
  85168. };
  85169. /**
  85170. * Disposes the sphere.
  85171. * @param {bolean} force
  85172. */
  85173. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85174. var _this = this;
  85175. if (force === void 0) { force = true; }
  85176. if (force) {
  85177. this._sphere.dispose();
  85178. }
  85179. else {
  85180. setTimeout(function () {
  85181. if (!_this._dataFetched) {
  85182. _this._sphere.dispose();
  85183. }
  85184. }, 0);
  85185. }
  85186. };
  85187. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85188. // Since the params won't change, we fetch the event only once
  85189. if (this._sphere) {
  85190. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85191. }
  85192. else {
  85193. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85194. if (radialExplosionEvent) {
  85195. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85196. }
  85197. }
  85198. };
  85199. return PhysicsGravitationalFieldEvent;
  85200. }());
  85201. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85202. /***** Updraft *****/
  85203. var PhysicsUpdraftEvent = /** @class */ (function () {
  85204. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85205. this._scene = _scene;
  85206. this._origin = _origin;
  85207. this._radius = _radius;
  85208. this._strength = _strength;
  85209. this._height = _height;
  85210. this._updraftMode = _updraftMode;
  85211. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85212. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85213. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85214. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85215. this._physicsEngine = this._scene.getPhysicsEngine();
  85216. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85217. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85218. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85219. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85220. }
  85221. this._tickCallback = this._tick.bind(this);
  85222. }
  85223. /**
  85224. * Returns the data related to the updraft event (cylinder).
  85225. * @returns {PhysicsUpdraftEventData}
  85226. */
  85227. PhysicsUpdraftEvent.prototype.getData = function () {
  85228. this._dataFetched = true;
  85229. return {
  85230. cylinder: this._cylinder,
  85231. };
  85232. };
  85233. /**
  85234. * Enables the updraft.
  85235. */
  85236. PhysicsUpdraftEvent.prototype.enable = function () {
  85237. this._tickCallback.call(this);
  85238. this._scene.registerBeforeRender(this._tickCallback);
  85239. };
  85240. /**
  85241. * Disables the cortex.
  85242. */
  85243. PhysicsUpdraftEvent.prototype.disable = function () {
  85244. this._scene.unregisterBeforeRender(this._tickCallback);
  85245. };
  85246. /**
  85247. * Disposes the sphere.
  85248. * @param {bolean} force
  85249. */
  85250. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85251. var _this = this;
  85252. if (force === void 0) { force = true; }
  85253. if (force) {
  85254. this._cylinder.dispose();
  85255. }
  85256. else {
  85257. setTimeout(function () {
  85258. if (!_this._dataFetched) {
  85259. _this._cylinder.dispose();
  85260. }
  85261. }, 0);
  85262. }
  85263. };
  85264. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85265. if (impostor.mass === 0) {
  85266. return null;
  85267. }
  85268. if (!this._intersectsWithCylinder(impostor)) {
  85269. return null;
  85270. }
  85271. var impostorObjectCenter = impostor.getObjectCenter();
  85272. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85273. var direction = this._originDirection;
  85274. }
  85275. else {
  85276. var direction = impostorObjectCenter.subtract(this._originTop);
  85277. }
  85278. var multiplier = this._strength * -1;
  85279. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85280. return { force: force, contactPoint: impostorObjectCenter };
  85281. };
  85282. PhysicsUpdraftEvent.prototype._tick = function () {
  85283. var _this = this;
  85284. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85285. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85286. if (!impostorForceAndContactPoint) {
  85287. return;
  85288. }
  85289. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85290. });
  85291. };
  85292. /*** Helpers ***/
  85293. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85294. if (!this._cylinder) {
  85295. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85296. height: this._height,
  85297. diameter: this._radius * 2,
  85298. }, this._scene);
  85299. this._cylinder.isVisible = false;
  85300. }
  85301. };
  85302. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85303. var impostorObject = impostor.object;
  85304. this._prepareCylinder();
  85305. this._cylinder.position = this._cylinderPosition;
  85306. return this._cylinder.intersectsMesh(impostorObject, true);
  85307. };
  85308. return PhysicsUpdraftEvent;
  85309. }());
  85310. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85311. /***** Vortex *****/
  85312. var PhysicsVortexEvent = /** @class */ (function () {
  85313. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85314. this._scene = _scene;
  85315. this._origin = _origin;
  85316. this._radius = _radius;
  85317. this._strength = _strength;
  85318. this._height = _height;
  85319. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85320. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85321. this._updraftMultiplier = 0.02;
  85322. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85323. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85324. this._physicsEngine = this._scene.getPhysicsEngine();
  85325. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85326. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85327. this._tickCallback = this._tick.bind(this);
  85328. }
  85329. /**
  85330. * Returns the data related to the vortex event (cylinder).
  85331. * @returns {PhysicsVortexEventData}
  85332. */
  85333. PhysicsVortexEvent.prototype.getData = function () {
  85334. this._dataFetched = true;
  85335. return {
  85336. cylinder: this._cylinder,
  85337. };
  85338. };
  85339. /**
  85340. * Enables the vortex.
  85341. */
  85342. PhysicsVortexEvent.prototype.enable = function () {
  85343. this._tickCallback.call(this);
  85344. this._scene.registerBeforeRender(this._tickCallback);
  85345. };
  85346. /**
  85347. * Disables the cortex.
  85348. */
  85349. PhysicsVortexEvent.prototype.disable = function () {
  85350. this._scene.unregisterBeforeRender(this._tickCallback);
  85351. };
  85352. /**
  85353. * Disposes the sphere.
  85354. * @param {bolean} force
  85355. */
  85356. PhysicsVortexEvent.prototype.dispose = function (force) {
  85357. var _this = this;
  85358. if (force === void 0) { force = true; }
  85359. if (force) {
  85360. this._cylinder.dispose();
  85361. }
  85362. else {
  85363. setTimeout(function () {
  85364. if (!_this._dataFetched) {
  85365. _this._cylinder.dispose();
  85366. }
  85367. }, 0);
  85368. }
  85369. };
  85370. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85371. if (impostor.mass === 0) {
  85372. return null;
  85373. }
  85374. if (!this._intersectsWithCylinder(impostor)) {
  85375. return null;
  85376. }
  85377. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85378. return null;
  85379. }
  85380. var impostorObjectCenter = impostor.getObjectCenter();
  85381. 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)
  85382. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85383. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85384. var hit = ray.intersectsMesh(impostor.object);
  85385. var contactPoint = hit.pickedPoint;
  85386. if (!contactPoint) {
  85387. return null;
  85388. }
  85389. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85390. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85391. var directionToOrigin = contactPoint.normalize();
  85392. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85393. directionToOrigin = directionToOrigin.negate();
  85394. }
  85395. // TODO: find a more physically based solution
  85396. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85397. var forceX = directionToOrigin.x * this._strength / 8;
  85398. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85399. var forceZ = directionToOrigin.z * this._strength / 8;
  85400. }
  85401. else {
  85402. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85403. var forceY = this._originTop.y * this._updraftMultiplier;
  85404. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85405. }
  85406. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85407. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85408. return { force: force, contactPoint: impostorObjectCenter };
  85409. };
  85410. PhysicsVortexEvent.prototype._tick = function () {
  85411. var _this = this;
  85412. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85413. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85414. if (!impostorForceAndContactPoint) {
  85415. return;
  85416. }
  85417. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85418. });
  85419. };
  85420. /*** Helpers ***/
  85421. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85422. if (!this._cylinder) {
  85423. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85424. height: this._height,
  85425. diameter: this._radius * 2,
  85426. }, this._scene);
  85427. this._cylinder.isVisible = false;
  85428. }
  85429. };
  85430. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85431. var impostorObject = impostor.object;
  85432. this._prepareCylinder();
  85433. this._cylinder.position = this._cylinderPosition;
  85434. return this._cylinder.intersectsMesh(impostorObject, true);
  85435. };
  85436. return PhysicsVortexEvent;
  85437. }());
  85438. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85439. /***** Enums *****/
  85440. /**
  85441. * The strenght of the force in correspondence to the distance of the affected object
  85442. */
  85443. var PhysicsRadialImpulseFalloff;
  85444. (function (PhysicsRadialImpulseFalloff) {
  85445. /** Defines that impulse is constant in strength across it's whole radius */
  85446. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85447. /** DEfines that impulse gets weaker if it's further from the origin */
  85448. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85449. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85450. /**
  85451. * The strenght of the force in correspondence to the distance of the affected object
  85452. */
  85453. var PhysicsUpdraftMode;
  85454. (function (PhysicsUpdraftMode) {
  85455. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85456. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85457. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85458. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85459. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85460. })(BABYLON || (BABYLON = {}));
  85461. //# sourceMappingURL=babylon.physicsHelper.js.map
  85462. var BABYLON;
  85463. (function (BABYLON) {
  85464. var CannonJSPlugin = /** @class */ (function () {
  85465. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85466. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85467. if (iterations === void 0) { iterations = 10; }
  85468. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85469. this.name = "CannonJSPlugin";
  85470. this._physicsMaterials = new Array();
  85471. this._fixedTimeStep = 1 / 60;
  85472. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85473. this.BJSCANNON = CANNON;
  85474. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85475. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85476. this._tmpPosition = BABYLON.Vector3.Zero();
  85477. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85478. this._tmpUnityRotation = new BABYLON.Quaternion();
  85479. if (!this.isSupported()) {
  85480. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85481. return;
  85482. }
  85483. this._extendNamespace();
  85484. this.world = new this.BJSCANNON.World();
  85485. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85486. this.world.solver.iterations = iterations;
  85487. }
  85488. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85489. this.world.gravity.copy(gravity);
  85490. };
  85491. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85492. this._fixedTimeStep = timeStep;
  85493. };
  85494. CannonJSPlugin.prototype.getTimeStep = function () {
  85495. return this._fixedTimeStep;
  85496. };
  85497. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85498. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85499. };
  85500. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85501. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85502. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85503. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85504. };
  85505. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85506. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85507. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85508. impostor.physicsBody.applyForce(impulse, worldPoint);
  85509. };
  85510. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85511. //parent-child relationship. Does this impostor has a parent impostor?
  85512. if (impostor.parent) {
  85513. if (impostor.physicsBody) {
  85514. this.removePhysicsBody(impostor);
  85515. //TODO is that needed?
  85516. impostor.forceUpdate();
  85517. }
  85518. return;
  85519. }
  85520. //should a new body be created for this impostor?
  85521. if (impostor.isBodyInitRequired()) {
  85522. var shape = this._createShape(impostor);
  85523. //unregister events, if body is being changed
  85524. var oldBody = impostor.physicsBody;
  85525. if (oldBody) {
  85526. this.removePhysicsBody(impostor);
  85527. }
  85528. //create the body and material
  85529. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85530. var bodyCreationObject = {
  85531. mass: impostor.getParam("mass"),
  85532. material: material
  85533. };
  85534. // A simple extend, in case native options were used.
  85535. var nativeOptions = impostor.getParam("nativeOptions");
  85536. for (var key in nativeOptions) {
  85537. if (nativeOptions.hasOwnProperty(key)) {
  85538. bodyCreationObject[key] = nativeOptions[key];
  85539. }
  85540. }
  85541. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85542. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85543. this.world.addEventListener("preStep", impostor.beforeStep);
  85544. this.world.addEventListener("postStep", impostor.afterStep);
  85545. impostor.physicsBody.addShape(shape);
  85546. this.world.add(impostor.physicsBody);
  85547. //try to keep the body moving in the right direction by taking old properties.
  85548. //Should be tested!
  85549. if (oldBody) {
  85550. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85551. impostor.physicsBody[param].copy(oldBody[param]);
  85552. });
  85553. }
  85554. this._processChildMeshes(impostor);
  85555. }
  85556. //now update the body's transformation
  85557. this._updatePhysicsBodyTransformation(impostor);
  85558. };
  85559. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85560. var _this = this;
  85561. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85562. var currentRotation = mainImpostor.object.rotationQuaternion;
  85563. if (meshChildren.length) {
  85564. var processMesh = function (localPosition, mesh) {
  85565. if (!currentRotation || !mesh.rotationQuaternion) {
  85566. return;
  85567. }
  85568. var childImpostor = mesh.getPhysicsImpostor();
  85569. if (childImpostor) {
  85570. var parent = childImpostor.parent;
  85571. if (parent !== mainImpostor) {
  85572. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85573. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85574. if (childImpostor.physicsBody) {
  85575. _this.removePhysicsBody(childImpostor);
  85576. childImpostor.physicsBody = null;
  85577. }
  85578. childImpostor.parent = mainImpostor;
  85579. childImpostor.resetUpdateFlags();
  85580. 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));
  85581. //Add the mass of the children.
  85582. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85583. }
  85584. }
  85585. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85586. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85587. };
  85588. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85589. }
  85590. };
  85591. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85592. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85593. this.world.removeEventListener("preStep", impostor.beforeStep);
  85594. this.world.removeEventListener("postStep", impostor.afterStep);
  85595. this.world.remove(impostor.physicsBody);
  85596. };
  85597. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85598. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85599. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85600. if (!mainBody || !connectedBody) {
  85601. return;
  85602. }
  85603. var constraint;
  85604. var jointData = impostorJoint.joint.jointData;
  85605. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85606. var constraintData = {
  85607. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85608. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85609. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85610. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85611. maxForce: jointData.nativeParams.maxForce,
  85612. collideConnected: !!jointData.collision
  85613. };
  85614. switch (impostorJoint.joint.type) {
  85615. case BABYLON.PhysicsJoint.HingeJoint:
  85616. case BABYLON.PhysicsJoint.Hinge2Joint:
  85617. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85618. break;
  85619. case BABYLON.PhysicsJoint.DistanceJoint:
  85620. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85621. break;
  85622. case BABYLON.PhysicsJoint.SpringJoint:
  85623. var springData = jointData;
  85624. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85625. restLength: springData.length,
  85626. stiffness: springData.stiffness,
  85627. damping: springData.damping,
  85628. localAnchorA: constraintData.pivotA,
  85629. localAnchorB: constraintData.pivotB
  85630. });
  85631. break;
  85632. case BABYLON.PhysicsJoint.LockJoint:
  85633. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85634. break;
  85635. case BABYLON.PhysicsJoint.PointToPointJoint:
  85636. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85637. default:
  85638. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85639. break;
  85640. }
  85641. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85642. constraint.collideConnected = !!jointData.collision;
  85643. impostorJoint.joint.physicsJoint = constraint;
  85644. //don't add spring as constraint, as it is not one.
  85645. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85646. this.world.addConstraint(constraint);
  85647. }
  85648. else {
  85649. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85650. constraint.applyForce();
  85651. });
  85652. }
  85653. };
  85654. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85655. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85656. };
  85657. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85658. var index;
  85659. var mat;
  85660. for (index = 0; index < this._physicsMaterials.length; index++) {
  85661. mat = this._physicsMaterials[index];
  85662. if (mat.friction === friction && mat.restitution === restitution) {
  85663. return mat;
  85664. }
  85665. }
  85666. var currentMat = new this.BJSCANNON.Material(name);
  85667. currentMat.friction = friction;
  85668. currentMat.restitution = restitution;
  85669. this._physicsMaterials.push(currentMat);
  85670. return currentMat;
  85671. };
  85672. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85673. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85674. };
  85675. CannonJSPlugin.prototype._createShape = function (impostor) {
  85676. var object = impostor.object;
  85677. var returnValue;
  85678. var extendSize = impostor.getObjectExtendSize();
  85679. switch (impostor.type) {
  85680. case BABYLON.PhysicsImpostor.SphereImpostor:
  85681. var radiusX = extendSize.x;
  85682. var radiusY = extendSize.y;
  85683. var radiusZ = extendSize.z;
  85684. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85685. break;
  85686. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85687. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85688. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85689. break;
  85690. case BABYLON.PhysicsImpostor.BoxImpostor:
  85691. var box = extendSize.scale(0.5);
  85692. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85693. break;
  85694. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85695. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85696. returnValue = new this.BJSCANNON.Plane();
  85697. break;
  85698. case BABYLON.PhysicsImpostor.MeshImpostor:
  85699. // should transform the vertex data to world coordinates!!
  85700. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85701. var rawFaces = object.getIndices ? object.getIndices() : [];
  85702. if (!rawVerts)
  85703. return;
  85704. // get only scale! so the object could transform correctly.
  85705. var oldPosition = object.position.clone();
  85706. var oldRotation = object.rotation && object.rotation.clone();
  85707. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85708. object.position.copyFromFloats(0, 0, 0);
  85709. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85710. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85711. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85712. var transform = object.computeWorldMatrix(true);
  85713. // convert rawVerts to object space
  85714. var temp = new Array();
  85715. var index;
  85716. for (index = 0; index < rawVerts.length; index += 3) {
  85717. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85718. }
  85719. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85720. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85721. //now set back the transformation!
  85722. object.position.copyFrom(oldPosition);
  85723. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85724. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85725. break;
  85726. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85727. var oldPosition2 = object.position.clone();
  85728. var oldRotation2 = object.rotation && object.rotation.clone();
  85729. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85730. object.position.copyFromFloats(0, 0, 0);
  85731. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85732. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85733. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85734. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85735. returnValue = this._createHeightmap(object);
  85736. object.position.copyFrom(oldPosition2);
  85737. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85738. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85739. object.computeWorldMatrix(true);
  85740. break;
  85741. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85742. returnValue = new this.BJSCANNON.Particle();
  85743. break;
  85744. }
  85745. return returnValue;
  85746. };
  85747. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85748. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85749. var transform = object.computeWorldMatrix(true);
  85750. // convert rawVerts to object space
  85751. var temp = new Array();
  85752. var index;
  85753. for (index = 0; index < pos.length; index += 3) {
  85754. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85755. }
  85756. pos = temp;
  85757. var matrix = new Array();
  85758. //For now pointDepth will not be used and will be automatically calculated.
  85759. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85760. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85761. var boundingInfo = object.getBoundingInfo();
  85762. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85763. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85764. var elementSize = dim * 2 / arraySize;
  85765. for (var i = 0; i < pos.length; i = i + 3) {
  85766. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85767. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85768. var y = -pos[i + 2] + minY;
  85769. if (!matrix[x]) {
  85770. matrix[x] = [];
  85771. }
  85772. if (!matrix[x][z]) {
  85773. matrix[x][z] = y;
  85774. }
  85775. matrix[x][z] = Math.max(y, matrix[x][z]);
  85776. }
  85777. for (var x = 0; x <= arraySize; ++x) {
  85778. if (!matrix[x]) {
  85779. var loc = 1;
  85780. while (!matrix[(x + loc) % arraySize]) {
  85781. loc++;
  85782. }
  85783. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85784. //console.log("missing x", x);
  85785. }
  85786. for (var z = 0; z <= arraySize; ++z) {
  85787. if (!matrix[x][z]) {
  85788. var loc = 1;
  85789. var newValue;
  85790. while (newValue === undefined) {
  85791. newValue = matrix[x][(z + loc++) % arraySize];
  85792. }
  85793. matrix[x][z] = newValue;
  85794. }
  85795. }
  85796. }
  85797. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85798. elementSize: elementSize
  85799. });
  85800. //For future reference, needed for body transformation
  85801. shape.minY = minY;
  85802. return shape;
  85803. };
  85804. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85805. var object = impostor.object;
  85806. //make sure it is updated...
  85807. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85808. // The delta between the mesh position and the mesh bounding box center
  85809. var bInfo = object.getBoundingInfo();
  85810. if (!bInfo)
  85811. return;
  85812. var center = impostor.getObjectCenter();
  85813. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85814. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85815. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85816. this._tmpPosition.copyFrom(center);
  85817. var quaternion = object.rotationQuaternion;
  85818. if (!quaternion) {
  85819. return;
  85820. }
  85821. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85822. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85823. //-90 DEG in X, precalculated
  85824. quaternion = quaternion.multiply(this._minus90X);
  85825. //Invert! (Precalculated, 90 deg in X)
  85826. //No need to clone. this will never change.
  85827. impostor.setDeltaRotation(this._plus90X);
  85828. }
  85829. //If it is a heightfield, if should be centered.
  85830. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  85831. var mesh = object;
  85832. var boundingInfo = mesh.getBoundingInfo();
  85833. //calculate the correct body position:
  85834. var rotationQuaternion = mesh.rotationQuaternion;
  85835. mesh.rotationQuaternion = this._tmpUnityRotation;
  85836. mesh.computeWorldMatrix(true);
  85837. //get original center with no rotation
  85838. var c = center.clone();
  85839. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  85840. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  85841. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  85842. mesh.setPreTransformMatrix(p);
  85843. mesh.computeWorldMatrix(true);
  85844. //calculate the translation
  85845. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  85846. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  85847. //add it inverted to the delta
  85848. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  85849. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  85850. //rotation is back
  85851. mesh.rotationQuaternion = rotationQuaternion;
  85852. mesh.setPreTransformMatrix(oldPivot);
  85853. mesh.computeWorldMatrix(true);
  85854. }
  85855. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  85856. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  85857. //this._tmpPosition.copyFrom(object.position);
  85858. }
  85859. impostor.setDeltaPosition(this._tmpDeltaPosition);
  85860. //Now update the impostor object
  85861. impostor.physicsBody.position.copy(this._tmpPosition);
  85862. impostor.physicsBody.quaternion.copy(quaternion);
  85863. };
  85864. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  85865. impostor.object.position.copyFrom(impostor.physicsBody.position);
  85866. if (impostor.object.rotationQuaternion) {
  85867. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  85868. }
  85869. };
  85870. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  85871. impostor.physicsBody.position.copy(newPosition);
  85872. impostor.physicsBody.quaternion.copy(newRotation);
  85873. };
  85874. CannonJSPlugin.prototype.isSupported = function () {
  85875. return this.BJSCANNON !== undefined;
  85876. };
  85877. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  85878. impostor.physicsBody.velocity.copy(velocity);
  85879. };
  85880. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  85881. impostor.physicsBody.angularVelocity.copy(velocity);
  85882. };
  85883. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  85884. var v = impostor.physicsBody.velocity;
  85885. if (!v) {
  85886. return null;
  85887. }
  85888. return new BABYLON.Vector3(v.x, v.y, v.z);
  85889. };
  85890. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  85891. var v = impostor.physicsBody.angularVelocity;
  85892. if (!v) {
  85893. return null;
  85894. }
  85895. return new BABYLON.Vector3(v.x, v.y, v.z);
  85896. };
  85897. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  85898. impostor.physicsBody.mass = mass;
  85899. impostor.physicsBody.updateMassProperties();
  85900. };
  85901. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  85902. return impostor.physicsBody.mass;
  85903. };
  85904. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  85905. return impostor.physicsBody.material.friction;
  85906. };
  85907. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  85908. impostor.physicsBody.material.friction = friction;
  85909. };
  85910. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  85911. return impostor.physicsBody.material.restitution;
  85912. };
  85913. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  85914. impostor.physicsBody.material.restitution = restitution;
  85915. };
  85916. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  85917. impostor.physicsBody.sleep();
  85918. };
  85919. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  85920. impostor.physicsBody.wakeUp();
  85921. };
  85922. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  85923. joint.physicsJoint.distance = maxDistance;
  85924. };
  85925. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85926. // if (!motorIndex) {
  85927. // joint.physicsJoint.enableMotor();
  85928. // }
  85929. // }
  85930. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  85931. // if (!motorIndex) {
  85932. // joint.physicsJoint.disableMotor();
  85933. // }
  85934. // }
  85935. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  85936. if (!motorIndex) {
  85937. joint.physicsJoint.enableMotor();
  85938. joint.physicsJoint.setMotorSpeed(speed);
  85939. if (maxForce) {
  85940. this.setLimit(joint, maxForce);
  85941. }
  85942. }
  85943. };
  85944. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  85945. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  85946. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  85947. };
  85948. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  85949. var body = impostor.physicsBody;
  85950. mesh.position.x = body.position.x;
  85951. mesh.position.y = body.position.y;
  85952. mesh.position.z = body.position.z;
  85953. if (mesh.rotationQuaternion) {
  85954. mesh.rotationQuaternion.x = body.quaternion.x;
  85955. mesh.rotationQuaternion.y = body.quaternion.y;
  85956. mesh.rotationQuaternion.z = body.quaternion.z;
  85957. mesh.rotationQuaternion.w = body.quaternion.w;
  85958. }
  85959. };
  85960. CannonJSPlugin.prototype.getRadius = function (impostor) {
  85961. var shape = impostor.physicsBody.shapes[0];
  85962. return shape.boundingSphereRadius;
  85963. };
  85964. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  85965. var shape = impostor.physicsBody.shapes[0];
  85966. result.x = shape.halfExtents.x * 2;
  85967. result.y = shape.halfExtents.y * 2;
  85968. result.z = shape.halfExtents.z * 2;
  85969. };
  85970. CannonJSPlugin.prototype.dispose = function () {
  85971. };
  85972. CannonJSPlugin.prototype._extendNamespace = function () {
  85973. //this will force cannon to execute at least one step when using interpolation
  85974. var step_tmp1 = new this.BJSCANNON.Vec3();
  85975. var Engine = this.BJSCANNON;
  85976. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  85977. maxSubSteps = maxSubSteps || 10;
  85978. timeSinceLastCalled = timeSinceLastCalled || 0;
  85979. if (timeSinceLastCalled === 0) {
  85980. this.internalStep(dt);
  85981. this.time += dt;
  85982. }
  85983. else {
  85984. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  85985. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  85986. var t0 = performance.now();
  85987. for (var i = 0; i !== internalSteps; i++) {
  85988. this.internalStep(dt);
  85989. if (performance.now() - t0 > dt * 1000) {
  85990. break;
  85991. }
  85992. }
  85993. this.time += timeSinceLastCalled;
  85994. var h = this.time % dt;
  85995. var h_div_dt = h / dt;
  85996. var interpvelo = step_tmp1;
  85997. var bodies = this.bodies;
  85998. for (var j = 0; j !== bodies.length; j++) {
  85999. var b = bodies[j];
  86000. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86001. b.position.vsub(b.previousPosition, interpvelo);
  86002. interpvelo.scale(h_div_dt, interpvelo);
  86003. b.position.vadd(interpvelo, b.interpolatedPosition);
  86004. }
  86005. else {
  86006. b.interpolatedPosition.copy(b.position);
  86007. b.interpolatedQuaternion.copy(b.quaternion);
  86008. }
  86009. }
  86010. }
  86011. };
  86012. };
  86013. return CannonJSPlugin;
  86014. }());
  86015. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86016. })(BABYLON || (BABYLON = {}));
  86017. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86018. var BABYLON;
  86019. (function (BABYLON) {
  86020. var OimoJSPlugin = /** @class */ (function () {
  86021. function OimoJSPlugin(iterations) {
  86022. this.name = "OimoJSPlugin";
  86023. this._tmpImpostorsArray = [];
  86024. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86025. this.BJSOIMO = OIMO;
  86026. this.world = new this.BJSOIMO.World({
  86027. iterations: iterations
  86028. });
  86029. this.world.clear();
  86030. }
  86031. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86032. this.world.gravity.copy(gravity);
  86033. };
  86034. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86035. this.world.timeStep = timeStep;
  86036. };
  86037. OimoJSPlugin.prototype.getTimeStep = function () {
  86038. return this.world.timeStep;
  86039. };
  86040. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86041. var _this = this;
  86042. impostors.forEach(function (impostor) {
  86043. impostor.beforeStep();
  86044. });
  86045. this.world.step();
  86046. impostors.forEach(function (impostor) {
  86047. impostor.afterStep();
  86048. //update the ordered impostors array
  86049. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86050. });
  86051. //check for collisions
  86052. var contact = this.world.contacts;
  86053. while (contact !== null) {
  86054. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86055. contact = contact.next;
  86056. continue;
  86057. }
  86058. //is this body colliding with any other? get the impostor
  86059. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86060. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86061. if (!mainImpostor || !collidingImpostor) {
  86062. contact = contact.next;
  86063. continue;
  86064. }
  86065. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86066. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86067. contact = contact.next;
  86068. }
  86069. };
  86070. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86071. var mass = impostor.physicsBody.mass;
  86072. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86073. };
  86074. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86075. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86076. this.applyImpulse(impostor, force, contactPoint);
  86077. };
  86078. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86079. var _this = this;
  86080. //parent-child relationship. Does this impostor has a parent impostor?
  86081. if (impostor.parent) {
  86082. if (impostor.physicsBody) {
  86083. this.removePhysicsBody(impostor);
  86084. //TODO is that needed?
  86085. impostor.forceUpdate();
  86086. }
  86087. return;
  86088. }
  86089. if (impostor.isBodyInitRequired()) {
  86090. var bodyConfig = {
  86091. name: impostor.uniqueId,
  86092. //Oimo must have mass, also for static objects.
  86093. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86094. size: [],
  86095. type: [],
  86096. pos: [],
  86097. posShape: [],
  86098. rot: [],
  86099. rotShape: [],
  86100. move: impostor.getParam("mass") !== 0,
  86101. density: impostor.getParam("mass"),
  86102. friction: impostor.getParam("friction"),
  86103. restitution: impostor.getParam("restitution"),
  86104. //Supporting older versions of Oimo
  86105. world: this.world
  86106. };
  86107. var impostors = [impostor];
  86108. var addToArray = function (parent) {
  86109. if (!parent.getChildMeshes)
  86110. return;
  86111. parent.getChildMeshes().forEach(function (m) {
  86112. if (m.physicsImpostor) {
  86113. impostors.push(m.physicsImpostor);
  86114. //m.physicsImpostor._init();
  86115. }
  86116. });
  86117. };
  86118. addToArray(impostor.object);
  86119. var checkWithEpsilon_1 = function (value) {
  86120. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86121. };
  86122. impostors.forEach(function (i) {
  86123. if (!i.object.rotationQuaternion) {
  86124. return;
  86125. }
  86126. //get the correct bounding box
  86127. var oldQuaternion = i.object.rotationQuaternion;
  86128. var rot = oldQuaternion.toEulerAngles();
  86129. var extendSize = i.getObjectExtendSize();
  86130. var radToDeg = 57.295779513082320876;
  86131. if (i === impostor) {
  86132. var center = impostor.getObjectCenter();
  86133. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86134. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86135. //Can also use Array.prototype.push.apply
  86136. bodyConfig.pos.push(center.x);
  86137. bodyConfig.pos.push(center.y);
  86138. bodyConfig.pos.push(center.z);
  86139. bodyConfig.posShape.push(0, 0, 0);
  86140. //tmp solution
  86141. bodyConfig.rot.push(rot.x * radToDeg);
  86142. bodyConfig.rot.push(rot.y * radToDeg);
  86143. bodyConfig.rot.push(rot.z * radToDeg);
  86144. bodyConfig.rotShape.push(0, 0, 0);
  86145. }
  86146. else {
  86147. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86148. bodyConfig.posShape.push(localPosition.x);
  86149. bodyConfig.posShape.push(localPosition.y);
  86150. bodyConfig.posShape.push(localPosition.z);
  86151. bodyConfig.pos.push(0, 0, 0);
  86152. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86153. bodyConfig.rot.push(0);
  86154. bodyConfig.rot.push(0);
  86155. bodyConfig.rot.push(0);
  86156. bodyConfig.rotShape.push(rot.x * radToDeg);
  86157. bodyConfig.rotShape.push(rot.y * radToDeg);
  86158. bodyConfig.rotShape.push(rot.z * radToDeg);
  86159. }
  86160. // register mesh
  86161. switch (i.type) {
  86162. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86163. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86164. case BABYLON.PhysicsImpostor.SphereImpostor:
  86165. var radiusX = extendSize.x;
  86166. var radiusY = extendSize.y;
  86167. var radiusZ = extendSize.z;
  86168. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86169. bodyConfig.type.push('sphere');
  86170. //due to the way oimo works with compounds, add 3 times
  86171. bodyConfig.size.push(size);
  86172. bodyConfig.size.push(size);
  86173. bodyConfig.size.push(size);
  86174. break;
  86175. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86176. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86177. var sizeY = checkWithEpsilon_1(extendSize.y);
  86178. bodyConfig.type.push('cylinder');
  86179. bodyConfig.size.push(sizeX);
  86180. bodyConfig.size.push(sizeY);
  86181. //due to the way oimo works with compounds, add one more value.
  86182. bodyConfig.size.push(sizeY);
  86183. break;
  86184. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86185. case BABYLON.PhysicsImpostor.BoxImpostor:
  86186. default:
  86187. var sizeX = checkWithEpsilon_1(extendSize.x);
  86188. var sizeY = checkWithEpsilon_1(extendSize.y);
  86189. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86190. bodyConfig.type.push('box');
  86191. //if (i === impostor) {
  86192. bodyConfig.size.push(sizeX);
  86193. bodyConfig.size.push(sizeY);
  86194. bodyConfig.size.push(sizeZ);
  86195. //} else {
  86196. // bodyConfig.size.push(0,0,0);
  86197. //}
  86198. break;
  86199. }
  86200. //actually not needed, but hey...
  86201. i.object.rotationQuaternion = oldQuaternion;
  86202. });
  86203. impostor.physicsBody = this.world.add(bodyConfig);
  86204. }
  86205. else {
  86206. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86207. }
  86208. impostor.setDeltaPosition(this._tmpPositionVector);
  86209. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86210. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86211. };
  86212. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86213. //impostor.physicsBody.dispose();
  86214. //Same as : (older oimo versions)
  86215. this.world.removeRigidBody(impostor.physicsBody);
  86216. };
  86217. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86218. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86219. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86220. if (!mainBody || !connectedBody) {
  86221. return;
  86222. }
  86223. var jointData = impostorJoint.joint.jointData;
  86224. var options = jointData.nativeParams || {};
  86225. var type;
  86226. var nativeJointData = {
  86227. body1: mainBody,
  86228. body2: connectedBody,
  86229. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86230. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86231. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86232. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86233. min: options.min,
  86234. max: options.max,
  86235. collision: options.collision || jointData.collision,
  86236. spring: options.spring,
  86237. //supporting older version of Oimo
  86238. world: this.world
  86239. };
  86240. switch (impostorJoint.joint.type) {
  86241. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86242. type = "jointBall";
  86243. break;
  86244. case BABYLON.PhysicsJoint.SpringJoint:
  86245. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86246. var springData = jointData;
  86247. nativeJointData.min = springData.length || nativeJointData.min;
  86248. //Max should also be set, just make sure it is at least min
  86249. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86250. case BABYLON.PhysicsJoint.DistanceJoint:
  86251. type = "jointDistance";
  86252. nativeJointData.max = jointData.maxDistance;
  86253. break;
  86254. case BABYLON.PhysicsJoint.PrismaticJoint:
  86255. type = "jointPrisme";
  86256. break;
  86257. case BABYLON.PhysicsJoint.SliderJoint:
  86258. type = "jointSlide";
  86259. break;
  86260. case BABYLON.PhysicsJoint.WheelJoint:
  86261. type = "jointWheel";
  86262. break;
  86263. case BABYLON.PhysicsJoint.HingeJoint:
  86264. default:
  86265. type = "jointHinge";
  86266. break;
  86267. }
  86268. nativeJointData.type = type;
  86269. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86270. };
  86271. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86272. //Bug in Oimo prevents us from disposing a joint in the playground
  86273. //joint.joint.physicsJoint.dispose();
  86274. //So we will bruteforce it!
  86275. try {
  86276. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86277. }
  86278. catch (e) {
  86279. BABYLON.Tools.Warn(e);
  86280. }
  86281. };
  86282. OimoJSPlugin.prototype.isSupported = function () {
  86283. return this.BJSOIMO !== undefined;
  86284. };
  86285. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86286. if (!impostor.physicsBody.sleeping) {
  86287. //TODO check that
  86288. /*if (impostor.physicsBody.shapes.next) {
  86289. var parentShape = this._getLastShape(impostor.physicsBody);
  86290. impostor.object.position.copyFrom(parentShape.position);
  86291. console.log(parentShape.position);
  86292. } else {*/
  86293. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86294. //}
  86295. if (impostor.object.rotationQuaternion) {
  86296. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86297. }
  86298. }
  86299. };
  86300. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86301. var body = impostor.physicsBody;
  86302. body.position.copy(newPosition);
  86303. body.orientation.copy(newRotation);
  86304. body.syncShapes();
  86305. body.awake();
  86306. };
  86307. /*private _getLastShape(body: any): any {
  86308. var lastShape = body.shapes;
  86309. while (lastShape.next) {
  86310. lastShape = lastShape.next;
  86311. }
  86312. return lastShape;
  86313. }*/
  86314. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86315. impostor.physicsBody.linearVelocity.copy(velocity);
  86316. };
  86317. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86318. impostor.physicsBody.angularVelocity.copy(velocity);
  86319. };
  86320. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86321. var v = impostor.physicsBody.linearVelocity;
  86322. if (!v) {
  86323. return null;
  86324. }
  86325. return new BABYLON.Vector3(v.x, v.y, v.z);
  86326. };
  86327. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86328. var v = impostor.physicsBody.angularVelocity;
  86329. if (!v) {
  86330. return null;
  86331. }
  86332. return new BABYLON.Vector3(v.x, v.y, v.z);
  86333. };
  86334. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86335. var staticBody = mass === 0;
  86336. //this will actually set the body's density and not its mass.
  86337. //But this is how oimo treats the mass variable.
  86338. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86339. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86340. };
  86341. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86342. return impostor.physicsBody.shapes.density;
  86343. };
  86344. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86345. return impostor.physicsBody.shapes.friction;
  86346. };
  86347. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86348. impostor.physicsBody.shapes.friction = friction;
  86349. };
  86350. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86351. return impostor.physicsBody.shapes.restitution;
  86352. };
  86353. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86354. impostor.physicsBody.shapes.restitution = restitution;
  86355. };
  86356. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86357. impostor.physicsBody.sleep();
  86358. };
  86359. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86360. impostor.physicsBody.awake();
  86361. };
  86362. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86363. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86364. if (minDistance !== void 0) {
  86365. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86366. }
  86367. };
  86368. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86369. //TODO separate rotational and transational motors.
  86370. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86371. if (motor) {
  86372. motor.setMotor(speed, maxForce);
  86373. }
  86374. };
  86375. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86376. //TODO separate rotational and transational motors.
  86377. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86378. if (motor) {
  86379. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86380. }
  86381. };
  86382. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86383. var body = impostor.physicsBody;
  86384. mesh.position.x = body.position.x;
  86385. mesh.position.y = body.position.y;
  86386. mesh.position.z = body.position.z;
  86387. if (mesh.rotationQuaternion) {
  86388. mesh.rotationQuaternion.x = body.orientation.x;
  86389. mesh.rotationQuaternion.y = body.orientation.y;
  86390. mesh.rotationQuaternion.z = body.orientation.z;
  86391. mesh.rotationQuaternion.w = body.orientation.s;
  86392. }
  86393. };
  86394. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86395. return impostor.physicsBody.shapes.radius;
  86396. };
  86397. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86398. var shape = impostor.physicsBody.shapes;
  86399. result.x = shape.halfWidth * 2;
  86400. result.y = shape.halfHeight * 2;
  86401. result.z = shape.halfDepth * 2;
  86402. };
  86403. OimoJSPlugin.prototype.dispose = function () {
  86404. this.world.clear();
  86405. };
  86406. return OimoJSPlugin;
  86407. }());
  86408. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86409. })(BABYLON || (BABYLON = {}));
  86410. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86411. var BABYLON;
  86412. (function (BABYLON) {
  86413. /*
  86414. * Based on jsTGALoader - Javascript loader for TGA file
  86415. * By Vincent Thibault
  86416. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86417. */
  86418. var TGATools = /** @class */ (function () {
  86419. function TGATools() {
  86420. }
  86421. TGATools.GetTGAHeader = function (data) {
  86422. var offset = 0;
  86423. var header = {
  86424. id_length: data[offset++],
  86425. colormap_type: data[offset++],
  86426. image_type: data[offset++],
  86427. colormap_index: data[offset++] | data[offset++] << 8,
  86428. colormap_length: data[offset++] | data[offset++] << 8,
  86429. colormap_size: data[offset++],
  86430. origin: [
  86431. data[offset++] | data[offset++] << 8,
  86432. data[offset++] | data[offset++] << 8
  86433. ],
  86434. width: data[offset++] | data[offset++] << 8,
  86435. height: data[offset++] | data[offset++] << 8,
  86436. pixel_size: data[offset++],
  86437. flags: data[offset++]
  86438. };
  86439. return header;
  86440. };
  86441. TGATools.UploadContent = function (gl, data) {
  86442. // Not enough data to contain header ?
  86443. if (data.length < 19) {
  86444. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86445. return;
  86446. }
  86447. // Read Header
  86448. var offset = 18;
  86449. var header = TGATools.GetTGAHeader(data);
  86450. // Assume it's a valid Targa file.
  86451. if (header.id_length + offset > data.length) {
  86452. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86453. return;
  86454. }
  86455. // Skip not needed data
  86456. offset += header.id_length;
  86457. var use_rle = false;
  86458. var use_pal = false;
  86459. var use_grey = false;
  86460. // Get some informations.
  86461. switch (header.image_type) {
  86462. case TGATools._TYPE_RLE_INDEXED:
  86463. use_rle = true;
  86464. case TGATools._TYPE_INDEXED:
  86465. use_pal = true;
  86466. break;
  86467. case TGATools._TYPE_RLE_RGB:
  86468. use_rle = true;
  86469. case TGATools._TYPE_RGB:
  86470. // use_rgb = true;
  86471. break;
  86472. case TGATools._TYPE_RLE_GREY:
  86473. use_rle = true;
  86474. case TGATools._TYPE_GREY:
  86475. use_grey = true;
  86476. break;
  86477. }
  86478. var pixel_data;
  86479. // var numAlphaBits = header.flags & 0xf;
  86480. var pixel_size = header.pixel_size >> 3;
  86481. var pixel_total = header.width * header.height * pixel_size;
  86482. // Read palettes
  86483. var palettes;
  86484. if (use_pal) {
  86485. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86486. }
  86487. // Read LRE
  86488. if (use_rle) {
  86489. pixel_data = new Uint8Array(pixel_total);
  86490. var c, count, i;
  86491. var localOffset = 0;
  86492. var pixels = new Uint8Array(pixel_size);
  86493. while (offset < pixel_total && localOffset < pixel_total) {
  86494. c = data[offset++];
  86495. count = (c & 0x7f) + 1;
  86496. // RLE pixels
  86497. if (c & 0x80) {
  86498. // Bind pixel tmp array
  86499. for (i = 0; i < pixel_size; ++i) {
  86500. pixels[i] = data[offset++];
  86501. }
  86502. // Copy pixel array
  86503. for (i = 0; i < count; ++i) {
  86504. pixel_data.set(pixels, localOffset + i * pixel_size);
  86505. }
  86506. localOffset += pixel_size * count;
  86507. }
  86508. // Raw pixels
  86509. else {
  86510. count *= pixel_size;
  86511. for (i = 0; i < count; ++i) {
  86512. pixel_data[localOffset + i] = data[offset++];
  86513. }
  86514. localOffset += count;
  86515. }
  86516. }
  86517. }
  86518. // RAW Pixels
  86519. else {
  86520. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86521. }
  86522. // Load to texture
  86523. var x_start, y_start, x_step, y_step, y_end, x_end;
  86524. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86525. default:
  86526. case TGATools._ORIGIN_UL:
  86527. x_start = 0;
  86528. x_step = 1;
  86529. x_end = header.width;
  86530. y_start = 0;
  86531. y_step = 1;
  86532. y_end = header.height;
  86533. break;
  86534. case TGATools._ORIGIN_BL:
  86535. x_start = 0;
  86536. x_step = 1;
  86537. x_end = header.width;
  86538. y_start = header.height - 1;
  86539. y_step = -1;
  86540. y_end = -1;
  86541. break;
  86542. case TGATools._ORIGIN_UR:
  86543. x_start = header.width - 1;
  86544. x_step = -1;
  86545. x_end = -1;
  86546. y_start = 0;
  86547. y_step = 1;
  86548. y_end = header.height;
  86549. break;
  86550. case TGATools._ORIGIN_BR:
  86551. x_start = header.width - 1;
  86552. x_step = -1;
  86553. x_end = -1;
  86554. y_start = header.height - 1;
  86555. y_step = -1;
  86556. y_end = -1;
  86557. break;
  86558. }
  86559. // Load the specify method
  86560. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86561. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86562. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86563. };
  86564. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86565. var image = pixel_data, colormap = palettes;
  86566. var width = header.width, height = header.height;
  86567. var color, i = 0, x, y;
  86568. var imageData = new Uint8Array(width * height * 4);
  86569. for (y = y_start; y !== y_end; y += y_step) {
  86570. for (x = x_start; x !== x_end; x += x_step, i++) {
  86571. color = image[i];
  86572. imageData[(x + width * y) * 4 + 3] = 255;
  86573. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86574. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86575. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86576. }
  86577. }
  86578. return imageData;
  86579. };
  86580. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86581. var image = pixel_data;
  86582. var width = header.width, height = header.height;
  86583. var color, i = 0, x, y;
  86584. var imageData = new Uint8Array(width * height * 4);
  86585. for (y = y_start; y !== y_end; y += y_step) {
  86586. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86587. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86588. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86589. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86590. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86591. imageData[(x + width * y) * 4 + 0] = r;
  86592. imageData[(x + width * y) * 4 + 1] = g;
  86593. imageData[(x + width * y) * 4 + 2] = b;
  86594. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86595. }
  86596. }
  86597. return imageData;
  86598. };
  86599. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86600. var image = pixel_data;
  86601. var width = header.width, height = header.height;
  86602. var i = 0, x, y;
  86603. var imageData = new Uint8Array(width * height * 4);
  86604. for (y = y_start; y !== y_end; y += y_step) {
  86605. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86606. imageData[(x + width * y) * 4 + 3] = 255;
  86607. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86608. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86609. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86610. }
  86611. }
  86612. return imageData;
  86613. };
  86614. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86615. var image = pixel_data;
  86616. var width = header.width, height = header.height;
  86617. var i = 0, x, y;
  86618. var imageData = new Uint8Array(width * height * 4);
  86619. for (y = y_start; y !== y_end; y += y_step) {
  86620. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86621. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86622. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86623. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86624. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86625. }
  86626. }
  86627. return imageData;
  86628. };
  86629. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86630. var image = pixel_data;
  86631. var width = header.width, height = header.height;
  86632. var color, i = 0, x, y;
  86633. var imageData = new Uint8Array(width * height * 4);
  86634. for (y = y_start; y !== y_end; y += y_step) {
  86635. for (x = x_start; x !== x_end; x += x_step, i++) {
  86636. color = image[i];
  86637. imageData[(x + width * y) * 4 + 0] = color;
  86638. imageData[(x + width * y) * 4 + 1] = color;
  86639. imageData[(x + width * y) * 4 + 2] = color;
  86640. imageData[(x + width * y) * 4 + 3] = 255;
  86641. }
  86642. }
  86643. return imageData;
  86644. };
  86645. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86646. var image = pixel_data;
  86647. var width = header.width, height = header.height;
  86648. var i = 0, x, y;
  86649. var imageData = new Uint8Array(width * height * 4);
  86650. for (y = y_start; y !== y_end; y += y_step) {
  86651. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86652. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86653. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86654. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86655. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86656. }
  86657. }
  86658. return imageData;
  86659. };
  86660. //private static _TYPE_NO_DATA = 0;
  86661. TGATools._TYPE_INDEXED = 1;
  86662. TGATools._TYPE_RGB = 2;
  86663. TGATools._TYPE_GREY = 3;
  86664. TGATools._TYPE_RLE_INDEXED = 9;
  86665. TGATools._TYPE_RLE_RGB = 10;
  86666. TGATools._TYPE_RLE_GREY = 11;
  86667. TGATools._ORIGIN_MASK = 0x30;
  86668. TGATools._ORIGIN_SHIFT = 0x04;
  86669. TGATools._ORIGIN_BL = 0x00;
  86670. TGATools._ORIGIN_BR = 0x01;
  86671. TGATools._ORIGIN_UL = 0x02;
  86672. TGATools._ORIGIN_UR = 0x03;
  86673. return TGATools;
  86674. }());
  86675. BABYLON.TGATools = TGATools;
  86676. })(BABYLON || (BABYLON = {}));
  86677. //# sourceMappingURL=babylon.tga.js.map
  86678. var BABYLON;
  86679. (function (BABYLON) {
  86680. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86681. // All values and structures referenced from:
  86682. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86683. var DDS_MAGIC = 0x20534444;
  86684. var
  86685. //DDSD_CAPS = 0x1,
  86686. //DDSD_HEIGHT = 0x2,
  86687. //DDSD_WIDTH = 0x4,
  86688. //DDSD_PITCH = 0x8,
  86689. //DDSD_PIXELFORMAT = 0x1000,
  86690. DDSD_MIPMAPCOUNT = 0x20000;
  86691. //DDSD_LINEARSIZE = 0x80000,
  86692. //DDSD_DEPTH = 0x800000;
  86693. // var DDSCAPS_COMPLEX = 0x8,
  86694. // DDSCAPS_MIPMAP = 0x400000,
  86695. // DDSCAPS_TEXTURE = 0x1000;
  86696. var DDSCAPS2_CUBEMAP = 0x200;
  86697. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86698. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86699. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86700. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86701. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86702. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86703. // DDSCAPS2_VOLUME = 0x200000;
  86704. var
  86705. //DDPF_ALPHAPIXELS = 0x1,
  86706. //DDPF_ALPHA = 0x2,
  86707. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86708. //DDPF_YUV = 0x200,
  86709. DDPF_LUMINANCE = 0x20000;
  86710. function FourCCToInt32(value) {
  86711. return value.charCodeAt(0) +
  86712. (value.charCodeAt(1) << 8) +
  86713. (value.charCodeAt(2) << 16) +
  86714. (value.charCodeAt(3) << 24);
  86715. }
  86716. function Int32ToFourCC(value) {
  86717. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86718. }
  86719. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86720. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86721. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86722. var FOURCC_DX10 = FourCCToInt32("DX10");
  86723. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86724. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86725. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86726. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86727. var headerLengthInt = 31; // The header length in 32 bit ints
  86728. // Offsets into the header array
  86729. var off_magic = 0;
  86730. var off_size = 1;
  86731. var off_flags = 2;
  86732. var off_height = 3;
  86733. var off_width = 4;
  86734. var off_mipmapCount = 7;
  86735. var off_pfFlags = 20;
  86736. var off_pfFourCC = 21;
  86737. var off_RGBbpp = 22;
  86738. var off_RMask = 23;
  86739. var off_GMask = 24;
  86740. var off_BMask = 25;
  86741. var off_AMask = 26;
  86742. // var off_caps1 = 27;
  86743. var off_caps2 = 28;
  86744. // var off_caps3 = 29;
  86745. // var off_caps4 = 30;
  86746. var off_dxgiFormat = 32;
  86747. ;
  86748. var DDSTools = /** @class */ (function () {
  86749. function DDSTools() {
  86750. }
  86751. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86752. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86753. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86754. var mipmapCount = 1;
  86755. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86756. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86757. }
  86758. var fourCC = header[off_pfFourCC];
  86759. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86760. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86761. switch (fourCC) {
  86762. case FOURCC_D3DFMT_R16G16B16A16F:
  86763. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86764. break;
  86765. case FOURCC_D3DFMT_R32G32B32A32F:
  86766. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86767. break;
  86768. case FOURCC_DX10:
  86769. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86770. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86771. break;
  86772. }
  86773. }
  86774. return {
  86775. width: header[off_width],
  86776. height: header[off_height],
  86777. mipmapCount: mipmapCount,
  86778. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86779. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86780. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86781. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86782. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86783. dxgiFormat: dxgiFormat,
  86784. textureType: textureType
  86785. };
  86786. };
  86787. DDSTools._ToHalfFloat = function (value) {
  86788. if (!DDSTools._FloatView) {
  86789. DDSTools._FloatView = new Float32Array(1);
  86790. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86791. }
  86792. DDSTools._FloatView[0] = value;
  86793. var x = DDSTools._Int32View[0];
  86794. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86795. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86796. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86797. /* If zero, or denormal, or exponent underflows too much for a denormal
  86798. * half, return signed zero. */
  86799. if (e < 103) {
  86800. return bits;
  86801. }
  86802. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86803. if (e > 142) {
  86804. bits |= 0x7c00;
  86805. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86806. * not Inf, so make sure we set one mantissa bit too. */
  86807. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86808. return bits;
  86809. }
  86810. /* If exponent underflows but not too much, return a denormal */
  86811. if (e < 113) {
  86812. m |= 0x0800;
  86813. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86814. * to 1, which is OK. */
  86815. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86816. return bits;
  86817. }
  86818. bits |= ((e - 112) << 10) | (m >> 1);
  86819. bits += m & 1;
  86820. return bits;
  86821. };
  86822. DDSTools._FromHalfFloat = function (value) {
  86823. var s = (value & 0x8000) >> 15;
  86824. var e = (value & 0x7C00) >> 10;
  86825. var f = value & 0x03FF;
  86826. if (e === 0) {
  86827. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  86828. }
  86829. else if (e == 0x1F) {
  86830. return f ? NaN : ((s ? -1 : 1) * Infinity);
  86831. }
  86832. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  86833. };
  86834. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86835. var destArray = new Float32Array(dataLength);
  86836. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86837. var index = 0;
  86838. for (var y = 0; y < height; y++) {
  86839. for (var x = 0; x < width; x++) {
  86840. var srcPos = (x + y * width) * 4;
  86841. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  86842. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  86843. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  86844. if (DDSTools.StoreLODInAlphaChannel) {
  86845. destArray[index + 3] = lod;
  86846. }
  86847. else {
  86848. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  86849. }
  86850. index += 4;
  86851. }
  86852. }
  86853. return destArray;
  86854. };
  86855. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86856. if (DDSTools.StoreLODInAlphaChannel) {
  86857. var destArray = new Uint16Array(dataLength);
  86858. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86859. var index = 0;
  86860. for (var y = 0; y < height; y++) {
  86861. for (var x = 0; x < width; x++) {
  86862. var srcPos = (x + y * width) * 4;
  86863. destArray[index] = srcData[srcPos];
  86864. destArray[index + 1] = srcData[srcPos + 1];
  86865. destArray[index + 2] = srcData[srcPos + 2];
  86866. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  86867. index += 4;
  86868. }
  86869. }
  86870. return destArray;
  86871. }
  86872. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  86873. };
  86874. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86875. if (DDSTools.StoreLODInAlphaChannel) {
  86876. var destArray = new Float32Array(dataLength);
  86877. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86878. var index = 0;
  86879. for (var y = 0; y < height; y++) {
  86880. for (var x = 0; x < width; x++) {
  86881. var srcPos = (x + y * width) * 4;
  86882. destArray[index] = srcData[srcPos];
  86883. destArray[index + 1] = srcData[srcPos + 1];
  86884. destArray[index + 2] = srcData[srcPos + 2];
  86885. destArray[index + 3] = lod;
  86886. index += 4;
  86887. }
  86888. }
  86889. return destArray;
  86890. }
  86891. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  86892. };
  86893. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86894. var destArray = new Uint8Array(dataLength);
  86895. var srcData = new Float32Array(arrayBuffer, dataOffset);
  86896. var index = 0;
  86897. for (var y = 0; y < height; y++) {
  86898. for (var x = 0; x < width; x++) {
  86899. var srcPos = (x + y * width) * 4;
  86900. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  86901. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  86902. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  86903. if (DDSTools.StoreLODInAlphaChannel) {
  86904. destArray[index + 3] = lod;
  86905. }
  86906. else {
  86907. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  86908. }
  86909. index += 4;
  86910. }
  86911. }
  86912. return destArray;
  86913. };
  86914. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  86915. var destArray = new Uint8Array(dataLength);
  86916. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  86917. var index = 0;
  86918. for (var y = 0; y < height; y++) {
  86919. for (var x = 0; x < width; x++) {
  86920. var srcPos = (x + y * width) * 4;
  86921. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  86922. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  86923. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  86924. if (DDSTools.StoreLODInAlphaChannel) {
  86925. destArray[index + 3] = lod;
  86926. }
  86927. else {
  86928. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  86929. }
  86930. index += 4;
  86931. }
  86932. }
  86933. return destArray;
  86934. };
  86935. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  86936. var byteArray = new Uint8Array(dataLength);
  86937. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86938. var index = 0;
  86939. for (var y = 0; y < height; y++) {
  86940. for (var x = 0; x < width; x++) {
  86941. var srcPos = (x + y * width) * 4;
  86942. byteArray[index] = srcData[srcPos + rOffset];
  86943. byteArray[index + 1] = srcData[srcPos + gOffset];
  86944. byteArray[index + 2] = srcData[srcPos + bOffset];
  86945. byteArray[index + 3] = srcData[srcPos + aOffset];
  86946. index += 4;
  86947. }
  86948. }
  86949. return byteArray;
  86950. };
  86951. DDSTools._ExtractLongWordOrder = function (value) {
  86952. if (value === 0 || value === 255 || value === -16777216) {
  86953. return 0;
  86954. }
  86955. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  86956. };
  86957. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  86958. var byteArray = new Uint8Array(dataLength);
  86959. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86960. var index = 0;
  86961. for (var y = 0; y < height; y++) {
  86962. for (var x = 0; x < width; x++) {
  86963. var srcPos = (x + y * width) * 3;
  86964. byteArray[index] = srcData[srcPos + rOffset];
  86965. byteArray[index + 1] = srcData[srcPos + gOffset];
  86966. byteArray[index + 2] = srcData[srcPos + bOffset];
  86967. index += 3;
  86968. }
  86969. }
  86970. return byteArray;
  86971. };
  86972. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  86973. var byteArray = new Uint8Array(dataLength);
  86974. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  86975. var index = 0;
  86976. for (var y = 0; y < height; y++) {
  86977. for (var x = 0; x < width; x++) {
  86978. var srcPos = (x + y * width);
  86979. byteArray[index] = srcData[srcPos];
  86980. index++;
  86981. }
  86982. }
  86983. return byteArray;
  86984. };
  86985. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  86986. if (lodIndex === void 0) { lodIndex = -1; }
  86987. var sphericalPolynomialFaces = null;
  86988. if (info.sphericalPolynomial) {
  86989. sphericalPolynomialFaces = new Array();
  86990. }
  86991. var ext = engine.getCaps().s3tc;
  86992. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86993. var fourCC, width, height, dataLength = 0, dataOffset;
  86994. var byteArray, mipmapCount, mip;
  86995. var internalFormat = 0;
  86996. var format = 0;
  86997. var blockBytes = 1;
  86998. if (header[off_magic] !== DDS_MAGIC) {
  86999. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87000. return;
  87001. }
  87002. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87003. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87004. return;
  87005. }
  87006. if (info.isCompressed && !ext) {
  87007. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87008. return;
  87009. }
  87010. var bpp = header[off_RGBbpp];
  87011. dataOffset = header[off_size] + 4;
  87012. var computeFormats = false;
  87013. if (info.isFourCC) {
  87014. fourCC = header[off_pfFourCC];
  87015. switch (fourCC) {
  87016. case FOURCC_DXT1:
  87017. blockBytes = 8;
  87018. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87019. break;
  87020. case FOURCC_DXT3:
  87021. blockBytes = 16;
  87022. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87023. break;
  87024. case FOURCC_DXT5:
  87025. blockBytes = 16;
  87026. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87027. break;
  87028. case FOURCC_D3DFMT_R16G16B16A16F:
  87029. computeFormats = true;
  87030. break;
  87031. case FOURCC_D3DFMT_R32G32B32A32F:
  87032. computeFormats = true;
  87033. break;
  87034. case FOURCC_DX10:
  87035. // There is an additionnal header so dataOffset need to be changed
  87036. dataOffset += 5 * 4; // 5 uints
  87037. var supported = false;
  87038. switch (info.dxgiFormat) {
  87039. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87040. computeFormats = true;
  87041. supported = true;
  87042. break;
  87043. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87044. info.isRGB = true;
  87045. info.isFourCC = false;
  87046. bpp = 32;
  87047. supported = true;
  87048. break;
  87049. }
  87050. if (supported) {
  87051. break;
  87052. }
  87053. default:
  87054. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87055. return;
  87056. }
  87057. }
  87058. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87059. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87060. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87061. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87062. if (computeFormats) {
  87063. format = engine._getWebGLTextureType(info.textureType);
  87064. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87065. }
  87066. mipmapCount = 1;
  87067. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87068. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87069. }
  87070. for (var face = 0; face < faces; face++) {
  87071. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87072. width = header[off_width];
  87073. height = header[off_height];
  87074. for (mip = 0; mip < mipmapCount; ++mip) {
  87075. if (lodIndex === -1 || lodIndex === mip) {
  87076. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87077. var i = (lodIndex === -1) ? mip : 0;
  87078. if (!info.isCompressed && info.isFourCC) {
  87079. dataLength = width * height * 4;
  87080. var floatArray = null;
  87081. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87082. if (bpp === 128) {
  87083. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87084. if (sphericalPolynomialFaces && i == 0) {
  87085. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87086. }
  87087. }
  87088. else if (bpp === 64) {
  87089. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87090. if (sphericalPolynomialFaces && i == 0) {
  87091. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87092. }
  87093. }
  87094. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87095. format = engine._getWebGLTextureType(info.textureType);
  87096. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87097. }
  87098. else {
  87099. if (bpp === 128) {
  87100. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87101. if (sphericalPolynomialFaces && i == 0) {
  87102. sphericalPolynomialFaces.push(floatArray);
  87103. }
  87104. }
  87105. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87106. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87107. if (sphericalPolynomialFaces && i == 0) {
  87108. sphericalPolynomialFaces.push(floatArray);
  87109. }
  87110. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87111. format = engine._getWebGLTextureType(info.textureType);
  87112. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87113. }
  87114. else { // 64
  87115. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87116. if (sphericalPolynomialFaces && i == 0) {
  87117. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87118. }
  87119. }
  87120. }
  87121. if (floatArray) {
  87122. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87123. }
  87124. }
  87125. else if (info.isRGB) {
  87126. if (bpp === 24) {
  87127. dataLength = width * height * 3;
  87128. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87129. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87130. }
  87131. else { // 32
  87132. dataLength = width * height * 4;
  87133. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87134. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87135. }
  87136. }
  87137. else if (info.isLuminance) {
  87138. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87139. var unpaddedRowSize = width;
  87140. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87141. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87142. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87143. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87144. }
  87145. else {
  87146. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87147. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87148. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87149. }
  87150. }
  87151. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87152. width *= 0.5;
  87153. height *= 0.5;
  87154. width = Math.max(1.0, width);
  87155. height = Math.max(1.0, height);
  87156. }
  87157. if (currentFace !== undefined) {
  87158. // Loading a single face
  87159. break;
  87160. }
  87161. }
  87162. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87163. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87164. size: header[off_width],
  87165. right: sphericalPolynomialFaces[0],
  87166. left: sphericalPolynomialFaces[1],
  87167. up: sphericalPolynomialFaces[2],
  87168. down: sphericalPolynomialFaces[3],
  87169. front: sphericalPolynomialFaces[4],
  87170. back: sphericalPolynomialFaces[5],
  87171. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87172. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87173. gammaSpace: false,
  87174. });
  87175. }
  87176. else {
  87177. info.sphericalPolynomial = undefined;
  87178. }
  87179. };
  87180. DDSTools.StoreLODInAlphaChannel = false;
  87181. return DDSTools;
  87182. }());
  87183. BABYLON.DDSTools = DDSTools;
  87184. })(BABYLON || (BABYLON = {}));
  87185. //# sourceMappingURL=babylon.dds.js.map
  87186. var BABYLON;
  87187. (function (BABYLON) {
  87188. /**
  87189. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87190. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87191. */
  87192. var KhronosTextureContainer = /** @class */ (function () {
  87193. /**
  87194. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87195. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87196. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87197. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87198. */
  87199. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87200. this.arrayBuffer = arrayBuffer;
  87201. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87202. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87203. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87204. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87205. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87206. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87207. BABYLON.Tools.Error("texture missing KTX identifier");
  87208. return;
  87209. }
  87210. // load the reset of the header in native 32 bit int
  87211. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87212. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87213. var oppositeEndianess = header[0] === 0x01020304;
  87214. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87215. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87216. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87217. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87218. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87219. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87220. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87221. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87222. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87223. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87224. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87225. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87226. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87227. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87228. if (this.glType !== 0) {
  87229. BABYLON.Tools.Error("only compressed formats currently supported");
  87230. return;
  87231. }
  87232. else {
  87233. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87234. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87235. }
  87236. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87237. BABYLON.Tools.Error("only 2D textures currently supported");
  87238. return;
  87239. }
  87240. if (this.numberOfArrayElements !== 0) {
  87241. BABYLON.Tools.Error("texture arrays not currently supported");
  87242. return;
  87243. }
  87244. if (this.numberOfFaces !== facesExpected) {
  87245. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87246. return;
  87247. }
  87248. // we now have a completely validated file, so could use existence of loadType as success
  87249. // would need to make this more elaborate & adjust checks above to support more than one load type
  87250. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87251. }
  87252. // not as fast hardware based, but will probably never need to use
  87253. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87254. return ((val & 0xFF) << 24)
  87255. | ((val & 0xFF00) << 8)
  87256. | ((val >> 8) & 0xFF00)
  87257. | ((val >> 24) & 0xFF);
  87258. };
  87259. /**
  87260. * It is assumed that the texture has already been created & is currently bound
  87261. */
  87262. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87263. switch (this.loadType) {
  87264. case KhronosTextureContainer.COMPRESSED_2D:
  87265. this._upload2DCompressedLevels(gl, loadMipmaps);
  87266. break;
  87267. case KhronosTextureContainer.TEX_2D:
  87268. case KhronosTextureContainer.COMPRESSED_3D:
  87269. case KhronosTextureContainer.TEX_3D:
  87270. }
  87271. };
  87272. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87273. // initialize width & height for level 1
  87274. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87275. var width = this.pixelWidth;
  87276. var height = this.pixelHeight;
  87277. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87278. for (var level = 0; level < mipmapCount; level++) {
  87279. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87280. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87281. for (var face = 0; face < this.numberOfFaces; face++) {
  87282. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87283. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87284. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87285. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87286. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87287. }
  87288. width = Math.max(1.0, width * 0.5);
  87289. height = Math.max(1.0, height * 0.5);
  87290. }
  87291. };
  87292. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87293. // load types
  87294. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87295. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87296. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87297. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87298. return KhronosTextureContainer;
  87299. }());
  87300. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87301. })(BABYLON || (BABYLON = {}));
  87302. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87303. var BABYLON;
  87304. (function (BABYLON) {
  87305. var Debug;
  87306. (function (Debug) {
  87307. /**
  87308. * Class used to render a debug view of a given skeleton
  87309. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87310. */
  87311. var SkeletonViewer = /** @class */ (function () {
  87312. /**
  87313. * Creates a new SkeletonViewer
  87314. * @param skeleton defines the skeleton to render
  87315. * @param mesh defines the mesh attached to the skeleton
  87316. * @param scene defines the hosting scene
  87317. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87318. * @param renderingGroupId defines the rendering group id to use with the viewer
  87319. */
  87320. function SkeletonViewer(
  87321. /** defines the skeleton to render */
  87322. skeleton,
  87323. /** defines the mesh attached to the skeleton */
  87324. mesh, scene,
  87325. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87326. autoUpdateBonesMatrices,
  87327. /** defines the rendering group id to use with the viewer */
  87328. renderingGroupId) {
  87329. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87330. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87331. this.skeleton = skeleton;
  87332. this.mesh = mesh;
  87333. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87334. this.renderingGroupId = renderingGroupId;
  87335. /** Gets or sets the color used to render the skeleton */
  87336. this.color = BABYLON.Color3.White();
  87337. this._debugLines = new Array();
  87338. this._isEnabled = false;
  87339. this._scene = scene;
  87340. this.update();
  87341. this._renderFunction = this.update.bind(this);
  87342. }
  87343. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87344. get: function () {
  87345. return this._isEnabled;
  87346. },
  87347. /** Gets or sets a boolean indicating if the viewer is enabled */
  87348. set: function (value) {
  87349. if (this._isEnabled === value) {
  87350. return;
  87351. }
  87352. this._isEnabled = value;
  87353. if (value) {
  87354. this._scene.registerBeforeRender(this._renderFunction);
  87355. }
  87356. else {
  87357. this._scene.unregisterBeforeRender(this._renderFunction);
  87358. }
  87359. },
  87360. enumerable: true,
  87361. configurable: true
  87362. });
  87363. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87364. if (x === void 0) { x = 0; }
  87365. if (y === void 0) { y = 0; }
  87366. if (z === void 0) { z = 0; }
  87367. var tmat = BABYLON.Tmp.Matrix[0];
  87368. var parentBone = bone.getParent();
  87369. tmat.copyFrom(bone.getLocalMatrix());
  87370. if (x !== 0 || y !== 0 || z !== 0) {
  87371. var tmat2 = BABYLON.Tmp.Matrix[1];
  87372. BABYLON.Matrix.IdentityToRef(tmat2);
  87373. tmat2.m[12] = x;
  87374. tmat2.m[13] = y;
  87375. tmat2.m[14] = z;
  87376. tmat2.multiplyToRef(tmat, tmat);
  87377. }
  87378. if (parentBone) {
  87379. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87380. }
  87381. tmat.multiplyToRef(meshMat, tmat);
  87382. position.x = tmat.m[12];
  87383. position.y = tmat.m[13];
  87384. position.z = tmat.m[14];
  87385. };
  87386. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87387. var len = bones.length;
  87388. var meshPos = this.mesh.position;
  87389. for (var i = 0; i < len; i++) {
  87390. var bone = bones[i];
  87391. var points = this._debugLines[i];
  87392. if (!points) {
  87393. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87394. this._debugLines[i] = points;
  87395. }
  87396. this._getBonePosition(points[0], bone, meshMat);
  87397. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87398. points[0].subtractInPlace(meshPos);
  87399. points[1].subtractInPlace(meshPos);
  87400. }
  87401. };
  87402. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87403. var len = bones.length;
  87404. var boneNum = 0;
  87405. var meshPos = this.mesh.position;
  87406. for (var i = len - 1; i >= 0; i--) {
  87407. var childBone = bones[i];
  87408. var parentBone = childBone.getParent();
  87409. if (!parentBone) {
  87410. continue;
  87411. }
  87412. var points = this._debugLines[boneNum];
  87413. if (!points) {
  87414. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87415. this._debugLines[boneNum] = points;
  87416. }
  87417. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87418. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87419. points[0].subtractInPlace(meshPos);
  87420. points[1].subtractInPlace(meshPos);
  87421. boneNum++;
  87422. }
  87423. };
  87424. /** Update the viewer to sync with current skeleton state */
  87425. SkeletonViewer.prototype.update = function () {
  87426. if (this.autoUpdateBonesMatrices) {
  87427. this.skeleton.computeAbsoluteTransforms();
  87428. }
  87429. if (this.skeleton.bones[0].length === undefined) {
  87430. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87431. }
  87432. else {
  87433. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87434. }
  87435. if (!this._debugMesh) {
  87436. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87437. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87438. }
  87439. else {
  87440. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87441. }
  87442. this._debugMesh.position.copyFrom(this.mesh.position);
  87443. this._debugMesh.color = this.color;
  87444. };
  87445. /** Release associated resources */
  87446. SkeletonViewer.prototype.dispose = function () {
  87447. if (this._debugMesh) {
  87448. this.isEnabled = false;
  87449. this._debugMesh.dispose();
  87450. this._debugMesh = null;
  87451. }
  87452. };
  87453. return SkeletonViewer;
  87454. }());
  87455. Debug.SkeletonViewer = SkeletonViewer;
  87456. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87457. })(BABYLON || (BABYLON = {}));
  87458. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87459. /**
  87460. * Module Debug contains the (visual) components to debug a scene correctly
  87461. */
  87462. var BABYLON;
  87463. (function (BABYLON) {
  87464. var Debug;
  87465. (function (Debug) {
  87466. /**
  87467. * The Axes viewer will show 3 axes in a specific point in space
  87468. */
  87469. var AxesViewer = /** @class */ (function () {
  87470. /**
  87471. * Creates a new AxesViewer
  87472. * @param scene defines the hosting scene
  87473. * @param scaleLines defines a number used to scale line length (1 by default)
  87474. */
  87475. function AxesViewer(scene, scaleLines) {
  87476. if (scaleLines === void 0) { scaleLines = 1; }
  87477. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87478. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87479. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87480. /**
  87481. * Gets or sets a number used to scale line length
  87482. */
  87483. this.scaleLines = 1;
  87484. this.scaleLines = scaleLines;
  87485. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87486. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87487. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87488. this._xmesh.renderingGroupId = 2;
  87489. this._ymesh.renderingGroupId = 2;
  87490. this._zmesh.renderingGroupId = 2;
  87491. this._xmesh.material.checkReadyOnlyOnce = true;
  87492. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87493. this._ymesh.material.checkReadyOnlyOnce = true;
  87494. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87495. this._zmesh.material.checkReadyOnlyOnce = true;
  87496. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87497. this.scene = scene;
  87498. }
  87499. /**
  87500. * Force the viewer to update
  87501. * @param position defines the position of the viewer
  87502. * @param xaxis defines the x axis of the viewer
  87503. * @param yaxis defines the y axis of the viewer
  87504. * @param zaxis defines the z axis of the viewer
  87505. */
  87506. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87507. var scaleLines = this.scaleLines;
  87508. if (this._xmesh) {
  87509. this._xmesh.position.copyFrom(position);
  87510. }
  87511. if (this._ymesh) {
  87512. this._ymesh.position.copyFrom(position);
  87513. }
  87514. if (this._zmesh) {
  87515. this._zmesh.position.copyFrom(position);
  87516. }
  87517. var point2 = this._xline[1];
  87518. point2.x = xaxis.x * scaleLines;
  87519. point2.y = xaxis.y * scaleLines;
  87520. point2.z = xaxis.z * scaleLines;
  87521. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87522. point2 = this._yline[1];
  87523. point2.x = yaxis.x * scaleLines;
  87524. point2.y = yaxis.y * scaleLines;
  87525. point2.z = yaxis.z * scaleLines;
  87526. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87527. point2 = this._zline[1];
  87528. point2.x = zaxis.x * scaleLines;
  87529. point2.y = zaxis.y * scaleLines;
  87530. point2.z = zaxis.z * scaleLines;
  87531. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87532. };
  87533. /** Releases resources */
  87534. AxesViewer.prototype.dispose = function () {
  87535. if (this._xmesh) {
  87536. this._xmesh.dispose();
  87537. }
  87538. if (this._ymesh) {
  87539. this._ymesh.dispose();
  87540. }
  87541. if (this._zmesh) {
  87542. this._zmesh.dispose();
  87543. }
  87544. this._xmesh = null;
  87545. this._ymesh = null;
  87546. this._zmesh = null;
  87547. this.scene = null;
  87548. };
  87549. return AxesViewer;
  87550. }());
  87551. Debug.AxesViewer = AxesViewer;
  87552. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87553. })(BABYLON || (BABYLON = {}));
  87554. //# sourceMappingURL=babylon.axesViewer.js.map
  87555. var BABYLON;
  87556. (function (BABYLON) {
  87557. var Debug;
  87558. (function (Debug) {
  87559. /**
  87560. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87561. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87562. */
  87563. var BoneAxesViewer = /** @class */ (function (_super) {
  87564. __extends(BoneAxesViewer, _super);
  87565. /**
  87566. * Creates a new BoneAxesViewer
  87567. * @param scene defines the hosting scene
  87568. * @param bone defines the target bone
  87569. * @param mesh defines the target mesh
  87570. * @param scaleLines defines a scaling factor for line length (1 by default)
  87571. */
  87572. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87573. if (scaleLines === void 0) { scaleLines = 1; }
  87574. var _this = _super.call(this, scene, scaleLines) || this;
  87575. /** Gets current position */
  87576. _this.pos = BABYLON.Vector3.Zero();
  87577. /** Gets direction of X axis */
  87578. _this.xaxis = BABYLON.Vector3.Zero();
  87579. /** Gets direction of Y axis */
  87580. _this.yaxis = BABYLON.Vector3.Zero();
  87581. /** Gets direction of Z axis */
  87582. _this.zaxis = BABYLON.Vector3.Zero();
  87583. _this.mesh = mesh;
  87584. _this.bone = bone;
  87585. return _this;
  87586. }
  87587. /**
  87588. * Force the viewer to update
  87589. */
  87590. BoneAxesViewer.prototype.update = function () {
  87591. if (!this.mesh || !this.bone) {
  87592. return;
  87593. }
  87594. var bone = this.bone;
  87595. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87596. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87597. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87598. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87599. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87600. };
  87601. /** Releases resources */
  87602. BoneAxesViewer.prototype.dispose = function () {
  87603. if (this.mesh) {
  87604. this.mesh = null;
  87605. this.bone = null;
  87606. _super.prototype.dispose.call(this);
  87607. }
  87608. };
  87609. return BoneAxesViewer;
  87610. }(Debug.AxesViewer));
  87611. Debug.BoneAxesViewer = BoneAxesViewer;
  87612. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87613. })(BABYLON || (BABYLON = {}));
  87614. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87615. var BABYLON;
  87616. (function (BABYLON) {
  87617. var RayHelper = /** @class */ (function () {
  87618. function RayHelper(ray) {
  87619. this.ray = ray;
  87620. }
  87621. RayHelper.CreateAndShow = function (ray, scene, color) {
  87622. var helper = new RayHelper(ray);
  87623. helper.show(scene, color);
  87624. return helper;
  87625. };
  87626. RayHelper.prototype.show = function (scene, color) {
  87627. if (!this._renderFunction && this.ray) {
  87628. var ray = this.ray;
  87629. this._renderFunction = this._render.bind(this);
  87630. this._scene = scene;
  87631. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87632. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87633. if (this._renderFunction) {
  87634. this._scene.registerBeforeRender(this._renderFunction);
  87635. }
  87636. }
  87637. if (color && this._renderLine) {
  87638. this._renderLine.color.copyFrom(color);
  87639. }
  87640. };
  87641. RayHelper.prototype.hide = function () {
  87642. if (this._renderFunction && this._scene) {
  87643. this._scene.unregisterBeforeRender(this._renderFunction);
  87644. this._scene = null;
  87645. this._renderFunction = null;
  87646. if (this._renderLine) {
  87647. this._renderLine.dispose();
  87648. this._renderLine = null;
  87649. }
  87650. this._renderPoints = [];
  87651. }
  87652. };
  87653. RayHelper.prototype._render = function () {
  87654. var ray = this.ray;
  87655. if (!ray) {
  87656. return;
  87657. }
  87658. var point = this._renderPoints[1];
  87659. var len = Math.min(ray.length, 1000000);
  87660. point.copyFrom(ray.direction);
  87661. point.scaleInPlace(len);
  87662. point.addInPlace(ray.origin);
  87663. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87664. };
  87665. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87666. this._attachedToMesh = mesh;
  87667. var ray = this.ray;
  87668. if (!ray) {
  87669. return;
  87670. }
  87671. if (!ray.direction) {
  87672. ray.direction = BABYLON.Vector3.Zero();
  87673. }
  87674. if (!ray.origin) {
  87675. ray.origin = BABYLON.Vector3.Zero();
  87676. }
  87677. if (length) {
  87678. ray.length = length;
  87679. }
  87680. if (!meshSpaceOrigin) {
  87681. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87682. }
  87683. if (!meshSpaceDirection) {
  87684. // -1 so that this will work with Mesh.lookAt
  87685. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87686. }
  87687. if (!this._meshSpaceDirection) {
  87688. this._meshSpaceDirection = meshSpaceDirection.clone();
  87689. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87690. }
  87691. else {
  87692. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87693. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87694. }
  87695. if (!this._updateToMeshFunction) {
  87696. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87697. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87698. }
  87699. this._updateToMesh();
  87700. };
  87701. RayHelper.prototype.detachFromMesh = function () {
  87702. if (this._attachedToMesh) {
  87703. if (this._updateToMeshFunction) {
  87704. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87705. }
  87706. this._attachedToMesh = null;
  87707. this._updateToMeshFunction = null;
  87708. }
  87709. };
  87710. RayHelper.prototype._updateToMesh = function () {
  87711. var ray = this.ray;
  87712. if (!this._attachedToMesh || !ray) {
  87713. return;
  87714. }
  87715. if (this._attachedToMesh._isDisposed) {
  87716. this.detachFromMesh();
  87717. return;
  87718. }
  87719. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87720. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87721. };
  87722. RayHelper.prototype.dispose = function () {
  87723. this.hide();
  87724. this.detachFromMesh();
  87725. this.ray = null;
  87726. };
  87727. return RayHelper;
  87728. }());
  87729. BABYLON.RayHelper = RayHelper;
  87730. })(BABYLON || (BABYLON = {}));
  87731. //# sourceMappingURL=babylon.rayHelper.js.map
  87732. var BABYLON;
  87733. (function (BABYLON) {
  87734. // load the inspector using require, if not present in the global namespace.
  87735. var DebugLayer = /** @class */ (function () {
  87736. function DebugLayer(scene) {
  87737. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87738. this._scene = scene;
  87739. // load inspector using require, if it doesn't exist on the global namespace.
  87740. }
  87741. /** Creates the inspector window. */
  87742. DebugLayer.prototype._createInspector = function (config) {
  87743. if (config === void 0) { config = {}; }
  87744. var popup = config.popup || false;
  87745. var initialTab = config.initialTab || 0;
  87746. var parentElement = config.parentElement || null;
  87747. if (!this._inspector) {
  87748. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87749. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87750. } // else nothing to do,; instance is already existing
  87751. };
  87752. DebugLayer.prototype.isVisible = function () {
  87753. if (!this._inspector) {
  87754. return false;
  87755. }
  87756. return true;
  87757. };
  87758. DebugLayer.prototype.hide = function () {
  87759. if (this._inspector) {
  87760. try {
  87761. this._inspector.dispose();
  87762. }
  87763. catch (e) {
  87764. // If the inspector has been removed directly from the inspector tool
  87765. }
  87766. this.onPropertyChangedObservable.clear();
  87767. this._inspector = null;
  87768. }
  87769. };
  87770. /**
  87771. *
  87772. * Launch the debugLayer.
  87773. *
  87774. * initialTab:
  87775. * | Value | Tab Name |
  87776. * | --- | --- |
  87777. * | 0 | Scene |
  87778. * | 1 | Console |
  87779. * | 2 | Stats |
  87780. * | 3 | Textures |
  87781. * | 4 | Mesh |
  87782. * | 5 | Light |
  87783. * | 6 | Material |
  87784. * | 7 | GLTF |
  87785. * | 8 | GUI |
  87786. * | 9 | Physics |
  87787. * | 10 | Camera |
  87788. * | 11 | Audio |
  87789. *
  87790. */
  87791. DebugLayer.prototype.show = function (config) {
  87792. if (config === void 0) { config = {}; }
  87793. if (typeof this.BJSINSPECTOR == 'undefined') {
  87794. // Load inspector and add it to the DOM
  87795. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87796. }
  87797. else {
  87798. // Otherwise creates the inspector
  87799. this._createInspector(config);
  87800. this.onPropertyChangedObservable = new BABYLON.Observable();
  87801. }
  87802. };
  87803. /**
  87804. * Gets the active tab
  87805. * @return the index of the active tab or -1 if the inspector is hidden
  87806. */
  87807. DebugLayer.prototype.getActiveTab = function () {
  87808. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87809. };
  87810. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87811. return DebugLayer;
  87812. }());
  87813. BABYLON.DebugLayer = DebugLayer;
  87814. })(BABYLON || (BABYLON = {}));
  87815. //# sourceMappingURL=babylon.debugLayer.js.map
  87816. var BABYLON;
  87817. (function (BABYLON) {
  87818. var Debug;
  87819. (function (Debug) {
  87820. /**
  87821. * Used to show the physics impostor around the specific mesh
  87822. */
  87823. var PhysicsViewer = /** @class */ (function () {
  87824. /**
  87825. * Creates a new PhysicsViewer
  87826. * @param scene defines the hosting scene
  87827. */
  87828. function PhysicsViewer(scene) {
  87829. /** @hidden */
  87830. this._impostors = [];
  87831. /** @hidden */
  87832. this._meshes = [];
  87833. /** @hidden */
  87834. this._numMeshes = 0;
  87835. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  87836. var physicEngine = this._scene.getPhysicsEngine();
  87837. if (physicEngine) {
  87838. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  87839. }
  87840. }
  87841. /** @hidden */
  87842. PhysicsViewer.prototype._updateDebugMeshes = function () {
  87843. var plugin = this._physicsEnginePlugin;
  87844. for (var i = 0; i < this._numMeshes; i++) {
  87845. var impostor = this._impostors[i];
  87846. if (!impostor) {
  87847. continue;
  87848. }
  87849. if (impostor.isDisposed) {
  87850. this.hideImpostor(this._impostors[i--]);
  87851. }
  87852. else {
  87853. var mesh = this._meshes[i];
  87854. if (mesh && plugin) {
  87855. plugin.syncMeshWithImpostor(mesh, impostor);
  87856. }
  87857. }
  87858. }
  87859. };
  87860. /**
  87861. * Renders a specified physic impostor
  87862. * @param impostor defines the impostor to render
  87863. */
  87864. PhysicsViewer.prototype.showImpostor = function (impostor) {
  87865. if (!this._scene) {
  87866. return;
  87867. }
  87868. for (var i = 0; i < this._numMeshes; i++) {
  87869. if (this._impostors[i] == impostor) {
  87870. return;
  87871. }
  87872. }
  87873. var debugMesh = this._getDebugMesh(impostor, this._scene);
  87874. if (debugMesh) {
  87875. this._impostors[this._numMeshes] = impostor;
  87876. this._meshes[this._numMeshes] = debugMesh;
  87877. if (this._numMeshes === 0) {
  87878. this._renderFunction = this._updateDebugMeshes.bind(this);
  87879. this._scene.registerBeforeRender(this._renderFunction);
  87880. }
  87881. this._numMeshes++;
  87882. }
  87883. };
  87884. /**
  87885. * Hides a specified physic impostor
  87886. * @param impostor defines the impostor to hide
  87887. */
  87888. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  87889. if (!impostor || !this._scene) {
  87890. return;
  87891. }
  87892. var removed = false;
  87893. for (var i = 0; i < this._numMeshes; i++) {
  87894. if (this._impostors[i] == impostor) {
  87895. var mesh = this._meshes[i];
  87896. if (!mesh) {
  87897. continue;
  87898. }
  87899. this._scene.removeMesh(mesh);
  87900. mesh.dispose();
  87901. this._numMeshes--;
  87902. if (this._numMeshes > 0) {
  87903. this._meshes[i] = this._meshes[this._numMeshes];
  87904. this._impostors[i] = this._impostors[this._numMeshes];
  87905. this._meshes[this._numMeshes] = null;
  87906. this._impostors[this._numMeshes] = null;
  87907. }
  87908. else {
  87909. this._meshes[0] = null;
  87910. this._impostors[0] = null;
  87911. }
  87912. removed = true;
  87913. break;
  87914. }
  87915. }
  87916. if (removed && this._numMeshes === 0) {
  87917. this._scene.unregisterBeforeRender(this._renderFunction);
  87918. }
  87919. };
  87920. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  87921. if (!this._debugMaterial) {
  87922. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  87923. this._debugMaterial.wireframe = true;
  87924. }
  87925. return this._debugMaterial;
  87926. };
  87927. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  87928. if (!this._debugBoxMesh) {
  87929. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  87930. this._debugBoxMesh.renderingGroupId = 1;
  87931. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87932. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  87933. scene.removeMesh(this._debugBoxMesh);
  87934. }
  87935. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  87936. };
  87937. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  87938. if (!this._debugSphereMesh) {
  87939. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  87940. this._debugSphereMesh.renderingGroupId = 1;
  87941. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  87942. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  87943. scene.removeMesh(this._debugSphereMesh);
  87944. }
  87945. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  87946. };
  87947. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  87948. var mesh = null;
  87949. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  87950. mesh = this._getDebugBoxMesh(scene);
  87951. impostor.getBoxSizeToRef(mesh.scaling);
  87952. }
  87953. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  87954. mesh = this._getDebugSphereMesh(scene);
  87955. var radius = impostor.getRadius();
  87956. mesh.scaling.x = radius * 2;
  87957. mesh.scaling.y = radius * 2;
  87958. mesh.scaling.z = radius * 2;
  87959. }
  87960. return mesh;
  87961. };
  87962. /** Releases all resources */
  87963. PhysicsViewer.prototype.dispose = function () {
  87964. for (var i = 0; i < this._numMeshes; i++) {
  87965. this.hideImpostor(this._impostors[i]);
  87966. }
  87967. if (this._debugBoxMesh) {
  87968. this._debugBoxMesh.dispose();
  87969. }
  87970. if (this._debugSphereMesh) {
  87971. this._debugSphereMesh.dispose();
  87972. }
  87973. if (this._debugMaterial) {
  87974. this._debugMaterial.dispose();
  87975. }
  87976. this._impostors.length = 0;
  87977. this._scene = null;
  87978. this._physicsEnginePlugin = null;
  87979. };
  87980. return PhysicsViewer;
  87981. }());
  87982. Debug.PhysicsViewer = PhysicsViewer;
  87983. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87984. })(BABYLON || (BABYLON = {}));
  87985. //# sourceMappingURL=babylon.physicsViewer.js.map
  87986. var BABYLON;
  87987. (function (BABYLON) {
  87988. var BoundingBoxRenderer = /** @class */ (function () {
  87989. function BoundingBoxRenderer(scene) {
  87990. this.frontColor = new BABYLON.Color3(1, 1, 1);
  87991. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  87992. this.showBackLines = true;
  87993. this.renderList = new BABYLON.SmartArray(32);
  87994. this._vertexBuffers = {};
  87995. this._scene = scene;
  87996. }
  87997. BoundingBoxRenderer.prototype._prepareRessources = function () {
  87998. if (this._colorShader) {
  87999. return;
  88000. }
  88001. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  88002. attributes: [BABYLON.VertexBuffer.PositionKind],
  88003. uniforms: ["world", "viewProjection", "color"]
  88004. });
  88005. var engine = this._scene.getEngine();
  88006. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88007. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88008. this._createIndexBuffer();
  88009. };
  88010. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88011. var engine = this._scene.getEngine();
  88012. 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]);
  88013. };
  88014. BoundingBoxRenderer.prototype._rebuild = function () {
  88015. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88016. if (vb) {
  88017. vb._rebuild();
  88018. }
  88019. this._createIndexBuffer();
  88020. };
  88021. BoundingBoxRenderer.prototype.reset = function () {
  88022. this.renderList.reset();
  88023. };
  88024. BoundingBoxRenderer.prototype.render = function () {
  88025. if (this.renderList.length === 0) {
  88026. return;
  88027. }
  88028. this._prepareRessources();
  88029. if (!this._colorShader.isReady()) {
  88030. return;
  88031. }
  88032. var engine = this._scene.getEngine();
  88033. engine.setDepthWrite(false);
  88034. this._colorShader._preBind();
  88035. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88036. var boundingBox = this.renderList.data[boundingBoxIndex];
  88037. var min = boundingBox.minimum;
  88038. var max = boundingBox.maximum;
  88039. var diff = max.subtract(min);
  88040. var median = min.add(diff.scale(0.5));
  88041. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88042. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88043. .multiply(boundingBox.getWorldMatrix());
  88044. // VBOs
  88045. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88046. if (this.showBackLines) {
  88047. // Back
  88048. engine.setDepthFunctionToGreaterOrEqual();
  88049. this._scene.resetCachedMaterial();
  88050. this._colorShader.setColor4("color", this.backColor.toColor4());
  88051. this._colorShader.bind(worldMatrix);
  88052. // Draw order
  88053. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88054. }
  88055. // Front
  88056. engine.setDepthFunctionToLess();
  88057. this._scene.resetCachedMaterial();
  88058. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88059. this._colorShader.bind(worldMatrix);
  88060. // Draw order
  88061. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88062. }
  88063. this._colorShader.unbind();
  88064. engine.setDepthFunctionToLessOrEqual();
  88065. engine.setDepthWrite(true);
  88066. };
  88067. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88068. this._prepareRessources();
  88069. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88070. return;
  88071. }
  88072. var engine = this._scene.getEngine();
  88073. engine.setDepthWrite(false);
  88074. engine.setColorWrite(false);
  88075. this._colorShader._preBind();
  88076. var boundingBox = mesh._boundingInfo.boundingBox;
  88077. var min = boundingBox.minimum;
  88078. var max = boundingBox.maximum;
  88079. var diff = max.subtract(min);
  88080. var median = min.add(diff.scale(0.5));
  88081. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88082. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88083. .multiply(boundingBox.getWorldMatrix());
  88084. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88085. engine.setDepthFunctionToLess();
  88086. this._scene.resetCachedMaterial();
  88087. this._colorShader.bind(worldMatrix);
  88088. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88089. this._colorShader.unbind();
  88090. engine.setDepthFunctionToLessOrEqual();
  88091. engine.setDepthWrite(true);
  88092. engine.setColorWrite(true);
  88093. };
  88094. BoundingBoxRenderer.prototype.dispose = function () {
  88095. if (!this._colorShader) {
  88096. return;
  88097. }
  88098. this.renderList.dispose();
  88099. this._colorShader.dispose();
  88100. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88101. if (buffer) {
  88102. buffer.dispose();
  88103. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88104. }
  88105. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88106. };
  88107. return BoundingBoxRenderer;
  88108. }());
  88109. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88110. })(BABYLON || (BABYLON = {}));
  88111. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88112. var BABYLON;
  88113. (function (BABYLON) {
  88114. /**
  88115. * Renders a layer on top of an existing scene
  88116. */
  88117. var UtilityLayerRenderer = /** @class */ (function () {
  88118. /**
  88119. * Instantiates a UtilityLayerRenderer
  88120. * @param originalScene the original scene that will be rendered on top of
  88121. */
  88122. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88123. var _this = this;
  88124. this.originalScene = originalScene;
  88125. this._pointerCaptures = {};
  88126. this._lastPointerEvents = {};
  88127. /**
  88128. * If the utility layer should automatically be rendered on top of existing scene
  88129. */
  88130. this.shouldRender = true;
  88131. /**
  88132. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88133. */
  88134. this.onlyCheckPointerDownEvents = true;
  88135. /**
  88136. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88137. */
  88138. this.processAllEvents = false;
  88139. /**
  88140. * Observable raised when the pointer move from the utility layer scene to the main scene
  88141. */
  88142. this.onPointerOutObservable = new BABYLON.Observable();
  88143. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88144. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88145. originalScene.getEngine().scenes.pop();
  88146. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88147. this.utilityLayerScene.detachControl();
  88148. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88149. if (!_this.processAllEvents) {
  88150. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88151. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88152. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88153. return;
  88154. }
  88155. }
  88156. var pointerEvent = (prePointerInfo.event);
  88157. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88158. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88159. return;
  88160. }
  88161. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88162. if (!prePointerInfo.ray && utilityScenePick) {
  88163. prePointerInfo.ray = utilityScenePick.ray;
  88164. }
  88165. // always fire the prepointer oversvable
  88166. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88167. // allow every non pointer down event to flow to the utility layer
  88168. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88169. if (!prePointerInfo.skipOnPointerObservable) {
  88170. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88171. }
  88172. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88173. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88174. }
  88175. return;
  88176. }
  88177. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88178. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88179. if (utilityScenePick && utilityScenePick.hit) {
  88180. if (!prePointerInfo.skipOnPointerObservable) {
  88181. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88182. }
  88183. prePointerInfo.skipOnPointerObservable = true;
  88184. }
  88185. }
  88186. else {
  88187. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88188. var pointerEvent_1 = (prePointerInfo.event);
  88189. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88190. if (originalScenePick && utilityScenePick) {
  88191. // No pick in utility scene
  88192. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88193. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88194. // We touched an utility mesh present in the main scene
  88195. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88196. prePointerInfo.skipOnPointerObservable = true;
  88197. }
  88198. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88199. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88200. }
  88201. }
  88202. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88203. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88204. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88205. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88206. }
  88207. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88208. // We have a pick in both scenes but main is closer than utility
  88209. // We touched an utility mesh present in the main scene
  88210. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88211. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88212. prePointerInfo.skipOnPointerObservable = true;
  88213. }
  88214. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88215. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88216. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88217. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88218. }
  88219. }
  88220. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88221. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88222. }
  88223. }
  88224. }
  88225. });
  88226. // Render directly on top of existing scene without clearing
  88227. this.utilityLayerScene.autoClear = false;
  88228. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88229. if (_this.shouldRender) {
  88230. _this.render();
  88231. }
  88232. });
  88233. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88234. _this.dispose();
  88235. });
  88236. this._updateCamera();
  88237. }
  88238. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88239. get: function () {
  88240. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88241. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88242. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88243. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88244. });
  88245. }
  88246. return UtilityLayerRenderer._DefaultUtilityLayer;
  88247. },
  88248. enumerable: true,
  88249. configurable: true
  88250. });
  88251. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88252. if (!prePointerInfo.skipOnPointerObservable) {
  88253. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88254. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88255. }
  88256. };
  88257. /**
  88258. * Renders the utility layers scene on top of the original scene
  88259. */
  88260. UtilityLayerRenderer.prototype.render = function () {
  88261. this._updateCamera();
  88262. this.utilityLayerScene.render(false);
  88263. };
  88264. /**
  88265. * Disposes of the renderer
  88266. */
  88267. UtilityLayerRenderer.prototype.dispose = function () {
  88268. this.onPointerOutObservable.clear();
  88269. if (this._afterRenderObserver) {
  88270. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88271. }
  88272. if (this._sceneDisposeObserver) {
  88273. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88274. }
  88275. if (this._originalPointerObserver) {
  88276. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88277. }
  88278. this.utilityLayerScene.dispose();
  88279. };
  88280. UtilityLayerRenderer.prototype._updateCamera = function () {
  88281. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88282. };
  88283. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88284. return UtilityLayerRenderer;
  88285. }());
  88286. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88287. })(BABYLON || (BABYLON = {}));
  88288. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88289. //# sourceMappingURL=babylon.behavior.js.map
  88290. var BABYLON;
  88291. (function (BABYLON) {
  88292. /**
  88293. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88294. */
  88295. var PointerDragBehavior = /** @class */ (function () {
  88296. /**
  88297. * Creates a pointer drag behavior that can be attached to a mesh
  88298. * @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)
  88299. */
  88300. function PointerDragBehavior(options) {
  88301. this.options = options;
  88302. /**
  88303. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88304. */
  88305. this.currentDraggingPointerID = -1;
  88306. /**
  88307. * If the behavior is currently in a dragging state
  88308. */
  88309. this.dragging = false;
  88310. /**
  88311. * 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)
  88312. */
  88313. this.dragDeltaRatio = 0.2;
  88314. /**
  88315. * If the drag plane orientation should be updated during the dragging (Default: true)
  88316. */
  88317. this.updateDragPlane = true;
  88318. // Debug mode will display drag planes to help visualize behavior
  88319. this._debugMode = false;
  88320. this._moving = false;
  88321. /**
  88322. * Fires each time the attached mesh is dragged with the pointer
  88323. * * delta between last drag position and current drag position in world space
  88324. * * dragDistance along the drag axis
  88325. * * dragPlaneNormal normal of the current drag plane used during the drag
  88326. * * dragPlanePoint in world space where the drag intersects the drag plane
  88327. */
  88328. this.onDragObservable = new BABYLON.Observable();
  88329. /**
  88330. * Fires each time a drag begins (eg. mouse down on mesh)
  88331. */
  88332. this.onDragStartObservable = new BABYLON.Observable();
  88333. /**
  88334. * Fires each time a drag ends (eg. mouse release after drag)
  88335. */
  88336. this.onDragEndObservable = new BABYLON.Observable();
  88337. /**
  88338. * If the attached mesh should be moved when dragged
  88339. */
  88340. this.moveAttached = true;
  88341. /**
  88342. * If the drag behavior will react to drag events (Default: true)
  88343. */
  88344. this.enabled = true;
  88345. /**
  88346. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88347. */
  88348. this.useObjectOrienationForDragging = true;
  88349. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88350. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88351. // Variables to avoid instantiation in the below method
  88352. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88353. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88354. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88355. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88356. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88357. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88358. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88359. var optionCount = 0;
  88360. if (options === undefined) {
  88361. options = {};
  88362. }
  88363. if (options.dragAxis) {
  88364. optionCount++;
  88365. }
  88366. if (options.dragPlaneNormal) {
  88367. optionCount++;
  88368. }
  88369. if (optionCount > 1) {
  88370. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88371. }
  88372. }
  88373. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88374. /**
  88375. * The name of the behavior
  88376. */
  88377. get: function () {
  88378. return "PointerDrag";
  88379. },
  88380. enumerable: true,
  88381. configurable: true
  88382. });
  88383. /**
  88384. * Initializes the behavior
  88385. */
  88386. PointerDragBehavior.prototype.init = function () { };
  88387. /**
  88388. * Attaches the drag behavior the passed in mesh
  88389. * @param ownerNode The mesh that will be dragged around once attached
  88390. */
  88391. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88392. var _this = this;
  88393. this._scene = ownerNode.getScene();
  88394. this._attachedNode = ownerNode;
  88395. // Initialize drag plane to not interfere with existing scene
  88396. if (!PointerDragBehavior._planeScene) {
  88397. if (this._debugMode) {
  88398. PointerDragBehavior._planeScene = this._scene;
  88399. }
  88400. else {
  88401. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88402. this._scene.getEngine().scenes.pop();
  88403. }
  88404. }
  88405. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88406. // State of the drag
  88407. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88408. var delta = new BABYLON.Vector3(0, 0, 0);
  88409. var dragLength = 0;
  88410. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88411. var pickPredicate = function (m) {
  88412. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88413. };
  88414. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88415. if (!_this.enabled) {
  88416. return;
  88417. }
  88418. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88419. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88420. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88421. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88422. if (pickedPoint) {
  88423. _this.dragging = true;
  88424. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88425. _this.lastDragPosition.copyFrom(pickedPoint);
  88426. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88427. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88428. }
  88429. }
  88430. }
  88431. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88432. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88433. _this.releaseDrag();
  88434. }
  88435. }
  88436. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88437. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88438. _this._moving = true;
  88439. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88440. if (pickedPoint) {
  88441. if (_this.updateDragPlane) {
  88442. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88443. }
  88444. // depending on the drag mode option drag accordingly
  88445. if (_this.options.dragAxis) {
  88446. // Convert local drag axis to world
  88447. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88448. // Project delta drag from the drag plane onto the drag axis
  88449. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88450. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88451. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88452. }
  88453. else {
  88454. dragLength = delta.length();
  88455. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88456. }
  88457. targetPosition.addInPlace(delta);
  88458. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88459. _this.lastDragPosition.copyFrom(pickedPoint);
  88460. }
  88461. }
  88462. }
  88463. });
  88464. this._scene.onBeforeRenderObservable.add(function () {
  88465. if (_this._moving && _this.moveAttached) {
  88466. // Slowly move mesh to avoid jitter
  88467. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88468. _this._tmpVector.scaleInPlace(0.2);
  88469. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88470. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88471. }
  88472. });
  88473. };
  88474. PointerDragBehavior.prototype.releaseDrag = function () {
  88475. this.dragging = false;
  88476. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88477. this.currentDraggingPointerID = -1;
  88478. this._moving = false;
  88479. };
  88480. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88481. var _this = this;
  88482. if (!ray) {
  88483. return null;
  88484. }
  88485. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88486. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88487. return pickResult.pickedPoint;
  88488. }
  88489. else {
  88490. return null;
  88491. }
  88492. };
  88493. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88494. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88495. this._pointA.copyFrom(dragPlanePosition);
  88496. if (this.options.dragAxis) {
  88497. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88498. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88499. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88500. ray.origin.subtractToRef(this._pointA, this._pointC);
  88501. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88502. // Get perpendicular line from direction to camera and drag axis
  88503. this._pointB.subtractToRef(this._pointA, this._lineA);
  88504. this._pointC.subtractToRef(this._pointA, this._lineB);
  88505. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88506. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88507. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88508. this._lookAt.normalize();
  88509. this._dragPlane.position.copyFrom(this._pointA);
  88510. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88511. this._dragPlane.lookAt(this._lookAt);
  88512. }
  88513. else if (this.options.dragPlaneNormal) {
  88514. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88515. this._dragPlane.position.copyFrom(this._pointA);
  88516. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88517. this._dragPlane.lookAt(this._lookAt);
  88518. }
  88519. else {
  88520. this._dragPlane.position.copyFrom(this._pointA);
  88521. this._dragPlane.lookAt(ray.origin);
  88522. }
  88523. this._dragPlane.computeWorldMatrix(true);
  88524. };
  88525. /**
  88526. * Detaches the behavior from the mesh
  88527. */
  88528. PointerDragBehavior.prototype.detach = function () {
  88529. if (this._pointerObserver) {
  88530. this._scene.onPointerObservable.remove(this._pointerObserver);
  88531. }
  88532. };
  88533. return PointerDragBehavior;
  88534. }());
  88535. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88536. })(BABYLON || (BABYLON = {}));
  88537. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88538. var BABYLON;
  88539. (function (BABYLON) {
  88540. /**
  88541. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88542. */
  88543. var MultiPointerScaleBehavior = /** @class */ (function () {
  88544. function MultiPointerScaleBehavior() {
  88545. this._startDistance = 0;
  88546. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88547. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88548. this._sceneRenderObserver = null;
  88549. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88550. this._dragBehaviorA.moveAttached = false;
  88551. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88552. this._dragBehaviorB.moveAttached = false;
  88553. }
  88554. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88555. /**
  88556. * The name of the behavior
  88557. */
  88558. get: function () {
  88559. return "MultiPointerScale";
  88560. },
  88561. enumerable: true,
  88562. configurable: true
  88563. });
  88564. /**
  88565. * Initializes the behavior
  88566. */
  88567. MultiPointerScaleBehavior.prototype.init = function () { };
  88568. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88569. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88570. };
  88571. /**
  88572. * Attaches the scale behavior the passed in mesh
  88573. * @param ownerNode The mesh that will be scaled around once attached
  88574. */
  88575. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88576. var _this = this;
  88577. this._ownerNode = ownerNode;
  88578. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88579. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88580. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88581. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88582. _this._dragBehaviorA.releaseDrag();
  88583. }
  88584. else {
  88585. _this._initialScale.copyFrom(ownerNode.scaling);
  88586. _this._startDistance = _this._getCurrentDistance();
  88587. }
  88588. }
  88589. });
  88590. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88591. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88592. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88593. _this._dragBehaviorB.releaseDrag();
  88594. }
  88595. else {
  88596. _this._initialScale.copyFrom(ownerNode.scaling);
  88597. _this._startDistance = _this._getCurrentDistance();
  88598. }
  88599. }
  88600. });
  88601. // Once both drag behaviors are active scale based on the distance between the two pointers
  88602. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88603. behavior.onDragObservable.add(function () {
  88604. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88605. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88606. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88607. }
  88608. });
  88609. });
  88610. ownerNode.addBehavior(this._dragBehaviorA);
  88611. ownerNode.addBehavior(this._dragBehaviorB);
  88612. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88613. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88614. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88615. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88616. if (change.length() > 0.01) {
  88617. ownerNode.scaling.addInPlace(change);
  88618. }
  88619. }
  88620. });
  88621. };
  88622. /**
  88623. * Detaches the behavior from the mesh
  88624. */
  88625. MultiPointerScaleBehavior.prototype.detach = function () {
  88626. var _this = this;
  88627. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88628. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88629. behavior.onDragStartObservable.clear();
  88630. behavior.onDragObservable.clear();
  88631. _this._ownerNode.removeBehavior(behavior);
  88632. });
  88633. };
  88634. return MultiPointerScaleBehavior;
  88635. }());
  88636. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88637. })(BABYLON || (BABYLON = {}));
  88638. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88639. var BABYLON;
  88640. (function (BABYLON) {
  88641. /**
  88642. * 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
  88643. */
  88644. var SixDofDragBehavior = /** @class */ (function () {
  88645. function SixDofDragBehavior() {
  88646. this._sceneRenderObserver = null;
  88647. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88648. this._moving = false;
  88649. this._startingOrientation = new BABYLON.Quaternion();
  88650. /**
  88651. * 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)
  88652. */
  88653. this.zDragFactor = 5;
  88654. /**
  88655. * If the behavior is currently in a dragging state
  88656. */
  88657. this.dragging = false;
  88658. /**
  88659. * 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)
  88660. */
  88661. this.dragDeltaRatio = 0.2;
  88662. /**
  88663. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88664. */
  88665. this.currentDraggingPointerID = -1;
  88666. }
  88667. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88668. /**
  88669. * The name of the behavior
  88670. */
  88671. get: function () {
  88672. return "SixDofDrag";
  88673. },
  88674. enumerable: true,
  88675. configurable: true
  88676. });
  88677. /**
  88678. * Initializes the behavior
  88679. */
  88680. SixDofDragBehavior.prototype.init = function () { };
  88681. /**
  88682. * Attaches the scale behavior the passed in mesh
  88683. * @param ownerNode The mesh that will be scaled around once attached
  88684. */
  88685. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88686. var _this = this;
  88687. this._ownerNode = ownerNode;
  88688. this._scene = this._ownerNode.getScene();
  88689. if (!SixDofDragBehavior._virtualScene) {
  88690. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88691. this._scene.getEngine().scenes.pop();
  88692. }
  88693. var pickedMesh = null;
  88694. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88695. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88696. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88697. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88698. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88699. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88700. var pickPredicate = function (m) {
  88701. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88702. };
  88703. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88704. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88705. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88706. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88707. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88708. // Set position and orientation of the controller
  88709. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88710. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88711. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88712. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88713. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88714. if (!pickedMesh.rotationQuaternion) {
  88715. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88716. }
  88717. var oldParent = pickedMesh.parent;
  88718. pickedMesh.setParent(null);
  88719. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88720. pickedMesh.setParent(oldParent);
  88721. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88722. // Update state
  88723. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88724. _this.dragging = true;
  88725. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88726. }
  88727. }
  88728. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88729. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88730. _this.dragging = false;
  88731. _this._moving = false;
  88732. _this.currentDraggingPointerID = -1;
  88733. pickedMesh = null;
  88734. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88735. }
  88736. }
  88737. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88738. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88739. // Calculate controller drag distance in controller space
  88740. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88741. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88742. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88743. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88744. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88745. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88746. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88747. if (_this._virtualDragMesh.position.z < 0) {
  88748. _this._virtualDragMesh.position.z = 0;
  88749. }
  88750. // Update the controller position
  88751. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88752. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88753. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88754. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88755. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88756. if (pickedMesh.parent) {
  88757. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88758. }
  88759. if (!_this._moving) {
  88760. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88761. }
  88762. _this._moving = true;
  88763. }
  88764. }
  88765. });
  88766. var tmpQuaternion = new BABYLON.Quaternion();
  88767. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88768. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88769. if (_this.dragging && _this._moving && pickedMesh) {
  88770. // Slowly move mesh to avoid jitter
  88771. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88772. // Get change in rotation
  88773. tmpQuaternion.copyFrom(_this._startingOrientation);
  88774. tmpQuaternion.x = -tmpQuaternion.x;
  88775. tmpQuaternion.y = -tmpQuaternion.y;
  88776. tmpQuaternion.z = -tmpQuaternion.z;
  88777. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88778. // Convert change in rotation to only y axis rotation
  88779. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88780. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88781. // Slowly move mesh to avoid jitter
  88782. var oldParent = pickedMesh.parent;
  88783. pickedMesh.setParent(null);
  88784. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88785. pickedMesh.setParent(oldParent);
  88786. }
  88787. });
  88788. };
  88789. /**
  88790. * Detaches the behavior from the mesh
  88791. */
  88792. SixDofDragBehavior.prototype.detach = function () {
  88793. this._scene.onPointerObservable.remove(this._pointerObserver);
  88794. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88795. this._virtualOriginMesh.dispose();
  88796. this._virtualDragMesh.dispose();
  88797. };
  88798. return SixDofDragBehavior;
  88799. }());
  88800. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88801. })(BABYLON || (BABYLON = {}));
  88802. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88803. var BABYLON;
  88804. (function (BABYLON) {
  88805. /**
  88806. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88807. */
  88808. var Gizmo = /** @class */ (function () {
  88809. /**
  88810. * Creates a gizmo
  88811. * @param gizmoLayer The utility layer the gizmo will be added to
  88812. */
  88813. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88814. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  88815. var _this = this;
  88816. this.gizmoLayer = gizmoLayer;
  88817. /**
  88818. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88819. */
  88820. this.updateGizmoRotationToMatchAttachedMesh = true;
  88821. /**
  88822. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88823. */
  88824. this.updateGizmoPositionToMatchAttachedMesh = true;
  88825. /**
  88826. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88827. */
  88828. this._updateScale = true;
  88829. this._interactionsEnabled = true;
  88830. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  88831. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  88832. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  88833. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  88834. _this._rootMesh.scaling.set(dist, dist, dist);
  88835. }
  88836. if (_this.attachedMesh) {
  88837. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  88838. if (!_this._rootMesh.rotationQuaternion) {
  88839. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  88840. }
  88841. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  88842. }
  88843. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  88844. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  88845. }
  88846. }
  88847. });
  88848. this.attachedMesh = null;
  88849. }
  88850. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  88851. /**
  88852. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  88853. * * When set, interactions will be enabled
  88854. */
  88855. get: function () {
  88856. return this._attachedMesh;
  88857. },
  88858. set: function (value) {
  88859. this._attachedMesh = value;
  88860. this._rootMesh.setEnabled(value ? true : false);
  88861. this._attachedMeshChanged(value);
  88862. },
  88863. enumerable: true,
  88864. configurable: true
  88865. });
  88866. Gizmo.prototype._attachedMeshChanged = function (value) {
  88867. };
  88868. /**
  88869. * Disposes of the gizmo
  88870. */
  88871. Gizmo.prototype.dispose = function () {
  88872. this._rootMesh.dispose();
  88873. if (this._beforeRenderObserver) {
  88874. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  88875. }
  88876. };
  88877. return Gizmo;
  88878. }());
  88879. BABYLON.Gizmo = Gizmo;
  88880. })(BABYLON || (BABYLON = {}));
  88881. //# sourceMappingURL=babylon.gizmo.js.map
  88882. var BABYLON;
  88883. (function (BABYLON) {
  88884. /**
  88885. * Single axis drag gizmo
  88886. */
  88887. var AxisDragGizmo = /** @class */ (function (_super) {
  88888. __extends(AxisDragGizmo, _super);
  88889. /**
  88890. * Creates an AxisDragGizmo
  88891. * @param gizmoLayer The utility layer the gizmo will be added to
  88892. * @param dragAxis The axis which the gizmo will be able to drag on
  88893. * @param color The color of the gizmo
  88894. */
  88895. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  88896. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  88897. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  88898. var _this = _super.call(this, gizmoLayer) || this;
  88899. _this._pointerObserver = null;
  88900. /**
  88901. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  88902. */
  88903. _this.snapDistance = 0;
  88904. /**
  88905. * Event that fires each time the gizmo snaps to a new location.
  88906. * * snapDistance is the the change in distance
  88907. */
  88908. _this.onSnapObservable = new BABYLON.Observable();
  88909. // Create Material
  88910. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88911. coloredMaterial.disableLighting = true;
  88912. coloredMaterial.emissiveColor = color;
  88913. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  88914. hoverMaterial.disableLighting = true;
  88915. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  88916. // Build mesh on root node
  88917. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  88918. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88919. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  88920. arrow.addChild(arrowMesh);
  88921. arrow.addChild(arrowTail);
  88922. // Position arrow pointing in its drag axis
  88923. arrowMesh.scaling.scaleInPlace(0.05);
  88924. arrowMesh.material = coloredMaterial;
  88925. arrowMesh.rotation.x = Math.PI / 2;
  88926. arrowMesh.position.z += 0.3;
  88927. arrowTail.rotation.x = Math.PI / 2;
  88928. arrowTail.material = coloredMaterial;
  88929. arrowTail.position.z += 0.15;
  88930. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  88931. _this._rootMesh.addChild(arrow);
  88932. var currentSnapDragDistance = 0;
  88933. var tmpVector = new BABYLON.Vector3();
  88934. var tmpSnapEvent = { snapDistance: 0 };
  88935. // Add drag behavior to handle events when the gizmo is dragged
  88936. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  88937. _this._dragBehavior.moveAttached = false;
  88938. _this._rootMesh.addBehavior(_this._dragBehavior);
  88939. _this._dragBehavior.onDragObservable.add(function (event) {
  88940. if (_this.attachedMesh) {
  88941. // Snapping logic
  88942. if (_this.snapDistance == 0) {
  88943. _this.attachedMesh.position.addInPlace(event.delta);
  88944. }
  88945. else {
  88946. currentSnapDragDistance += event.dragDistance;
  88947. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  88948. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  88949. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  88950. event.delta.normalizeToRef(tmpVector);
  88951. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  88952. _this.attachedMesh.position.addInPlace(tmpVector);
  88953. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  88954. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  88955. }
  88956. }
  88957. }
  88958. });
  88959. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  88960. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  88961. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88962. m.material = hoverMaterial;
  88963. });
  88964. }
  88965. else {
  88966. _this._rootMesh.getChildMeshes().forEach(function (m) {
  88967. m.material = coloredMaterial;
  88968. });
  88969. }
  88970. });
  88971. return _this;
  88972. }
  88973. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  88974. if (this._dragBehavior) {
  88975. this._dragBehavior.enabled = value ? true : false;
  88976. }
  88977. };
  88978. /**
  88979. * Disposes of the gizmo
  88980. */
  88981. AxisDragGizmo.prototype.dispose = function () {
  88982. this.onSnapObservable.clear();
  88983. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  88984. this._dragBehavior.detach();
  88985. _super.prototype.dispose.call(this);
  88986. };
  88987. return AxisDragGizmo;
  88988. }(BABYLON.Gizmo));
  88989. BABYLON.AxisDragGizmo = AxisDragGizmo;
  88990. })(BABYLON || (BABYLON = {}));
  88991. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  88992. var BABYLON;
  88993. (function (BABYLON) {
  88994. /**
  88995. * Single axis scale gizmo
  88996. */
  88997. var AxisScaleGizmo = /** @class */ (function (_super) {
  88998. __extends(AxisScaleGizmo, _super);
  88999. /**
  89000. * Creates an AxisScaleGizmo
  89001. * @param gizmoLayer The utility layer the gizmo will be added to
  89002. * @param dragAxis The axis which the gizmo will be able to scale on
  89003. * @param color The color of the gizmo
  89004. */
  89005. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89006. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89007. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89008. var _this = _super.call(this, gizmoLayer) || this;
  89009. _this._pointerObserver = null;
  89010. /**
  89011. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89012. */
  89013. _this.snapDistance = 0;
  89014. /**
  89015. * Event that fires each time the gizmo snaps to a new location.
  89016. * * snapDistance is the the change in distance
  89017. */
  89018. _this.onSnapObservable = new BABYLON.Observable();
  89019. // Create Material
  89020. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89021. coloredMaterial.disableLighting = true;
  89022. coloredMaterial.emissiveColor = color;
  89023. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89024. hoverMaterial.disableLighting = true;
  89025. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89026. // Build mesh on root node
  89027. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89028. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89029. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89030. arrow.addChild(arrowMesh);
  89031. arrow.addChild(arrowTail);
  89032. // Position arrow pointing in its drag axis
  89033. arrowMesh.scaling.scaleInPlace(0.1);
  89034. arrowMesh.material = coloredMaterial;
  89035. arrowMesh.rotation.x = Math.PI / 2;
  89036. arrowMesh.position.z += 0.3;
  89037. arrowTail.rotation.x = Math.PI / 2;
  89038. arrowTail.material = coloredMaterial;
  89039. arrowTail.position.z += 0.15;
  89040. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89041. _this._rootMesh.addChild(arrow);
  89042. // Add drag behavior to handle events when the gizmo is dragged
  89043. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89044. _this._dragBehavior.moveAttached = false;
  89045. _this._rootMesh.addBehavior(_this._dragBehavior);
  89046. var currentSnapDragDistance = 0;
  89047. var tmpVector = new BABYLON.Vector3();
  89048. var tmpSnapEvent = { snapDistance: 0 };
  89049. _this._dragBehavior.onDragObservable.add(function (event) {
  89050. if (_this.attachedMesh) {
  89051. // Snapping logic
  89052. var snapped = false;
  89053. var dragSteps = 0;
  89054. if (_this.snapDistance == 0) {
  89055. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89056. }
  89057. else {
  89058. currentSnapDragDistance += event.dragDistance;
  89059. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89060. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89061. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89062. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89063. snapped = true;
  89064. }
  89065. else {
  89066. tmpVector.scaleInPlace(0);
  89067. }
  89068. }
  89069. var invertCount = 0;
  89070. if (_this.attachedMesh.scaling["x"] < 0) {
  89071. invertCount++;
  89072. }
  89073. if (_this.attachedMesh.scaling["y"] < 0) {
  89074. invertCount++;
  89075. }
  89076. if (_this.attachedMesh.scaling["z"] < 0) {
  89077. invertCount++;
  89078. }
  89079. if (invertCount % 2 == 0) {
  89080. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89081. }
  89082. else {
  89083. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  89084. }
  89085. if (snapped) {
  89086. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89087. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89088. }
  89089. }
  89090. });
  89091. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89092. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89093. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89094. m.material = hoverMaterial;
  89095. });
  89096. }
  89097. else {
  89098. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89099. m.material = coloredMaterial;
  89100. });
  89101. }
  89102. });
  89103. return _this;
  89104. }
  89105. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89106. if (this._dragBehavior) {
  89107. this._dragBehavior.enabled = value ? true : false;
  89108. }
  89109. };
  89110. /**
  89111. * Disposes of the gizmo
  89112. */
  89113. AxisScaleGizmo.prototype.dispose = function () {
  89114. this.onSnapObservable.clear();
  89115. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89116. this._dragBehavior.detach();
  89117. _super.prototype.dispose.call(this);
  89118. };
  89119. return AxisScaleGizmo;
  89120. }(BABYLON.Gizmo));
  89121. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89122. })(BABYLON || (BABYLON = {}));
  89123. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89124. var BABYLON;
  89125. (function (BABYLON) {
  89126. /**
  89127. * Single plane rotation gizmo
  89128. */
  89129. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89130. __extends(PlaneRotationGizmo, _super);
  89131. /**
  89132. * Creates a PlaneRotationGizmo
  89133. * @param gizmoLayer The utility layer the gizmo will be added to
  89134. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89135. * @param color The color of the gizmo
  89136. */
  89137. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89138. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89139. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89140. var _this = _super.call(this, gizmoLayer) || this;
  89141. _this._pointerObserver = null;
  89142. /**
  89143. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89144. */
  89145. _this.snapDistance = 0;
  89146. /**
  89147. * Event that fires each time the gizmo snaps to a new location.
  89148. * * snapDistance is the the change in distance
  89149. */
  89150. _this.onSnapObservable = new BABYLON.Observable();
  89151. // Create Material
  89152. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89153. coloredMaterial.disableLighting = true;
  89154. coloredMaterial.emissiveColor = color;
  89155. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89156. hoverMaterial.disableLighting = true;
  89157. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89158. // Build mesh on root node
  89159. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89160. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89161. // Position arrow pointing in its drag axis
  89162. rotationMesh.scaling.scaleInPlace(0.1);
  89163. rotationMesh.material = coloredMaterial;
  89164. rotationMesh.rotation.x = Math.PI / 2;
  89165. parentMesh.addChild(rotationMesh);
  89166. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89167. _this._rootMesh.addChild(parentMesh);
  89168. // Add drag behavior to handle events when the gizmo is dragged
  89169. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89170. _this._dragBehavior.moveAttached = false;
  89171. _this._rootMesh.addBehavior(_this._dragBehavior);
  89172. var lastDragPosition = null;
  89173. _this._dragBehavior.onDragStartObservable.add(function (e) {
  89174. if (_this.attachedMesh) {
  89175. lastDragPosition = e.dragPlanePoint;
  89176. }
  89177. });
  89178. var rotationMatrix = new BABYLON.Matrix();
  89179. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89180. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89181. var tmpSnapEvent = { snapDistance: 0 };
  89182. var currentSnapDragDistance = 0;
  89183. _this._dragBehavior.onDragObservable.add(function (event) {
  89184. if (_this.attachedMesh && lastDragPosition) {
  89185. if (!_this.attachedMesh.rotationQuaternion) {
  89186. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  89187. }
  89188. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89189. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89190. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89191. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89192. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89193. var angle = Math.atan2(cross.length(), dot);
  89194. planeNormalTowardsCamera.copyFrom(planeNormal);
  89195. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89196. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89197. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89198. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89199. }
  89200. // Flip up vector depending on which side the camera is on
  89201. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89202. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89203. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89204. planeNormalTowardsCamera.scaleInPlace(-1);
  89205. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89206. }
  89207. }
  89208. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89209. if (halfCircleSide)
  89210. angle = -angle;
  89211. // Snapping logic
  89212. var snapped = false;
  89213. if (_this.snapDistance != 0) {
  89214. currentSnapDragDistance += angle;
  89215. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89216. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89217. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89218. angle = _this.snapDistance * dragSteps;
  89219. snapped = true;
  89220. }
  89221. else {
  89222. angle = 0;
  89223. }
  89224. }
  89225. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89226. var quaternionCoefficient = Math.sin(angle / 2);
  89227. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89228. // Rotate selected mesh quaternion over fixed axis
  89229. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89230. lastDragPosition = event.dragPlanePoint;
  89231. if (snapped) {
  89232. tmpSnapEvent.snapDistance = angle;
  89233. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89234. }
  89235. }
  89236. });
  89237. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89238. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89239. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89240. m.material = hoverMaterial;
  89241. });
  89242. }
  89243. else {
  89244. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89245. m.material = coloredMaterial;
  89246. });
  89247. }
  89248. });
  89249. return _this;
  89250. }
  89251. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89252. if (this._dragBehavior) {
  89253. this._dragBehavior.enabled = value ? true : false;
  89254. }
  89255. };
  89256. /**
  89257. * Disposes of the gizmo
  89258. */
  89259. PlaneRotationGizmo.prototype.dispose = function () {
  89260. this.onSnapObservable.clear();
  89261. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89262. this._dragBehavior.detach();
  89263. _super.prototype.dispose.call(this);
  89264. };
  89265. return PlaneRotationGizmo;
  89266. }(BABYLON.Gizmo));
  89267. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89268. })(BABYLON || (BABYLON = {}));
  89269. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89270. var BABYLON;
  89271. (function (BABYLON) {
  89272. /**
  89273. * Gizmo that enables dragging a mesh along 3 axis
  89274. */
  89275. var PositionGizmo = /** @class */ (function (_super) {
  89276. __extends(PositionGizmo, _super);
  89277. /**
  89278. * Creates a PositionGizmo
  89279. * @param gizmoLayer The utility layer the gizmo will be added to
  89280. */
  89281. function PositionGizmo(gizmoLayer) {
  89282. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89283. var _this = _super.call(this, gizmoLayer) || this;
  89284. _this._xDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89285. _this._yDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89286. _this._zDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89287. _this.attachedMesh = null;
  89288. return _this;
  89289. }
  89290. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89291. set: function (mesh) {
  89292. if (this._xDrag) {
  89293. this._xDrag.attachedMesh = mesh;
  89294. this._yDrag.attachedMesh = mesh;
  89295. this._zDrag.attachedMesh = mesh;
  89296. }
  89297. },
  89298. enumerable: true,
  89299. configurable: true
  89300. });
  89301. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89302. get: function () {
  89303. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89304. },
  89305. set: function (value) {
  89306. if (this._xDrag) {
  89307. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89308. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89309. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89310. }
  89311. },
  89312. enumerable: true,
  89313. configurable: true
  89314. });
  89315. /**
  89316. * Disposes of the gizmo
  89317. */
  89318. PositionGizmo.prototype.dispose = function () {
  89319. this._xDrag.dispose();
  89320. this._yDrag.dispose();
  89321. this._zDrag.dispose();
  89322. };
  89323. return PositionGizmo;
  89324. }(BABYLON.Gizmo));
  89325. BABYLON.PositionGizmo = PositionGizmo;
  89326. })(BABYLON || (BABYLON = {}));
  89327. //# sourceMappingURL=babylon.positionGizmo.js.map
  89328. var BABYLON;
  89329. (function (BABYLON) {
  89330. /**
  89331. * Gizmo that enables rotating a mesh along 3 axis
  89332. */
  89333. var RotationGizmo = /** @class */ (function (_super) {
  89334. __extends(RotationGizmo, _super);
  89335. /**
  89336. * Creates a RotationGizmo
  89337. * @param gizmoLayer The utility layer the gizmo will be added to
  89338. */
  89339. function RotationGizmo(gizmoLayer) {
  89340. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89341. var _this = _super.call(this, gizmoLayer) || this;
  89342. _this._xDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89343. _this._yDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89344. _this._zDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89345. _this.attachedMesh = null;
  89346. return _this;
  89347. }
  89348. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89349. set: function (mesh) {
  89350. if (this._xDrag) {
  89351. this._xDrag.attachedMesh = mesh;
  89352. this._yDrag.attachedMesh = mesh;
  89353. this._zDrag.attachedMesh = mesh;
  89354. }
  89355. },
  89356. enumerable: true,
  89357. configurable: true
  89358. });
  89359. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89360. get: function () {
  89361. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89362. },
  89363. set: function (value) {
  89364. if (this._xDrag) {
  89365. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89366. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89367. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89368. }
  89369. },
  89370. enumerable: true,
  89371. configurable: true
  89372. });
  89373. /**
  89374. * Disposes of the gizmo
  89375. */
  89376. RotationGizmo.prototype.dispose = function () {
  89377. this._xDrag.dispose();
  89378. this._yDrag.dispose();
  89379. this._zDrag.dispose();
  89380. };
  89381. return RotationGizmo;
  89382. }(BABYLON.Gizmo));
  89383. BABYLON.RotationGizmo = RotationGizmo;
  89384. })(BABYLON || (BABYLON = {}));
  89385. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89386. var BABYLON;
  89387. (function (BABYLON) {
  89388. /**
  89389. * Gizmo that enables scaling a mesh along 3 axis
  89390. */
  89391. var ScaleGizmo = /** @class */ (function (_super) {
  89392. __extends(ScaleGizmo, _super);
  89393. /**
  89394. * Creates a ScaleGizmo
  89395. * @param gizmoLayer The utility layer the gizmo will be added to
  89396. */
  89397. function ScaleGizmo(gizmoLayer) {
  89398. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89399. var _this = _super.call(this, gizmoLayer) || this;
  89400. _this._xDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89401. _this._yDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89402. _this._zDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89403. _this.attachedMesh = null;
  89404. return _this;
  89405. }
  89406. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89407. set: function (mesh) {
  89408. if (this._xDrag) {
  89409. this._xDrag.attachedMesh = mesh;
  89410. this._yDrag.attachedMesh = mesh;
  89411. this._zDrag.attachedMesh = mesh;
  89412. }
  89413. },
  89414. enumerable: true,
  89415. configurable: true
  89416. });
  89417. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89418. get: function () {
  89419. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89420. },
  89421. set: function (value) {
  89422. if (this._xDrag) {
  89423. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89424. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89425. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89426. }
  89427. },
  89428. enumerable: true,
  89429. configurable: true
  89430. });
  89431. /**
  89432. * Disposes of the gizmo
  89433. */
  89434. ScaleGizmo.prototype.dispose = function () {
  89435. this._xDrag.dispose();
  89436. this._yDrag.dispose();
  89437. this._zDrag.dispose();
  89438. };
  89439. return ScaleGizmo;
  89440. }(BABYLON.Gizmo));
  89441. BABYLON.ScaleGizmo = ScaleGizmo;
  89442. })(BABYLON || (BABYLON = {}));
  89443. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89444. var BABYLON;
  89445. (function (BABYLON) {
  89446. /**
  89447. * Bounding box gizmo
  89448. */
  89449. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89450. __extends(BoundingBoxGizmo, _super);
  89451. /**
  89452. * Creates an BoundingBoxGizmo
  89453. * @param gizmoLayer The utility layer the gizmo will be added to
  89454. * @param color The color of the gizmo
  89455. */
  89456. function BoundingBoxGizmo(color, gizmoLayer) {
  89457. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89458. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89459. var _this = _super.call(this, gizmoLayer) || this;
  89460. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89461. _this._renderObserver = null;
  89462. _this._pointerObserver = null;
  89463. _this._scaleDragSpeed = 0.2;
  89464. _this._tmpQuaternion = new BABYLON.Quaternion();
  89465. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89466. /**
  89467. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  89468. */
  89469. _this.rotationSphereSize = 0.1;
  89470. /**
  89471. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  89472. */
  89473. _this.scaleBoxSize = 0.1;
  89474. /**
  89475. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  89476. */
  89477. _this.fixedDragMeshScreenSize = false;
  89478. /**
  89479. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  89480. */
  89481. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  89482. /**
  89483. * Fired when a rotation sphere or scale box is dragged
  89484. */
  89485. _this.onDragStartObservable = new BABYLON.Observable();
  89486. /**
  89487. * Fired when a rotation sphere or scale box drag is started
  89488. */
  89489. _this.onDragObservable = new BABYLON.Observable();
  89490. /**
  89491. * Fired when a rotation sphere or scale box drag is needed
  89492. */
  89493. _this.onDragEndObservable = new BABYLON.Observable();
  89494. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89495. _this._updateScale = false;
  89496. // Create Materials
  89497. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89498. coloredMaterial.disableLighting = true;
  89499. coloredMaterial.emissiveColor = color;
  89500. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89501. hoverColoredMaterial.disableLighting = true;
  89502. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89503. // Build bounding box out of lines
  89504. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89505. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89506. var lines = [];
  89507. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89508. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89509. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89510. 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));
  89511. 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));
  89512. 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));
  89513. 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));
  89514. 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));
  89515. 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));
  89516. 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));
  89517. 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));
  89518. 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));
  89519. lines.forEach(function (l) {
  89520. l.color = color;
  89521. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89522. l.isPickable = false;
  89523. _this._lineBoundingBox.addChild(l);
  89524. });
  89525. _this._rootMesh.addChild(_this._lineBoundingBox);
  89526. // Create rotation spheres
  89527. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89528. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89529. var _loop_1 = function (i_1) {
  89530. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  89531. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89532. sphere.material = coloredMaterial;
  89533. // Drag behavior
  89534. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89535. _dragBehavior.moveAttached = false;
  89536. _dragBehavior.updateDragPlane = false;
  89537. sphere.addBehavior(_dragBehavior);
  89538. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89539. var totalTurnAmountOfDrag = 0;
  89540. _dragBehavior.onDragStartObservable.add(function (event) {
  89541. startingTurnDirection.copyFrom(sphere.forward);
  89542. totalTurnAmountOfDrag = 0;
  89543. });
  89544. _dragBehavior.onDragObservable.add(function (event) {
  89545. _this.onDragObservable.notifyObservers({});
  89546. if (_this.attachedMesh) {
  89547. var worldDragDirection = startingTurnDirection;
  89548. // Project the world right on to the drag plane
  89549. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89550. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89551. // project drag delta on to the resulting drag axis and rotate based on that
  89552. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89553. // Rotate based on axis
  89554. if (!_this.attachedMesh.rotationQuaternion) {
  89555. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89556. }
  89557. // Do not allow the object to turn more than a full circle
  89558. totalTurnAmountOfDrag += projectDist;
  89559. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89560. if (i_1 >= 8) {
  89561. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89562. }
  89563. else if (i_1 >= 4) {
  89564. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89565. }
  89566. else {
  89567. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89568. }
  89569. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89570. }
  89571. }
  89572. });
  89573. // Selection/deselection
  89574. _dragBehavior.onDragStartObservable.add(function () {
  89575. _this.onDragStartObservable.notifyObservers({});
  89576. _this._selectNode(sphere);
  89577. });
  89578. _dragBehavior.onDragEndObservable.add(function () {
  89579. _this.onDragEndObservable.notifyObservers({});
  89580. _this._selectNode(null);
  89581. });
  89582. this_1._rotateSpheresParent.addChild(sphere);
  89583. };
  89584. var this_1 = this, _dragBehavior;
  89585. for (var i_1 = 0; i_1 < 12; i_1++) {
  89586. _loop_1(i_1);
  89587. }
  89588. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89589. // Create scale cubes
  89590. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89591. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89592. for (var i = 0; i < 2; i++) {
  89593. for (var j = 0; j < 2; j++) {
  89594. var _loop_2 = function () {
  89595. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  89596. box.material = coloredMaterial;
  89597. // Dragging logic
  89598. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89599. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89600. _dragBehavior.moveAttached = false;
  89601. box.addBehavior(_dragBehavior);
  89602. _dragBehavior.onDragObservable.add(function (event) {
  89603. _this.onDragObservable.notifyObservers({});
  89604. if (_this.attachedMesh) {
  89605. // Current boudning box dimensions
  89606. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89607. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89608. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89609. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89610. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89611. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89612. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89613. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89614. // Update scale and position
  89615. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89616. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89617. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89618. }
  89619. });
  89620. // Selection/deselection
  89621. _dragBehavior.onDragStartObservable.add(function () {
  89622. _this.onDragStartObservable.notifyObservers({});
  89623. _this._selectNode(box);
  89624. });
  89625. _dragBehavior.onDragEndObservable.add(function () {
  89626. _this.onDragEndObservable.notifyObservers({});
  89627. _this._selectNode(null);
  89628. });
  89629. this_2._scaleBoxesParent.addChild(box);
  89630. };
  89631. var this_2 = this, _dragBehavior;
  89632. for (var k = 0; k < 2; k++) {
  89633. _loop_2();
  89634. }
  89635. }
  89636. }
  89637. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89638. // Hover color change
  89639. var pointerIds = new Array();
  89640. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89641. if (!pointerIds[pointerInfo.event.pointerId]) {
  89642. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89643. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89644. pointerIds[pointerInfo.event.pointerId] = mesh;
  89645. mesh.material = hoverColoredMaterial;
  89646. }
  89647. });
  89648. }
  89649. else {
  89650. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89651. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89652. delete pointerIds[pointerInfo.event.pointerId];
  89653. }
  89654. }
  89655. });
  89656. // Update bounding box positions
  89657. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89658. _this._updateBoundingBox();
  89659. });
  89660. _this._updateBoundingBox();
  89661. return _this;
  89662. }
  89663. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89664. this._rotateSpheresParent.getChildMeshes()
  89665. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89666. m.isVisible = (!selectedMesh || m == selectedMesh);
  89667. });
  89668. };
  89669. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89670. if (this.attachedMesh) {
  89671. // Update bounding dimensions/positions
  89672. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89673. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89674. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89675. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89676. }
  89677. // Update rotation sphere locations
  89678. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89679. for (var i = 0; i < 3; i++) {
  89680. for (var j = 0; j < 2; j++) {
  89681. for (var k = 0; k < 2; k++) {
  89682. var index = ((i * 4) + (j * 2)) + k;
  89683. if (i == 0) {
  89684. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89685. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89686. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89687. }
  89688. if (i == 1) {
  89689. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89690. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89691. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89692. }
  89693. if (i == 2) {
  89694. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89695. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89696. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89697. }
  89698. if (this.fixedDragMeshScreenSize) {
  89699. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  89700. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  89701. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  89702. }
  89703. else {
  89704. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  89705. }
  89706. }
  89707. }
  89708. }
  89709. // Update scale box locations
  89710. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89711. for (var i = 0; i < 2; i++) {
  89712. for (var j = 0; j < 2; j++) {
  89713. for (var k = 0; k < 2; k++) {
  89714. var index = ((i * 4) + (j * 2)) + k;
  89715. if (scaleBoxes[index]) {
  89716. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89717. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89718. if (this.fixedDragMeshScreenSize) {
  89719. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  89720. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  89721. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  89722. }
  89723. else {
  89724. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  89725. }
  89726. }
  89727. }
  89728. }
  89729. }
  89730. };
  89731. /**
  89732. * Enables rotation on the specified axis and disables rotation on the others
  89733. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  89734. */
  89735. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  89736. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  89737. if (i < 4) {
  89738. m.setEnabled(axis.indexOf("x") != -1);
  89739. }
  89740. else if (i < 8) {
  89741. m.setEnabled(axis.indexOf("y") != -1);
  89742. }
  89743. else {
  89744. m.setEnabled(axis.indexOf("z") != -1);
  89745. }
  89746. });
  89747. };
  89748. /**
  89749. * Disposes of the gizmo
  89750. */
  89751. BoundingBoxGizmo.prototype.dispose = function () {
  89752. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89753. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89754. this._lineBoundingBox.dispose();
  89755. this._rotateSpheresParent.dispose();
  89756. this._scaleBoxesParent.dispose();
  89757. _super.prototype.dispose.call(this);
  89758. };
  89759. return BoundingBoxGizmo;
  89760. }(BABYLON.Gizmo));
  89761. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89762. })(BABYLON || (BABYLON = {}));
  89763. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89764. var BABYLON;
  89765. (function (BABYLON) {
  89766. /**
  89767. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89768. */
  89769. var GizmoManager = /** @class */ (function () {
  89770. /**
  89771. * Instatiates a gizmo manager
  89772. * @param scene the scene to overlay the gizmos on top of
  89773. * @param options If only a single gizmo should exist at one time
  89774. */
  89775. function GizmoManager(scene, options) {
  89776. var _this = this;
  89777. this.scene = scene;
  89778. // Set of gizmos that are currently in the scene for each mesh
  89779. this._gizmoSet = {};
  89780. this._pointerObserver = null;
  89781. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89782. // Options parsing
  89783. if (!options) {
  89784. options = {};
  89785. }
  89786. if (options.singleGizmo === undefined) {
  89787. options.singleGizmo = true;
  89788. }
  89789. // Instatiate/dispose gizmos based on pointer actions
  89790. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89791. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89792. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89793. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89794. if (options.singleGizmo) {
  89795. _this._clearGizmos();
  89796. }
  89797. // Enable gizmo when mesh is selected
  89798. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89799. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89800. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89801. }
  89802. else {
  89803. if (!options.singleGizmo) {
  89804. // Disable gizmo when clicked again
  89805. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89806. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89807. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89808. }
  89809. }
  89810. }
  89811. else {
  89812. if (options.singleGizmo) {
  89813. // Disable gizmo when clicked away
  89814. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89815. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89816. if (gizmoPick && !gizmoPick.hit) {
  89817. _this._clearGizmos();
  89818. }
  89819. }
  89820. }
  89821. }
  89822. }
  89823. });
  89824. }
  89825. /**
  89826. * Disposes of the gizmo manager
  89827. */
  89828. GizmoManager.prototype.dispose = function () {
  89829. this.scene.onPointerObservable.remove(this._pointerObserver);
  89830. this._clearGizmos();
  89831. this._gizmoLayer.dispose();
  89832. };
  89833. GizmoManager.prototype._clearGizmos = function () {
  89834. for (var key in this._gizmoSet) {
  89835. if (this._gizmoSet.hasOwnProperty(key)) {
  89836. this._gizmoSet[key].positionGizmo.dispose();
  89837. this._gizmoSet[key].rotationGizmo.dispose();
  89838. delete this._gizmoSet[key];
  89839. }
  89840. }
  89841. };
  89842. return GizmoManager;
  89843. }());
  89844. BABYLON.GizmoManager = GizmoManager;
  89845. })(BABYLON || (BABYLON = {}));
  89846. //# sourceMappingURL=babylon.gizmoManager.js.map
  89847. var BABYLON;
  89848. (function (BABYLON) {
  89849. /**
  89850. * Defines a target to use with MorphTargetManager
  89851. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  89852. */
  89853. var MorphTarget = /** @class */ (function () {
  89854. /**
  89855. * Creates a new MorphTarget
  89856. * @param name defines the name of the target
  89857. * @param influence defines the influence to use
  89858. */
  89859. function MorphTarget(
  89860. /** defines the name of the target */
  89861. name, influence, scene) {
  89862. if (influence === void 0) { influence = 0; }
  89863. if (scene === void 0) { scene = null; }
  89864. this.name = name;
  89865. /**
  89866. * Gets or sets the list of animations
  89867. */
  89868. this.animations = new Array();
  89869. this._positions = null;
  89870. this._normals = null;
  89871. this._tangents = null;
  89872. /**
  89873. * Observable raised when the influence changes
  89874. */
  89875. this.onInfluenceChanged = new BABYLON.Observable();
  89876. this._animationPropertiesOverride = null;
  89877. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89878. this.influence = influence;
  89879. }
  89880. Object.defineProperty(MorphTarget.prototype, "influence", {
  89881. /**
  89882. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  89883. */
  89884. get: function () {
  89885. return this._influence;
  89886. },
  89887. set: function (influence) {
  89888. if (this._influence === influence) {
  89889. return;
  89890. }
  89891. var previous = this._influence;
  89892. this._influence = influence;
  89893. if (this.onInfluenceChanged.hasObservers) {
  89894. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  89895. }
  89896. },
  89897. enumerable: true,
  89898. configurable: true
  89899. });
  89900. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  89901. /**
  89902. * Gets or sets the animation properties override
  89903. */
  89904. get: function () {
  89905. if (!this._animationPropertiesOverride && this._scene) {
  89906. return this._scene.animationPropertiesOverride;
  89907. }
  89908. return this._animationPropertiesOverride;
  89909. },
  89910. set: function (value) {
  89911. this._animationPropertiesOverride = value;
  89912. },
  89913. enumerable: true,
  89914. configurable: true
  89915. });
  89916. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  89917. /**
  89918. * Gets a boolean defining if the target contains position data
  89919. */
  89920. get: function () {
  89921. return !!this._positions;
  89922. },
  89923. enumerable: true,
  89924. configurable: true
  89925. });
  89926. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  89927. /**
  89928. * Gets a boolean defining if the target contains normal data
  89929. */
  89930. get: function () {
  89931. return !!this._normals;
  89932. },
  89933. enumerable: true,
  89934. configurable: true
  89935. });
  89936. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  89937. /**
  89938. * Gets a boolean defining if the target contains tangent data
  89939. */
  89940. get: function () {
  89941. return !!this._tangents;
  89942. },
  89943. enumerable: true,
  89944. configurable: true
  89945. });
  89946. /**
  89947. * Affects position data to this target
  89948. * @param data defines the position data to use
  89949. */
  89950. MorphTarget.prototype.setPositions = function (data) {
  89951. this._positions = data;
  89952. };
  89953. /**
  89954. * Gets the position data stored in this target
  89955. * @returns a FloatArray containing the position data (or null if not present)
  89956. */
  89957. MorphTarget.prototype.getPositions = function () {
  89958. return this._positions;
  89959. };
  89960. /**
  89961. * Affects normal data to this target
  89962. * @param data defines the normal data to use
  89963. */
  89964. MorphTarget.prototype.setNormals = function (data) {
  89965. this._normals = data;
  89966. };
  89967. /**
  89968. * Gets the normal data stored in this target
  89969. * @returns a FloatArray containing the normal data (or null if not present)
  89970. */
  89971. MorphTarget.prototype.getNormals = function () {
  89972. return this._normals;
  89973. };
  89974. /**
  89975. * Affects tangent data to this target
  89976. * @param data defines the tangent data to use
  89977. */
  89978. MorphTarget.prototype.setTangents = function (data) {
  89979. this._tangents = data;
  89980. };
  89981. /**
  89982. * Gets the tangent data stored in this target
  89983. * @returns a FloatArray containing the tangent data (or null if not present)
  89984. */
  89985. MorphTarget.prototype.getTangents = function () {
  89986. return this._tangents;
  89987. };
  89988. /**
  89989. * Serializes the current target into a Serialization object
  89990. * @returns the serialized object
  89991. */
  89992. MorphTarget.prototype.serialize = function () {
  89993. var serializationObject = {};
  89994. serializationObject.name = this.name;
  89995. serializationObject.influence = this.influence;
  89996. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  89997. if (this.hasNormals) {
  89998. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  89999. }
  90000. if (this.hasTangents) {
  90001. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90002. }
  90003. // Animations
  90004. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90005. return serializationObject;
  90006. };
  90007. // Statics
  90008. /**
  90009. * Creates a new target from serialized data
  90010. * @param serializationObject defines the serialized data to use
  90011. * @returns a new MorphTarget
  90012. */
  90013. MorphTarget.Parse = function (serializationObject) {
  90014. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90015. result.setPositions(serializationObject.positions);
  90016. if (serializationObject.normals) {
  90017. result.setNormals(serializationObject.normals);
  90018. }
  90019. if (serializationObject.tangents) {
  90020. result.setTangents(serializationObject.tangents);
  90021. }
  90022. // Animations
  90023. if (serializationObject.animations) {
  90024. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90025. var parsedAnimation = serializationObject.animations[animationIndex];
  90026. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90027. }
  90028. }
  90029. return result;
  90030. };
  90031. /**
  90032. * Creates a MorphTarget from mesh data
  90033. * @param mesh defines the source mesh
  90034. * @param name defines the name to use for the new target
  90035. * @param influence defines the influence to attach to the target
  90036. * @returns a new MorphTarget
  90037. */
  90038. MorphTarget.FromMesh = function (mesh, name, influence) {
  90039. if (!name) {
  90040. name = mesh.name;
  90041. }
  90042. var result = new MorphTarget(name, influence, mesh.getScene());
  90043. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90044. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90045. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90046. }
  90047. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90048. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90049. }
  90050. return result;
  90051. };
  90052. return MorphTarget;
  90053. }());
  90054. BABYLON.MorphTarget = MorphTarget;
  90055. })(BABYLON || (BABYLON = {}));
  90056. //# sourceMappingURL=babylon.morphTarget.js.map
  90057. var BABYLON;
  90058. (function (BABYLON) {
  90059. /**
  90060. * This class is used to deform meshes using morphing between different targets
  90061. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90062. */
  90063. var MorphTargetManager = /** @class */ (function () {
  90064. /**
  90065. * Creates a new MorphTargetManager
  90066. * @param scene defines the current scene
  90067. */
  90068. function MorphTargetManager(scene) {
  90069. if (scene === void 0) { scene = null; }
  90070. this._targets = new Array();
  90071. this._targetObservable = new Array();
  90072. this._activeTargets = new BABYLON.SmartArray(16);
  90073. this._supportsNormals = false;
  90074. this._supportsTangents = false;
  90075. this._vertexCount = 0;
  90076. this._uniqueId = 0;
  90077. this._tempInfluences = new Array();
  90078. if (!scene) {
  90079. scene = BABYLON.Engine.LastCreatedScene;
  90080. }
  90081. this._scene = scene;
  90082. if (this._scene) {
  90083. this._scene.morphTargetManagers.push(this);
  90084. this._uniqueId = this._scene.getUniqueId();
  90085. }
  90086. }
  90087. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90088. /**
  90089. * Gets the unique ID of this manager
  90090. */
  90091. get: function () {
  90092. return this._uniqueId;
  90093. },
  90094. enumerable: true,
  90095. configurable: true
  90096. });
  90097. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90098. /**
  90099. * Gets the number of vertices handled by this manager
  90100. */
  90101. get: function () {
  90102. return this._vertexCount;
  90103. },
  90104. enumerable: true,
  90105. configurable: true
  90106. });
  90107. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90108. /**
  90109. * Gets a boolean indicating if this manager supports morphing of normals
  90110. */
  90111. get: function () {
  90112. return this._supportsNormals;
  90113. },
  90114. enumerable: true,
  90115. configurable: true
  90116. });
  90117. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90118. /**
  90119. * Gets a boolean indicating if this manager supports morphing of tangents
  90120. */
  90121. get: function () {
  90122. return this._supportsTangents;
  90123. },
  90124. enumerable: true,
  90125. configurable: true
  90126. });
  90127. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90128. /**
  90129. * Gets the number of targets stored in this manager
  90130. */
  90131. get: function () {
  90132. return this._targets.length;
  90133. },
  90134. enumerable: true,
  90135. configurable: true
  90136. });
  90137. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90138. /**
  90139. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90140. */
  90141. get: function () {
  90142. return this._activeTargets.length;
  90143. },
  90144. enumerable: true,
  90145. configurable: true
  90146. });
  90147. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90148. /**
  90149. * Gets the list of influences (one per target)
  90150. */
  90151. get: function () {
  90152. return this._influences;
  90153. },
  90154. enumerable: true,
  90155. configurable: true
  90156. });
  90157. /**
  90158. * Gets the active target at specified index. An active target is a target with an influence > 0
  90159. * @param index defines the index to check
  90160. * @returns the requested target
  90161. */
  90162. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90163. return this._activeTargets.data[index];
  90164. };
  90165. /**
  90166. * Gets the target at specified index
  90167. * @param index defines the index to check
  90168. * @returns the requested target
  90169. */
  90170. MorphTargetManager.prototype.getTarget = function (index) {
  90171. return this._targets[index];
  90172. };
  90173. /**
  90174. * Add a new target to this manager
  90175. * @param target defines the target to add
  90176. */
  90177. MorphTargetManager.prototype.addTarget = function (target) {
  90178. var _this = this;
  90179. this._targets.push(target);
  90180. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90181. _this._syncActiveTargets(needUpdate);
  90182. }));
  90183. this._syncActiveTargets(true);
  90184. };
  90185. /**
  90186. * Removes a target from the manager
  90187. * @param target defines the target to remove
  90188. */
  90189. MorphTargetManager.prototype.removeTarget = function (target) {
  90190. var index = this._targets.indexOf(target);
  90191. if (index >= 0) {
  90192. this._targets.splice(index, 1);
  90193. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90194. this._syncActiveTargets(true);
  90195. }
  90196. };
  90197. /**
  90198. * Serializes the current manager into a Serialization object
  90199. * @returns the serialized object
  90200. */
  90201. MorphTargetManager.prototype.serialize = function () {
  90202. var serializationObject = {};
  90203. serializationObject.id = this.uniqueId;
  90204. serializationObject.targets = [];
  90205. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90206. var target = _a[_i];
  90207. serializationObject.targets.push(target.serialize());
  90208. }
  90209. return serializationObject;
  90210. };
  90211. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90212. var influenceCount = 0;
  90213. this._activeTargets.reset();
  90214. this._supportsNormals = true;
  90215. this._supportsTangents = true;
  90216. this._vertexCount = 0;
  90217. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90218. var target = _a[_i];
  90219. this._activeTargets.push(target);
  90220. this._tempInfluences[influenceCount++] = target.influence;
  90221. var positions = target.getPositions();
  90222. if (positions) {
  90223. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90224. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90225. var vertexCount = positions.length / 3;
  90226. if (this._vertexCount === 0) {
  90227. this._vertexCount = vertexCount;
  90228. }
  90229. else if (this._vertexCount !== vertexCount) {
  90230. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90231. return;
  90232. }
  90233. }
  90234. }
  90235. if (!this._influences || this._influences.length !== influenceCount) {
  90236. this._influences = new Float32Array(influenceCount);
  90237. }
  90238. for (var index = 0; index < influenceCount; index++) {
  90239. this._influences[index] = this._tempInfluences[index];
  90240. }
  90241. if (needUpdate) {
  90242. this.synchronize();
  90243. }
  90244. };
  90245. /**
  90246. * Syncrhonize the targets with all the meshes using this morph target manager
  90247. */
  90248. MorphTargetManager.prototype.synchronize = function () {
  90249. if (!this._scene) {
  90250. return;
  90251. }
  90252. // Flag meshes as dirty to resync with the active targets
  90253. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90254. var mesh = _a[_i];
  90255. if (mesh.morphTargetManager === this) {
  90256. mesh._syncGeometryWithMorphTargetManager();
  90257. }
  90258. }
  90259. };
  90260. // Statics
  90261. /**
  90262. * Creates a new MorphTargetManager from serialized data
  90263. * @param serializationObject defines the serialized data
  90264. * @param scene defines the hosting scene
  90265. * @returns the new MorphTargetManager
  90266. */
  90267. MorphTargetManager.Parse = function (serializationObject, scene) {
  90268. var result = new MorphTargetManager(scene);
  90269. result._uniqueId = serializationObject.id;
  90270. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90271. var targetData = _a[_i];
  90272. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90273. }
  90274. return result;
  90275. };
  90276. return MorphTargetManager;
  90277. }());
  90278. BABYLON.MorphTargetManager = MorphTargetManager;
  90279. })(BABYLON || (BABYLON = {}));
  90280. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90281. var BABYLON;
  90282. (function (BABYLON) {
  90283. var Octree = /** @class */ (function () {
  90284. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90285. if (maxDepth === void 0) { maxDepth = 2; }
  90286. this.maxDepth = maxDepth;
  90287. this.dynamicContent = new Array();
  90288. this._maxBlockCapacity = maxBlockCapacity || 64;
  90289. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90290. this._creationFunc = creationFunc;
  90291. }
  90292. // Methods
  90293. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90294. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90295. };
  90296. Octree.prototype.addMesh = function (entry) {
  90297. for (var index = 0; index < this.blocks.length; index++) {
  90298. var block = this.blocks[index];
  90299. block.addEntry(entry);
  90300. }
  90301. };
  90302. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90303. this._selectionContent.reset();
  90304. for (var index = 0; index < this.blocks.length; index++) {
  90305. var block = this.blocks[index];
  90306. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90307. }
  90308. if (allowDuplicate) {
  90309. this._selectionContent.concat(this.dynamicContent);
  90310. }
  90311. else {
  90312. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90313. }
  90314. return this._selectionContent;
  90315. };
  90316. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90317. this._selectionContent.reset();
  90318. for (var index = 0; index < this.blocks.length; index++) {
  90319. var block = this.blocks[index];
  90320. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90321. }
  90322. if (allowDuplicate) {
  90323. this._selectionContent.concat(this.dynamicContent);
  90324. }
  90325. else {
  90326. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90327. }
  90328. return this._selectionContent;
  90329. };
  90330. Octree.prototype.intersectsRay = function (ray) {
  90331. this._selectionContent.reset();
  90332. for (var index = 0; index < this.blocks.length; index++) {
  90333. var block = this.blocks[index];
  90334. block.intersectsRay(ray, this._selectionContent);
  90335. }
  90336. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90337. return this._selectionContent;
  90338. };
  90339. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90340. target.blocks = new Array();
  90341. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90342. // Segmenting space
  90343. for (var x = 0; x < 2; x++) {
  90344. for (var y = 0; y < 2; y++) {
  90345. for (var z = 0; z < 2; z++) {
  90346. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90347. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90348. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90349. block.addEntries(entries);
  90350. target.blocks.push(block);
  90351. }
  90352. }
  90353. }
  90354. };
  90355. Octree.CreationFuncForMeshes = function (entry, block) {
  90356. var boundingInfo = entry.getBoundingInfo();
  90357. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90358. block.entries.push(entry);
  90359. }
  90360. };
  90361. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90362. var boundingInfo = entry.getBoundingInfo();
  90363. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90364. block.entries.push(entry);
  90365. }
  90366. };
  90367. return Octree;
  90368. }());
  90369. BABYLON.Octree = Octree;
  90370. })(BABYLON || (BABYLON = {}));
  90371. //# sourceMappingURL=babylon.octree.js.map
  90372. var BABYLON;
  90373. (function (BABYLON) {
  90374. var OctreeBlock = /** @class */ (function () {
  90375. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90376. this.entries = new Array();
  90377. this._boundingVectors = new Array();
  90378. this._capacity = capacity;
  90379. this._depth = depth;
  90380. this._maxDepth = maxDepth;
  90381. this._creationFunc = creationFunc;
  90382. this._minPoint = minPoint;
  90383. this._maxPoint = maxPoint;
  90384. this._boundingVectors.push(minPoint.clone());
  90385. this._boundingVectors.push(maxPoint.clone());
  90386. this._boundingVectors.push(minPoint.clone());
  90387. this._boundingVectors[2].x = maxPoint.x;
  90388. this._boundingVectors.push(minPoint.clone());
  90389. this._boundingVectors[3].y = maxPoint.y;
  90390. this._boundingVectors.push(minPoint.clone());
  90391. this._boundingVectors[4].z = maxPoint.z;
  90392. this._boundingVectors.push(maxPoint.clone());
  90393. this._boundingVectors[5].z = minPoint.z;
  90394. this._boundingVectors.push(maxPoint.clone());
  90395. this._boundingVectors[6].x = minPoint.x;
  90396. this._boundingVectors.push(maxPoint.clone());
  90397. this._boundingVectors[7].y = minPoint.y;
  90398. }
  90399. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  90400. // Property
  90401. get: function () {
  90402. return this._capacity;
  90403. },
  90404. enumerable: true,
  90405. configurable: true
  90406. });
  90407. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  90408. get: function () {
  90409. return this._minPoint;
  90410. },
  90411. enumerable: true,
  90412. configurable: true
  90413. });
  90414. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  90415. get: function () {
  90416. return this._maxPoint;
  90417. },
  90418. enumerable: true,
  90419. configurable: true
  90420. });
  90421. // Methods
  90422. OctreeBlock.prototype.addEntry = function (entry) {
  90423. if (this.blocks) {
  90424. for (var index = 0; index < this.blocks.length; index++) {
  90425. var block = this.blocks[index];
  90426. block.addEntry(entry);
  90427. }
  90428. return;
  90429. }
  90430. this._creationFunc(entry, this);
  90431. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  90432. this.createInnerBlocks();
  90433. }
  90434. };
  90435. OctreeBlock.prototype.addEntries = function (entries) {
  90436. for (var index = 0; index < entries.length; index++) {
  90437. var mesh = entries[index];
  90438. this.addEntry(mesh);
  90439. }
  90440. };
  90441. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  90442. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  90443. if (this.blocks) {
  90444. for (var index = 0; index < this.blocks.length; index++) {
  90445. var block = this.blocks[index];
  90446. block.select(frustumPlanes, selection, allowDuplicate);
  90447. }
  90448. return;
  90449. }
  90450. if (allowDuplicate) {
  90451. selection.concat(this.entries);
  90452. }
  90453. else {
  90454. selection.concatWithNoDuplicate(this.entries);
  90455. }
  90456. }
  90457. };
  90458. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  90459. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  90460. if (this.blocks) {
  90461. for (var index = 0; index < this.blocks.length; index++) {
  90462. var block = this.blocks[index];
  90463. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  90464. }
  90465. return;
  90466. }
  90467. if (allowDuplicate) {
  90468. selection.concat(this.entries);
  90469. }
  90470. else {
  90471. selection.concatWithNoDuplicate(this.entries);
  90472. }
  90473. }
  90474. };
  90475. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90476. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90477. if (this.blocks) {
  90478. for (var index = 0; index < this.blocks.length; index++) {
  90479. var block = this.blocks[index];
  90480. block.intersectsRay(ray, selection);
  90481. }
  90482. return;
  90483. }
  90484. selection.concatWithNoDuplicate(this.entries);
  90485. }
  90486. };
  90487. OctreeBlock.prototype.createInnerBlocks = function () {
  90488. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90489. };
  90490. return OctreeBlock;
  90491. }());
  90492. BABYLON.OctreeBlock = OctreeBlock;
  90493. })(BABYLON || (BABYLON = {}));
  90494. //# sourceMappingURL=babylon.octreeBlock.js.map
  90495. var BABYLON;
  90496. (function (BABYLON) {
  90497. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90498. __extends(VRDistortionCorrectionPostProcess, _super);
  90499. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90500. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90501. 'LensCenter',
  90502. 'Scale',
  90503. 'ScaleIn',
  90504. 'HmdWarpParam'
  90505. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90506. _this._isRightEye = isRightEye;
  90507. _this._distortionFactors = vrMetrics.distortionK;
  90508. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90509. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90510. _this.adaptScaleToCurrentViewport = true;
  90511. _this.onSizeChangedObservable.add(function () {
  90512. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90513. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90514. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90515. });
  90516. _this.onApplyObservable.add(function (effect) {
  90517. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90518. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90519. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90520. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90521. });
  90522. return _this;
  90523. }
  90524. return VRDistortionCorrectionPostProcess;
  90525. }(BABYLON.PostProcess));
  90526. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90527. })(BABYLON || (BABYLON = {}));
  90528. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90529. var BABYLON;
  90530. (function (BABYLON) {
  90531. /**
  90532. * Postprocess used to generate anaglyphic rendering
  90533. */
  90534. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90535. __extends(AnaglyphPostProcess, _super);
  90536. /**
  90537. * Creates a new AnaglyphPostProcess
  90538. * @param name defines postprocess name
  90539. * @param options defines creation options or target ratio scale
  90540. * @param rigCameras defines cameras using this postprocess
  90541. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90542. * @param engine defines hosting engine
  90543. * @param reusable defines if the postprocess will be reused multiple times per frame
  90544. */
  90545. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90546. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90547. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90548. _this.onApplyObservable.add(function (effect) {
  90549. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90550. });
  90551. return _this;
  90552. }
  90553. return AnaglyphPostProcess;
  90554. }(BABYLON.PostProcess));
  90555. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90556. })(BABYLON || (BABYLON = {}));
  90557. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90558. var BABYLON;
  90559. (function (BABYLON) {
  90560. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90561. __extends(StereoscopicInterlacePostProcess, _super);
  90562. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90563. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90564. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90565. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90566. _this.onSizeChangedObservable.add(function () {
  90567. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90568. });
  90569. _this.onApplyObservable.add(function (effect) {
  90570. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90571. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90572. });
  90573. return _this;
  90574. }
  90575. return StereoscopicInterlacePostProcess;
  90576. }(BABYLON.PostProcess));
  90577. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90578. })(BABYLON || (BABYLON = {}));
  90579. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90580. var BABYLON;
  90581. (function (BABYLON) {
  90582. /**
  90583. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90584. * Screen rotation is taken into account.
  90585. */
  90586. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90587. function FreeCameraDeviceOrientationInput() {
  90588. var _this = this;
  90589. this._screenOrientationAngle = 0;
  90590. this._screenQuaternion = new BABYLON.Quaternion();
  90591. this._alpha = 0;
  90592. this._beta = 0;
  90593. this._gamma = 0;
  90594. this._orientationChanged = function () {
  90595. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90596. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90597. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90598. };
  90599. this._deviceOrientation = function (evt) {
  90600. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90601. _this._beta = evt.beta !== null ? evt.beta : 0;
  90602. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90603. };
  90604. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  90605. this._orientationChanged();
  90606. }
  90607. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  90608. get: function () {
  90609. return this._camera;
  90610. },
  90611. set: function (camera) {
  90612. this._camera = camera;
  90613. if (this._camera != null && !this._camera.rotationQuaternion) {
  90614. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90615. }
  90616. },
  90617. enumerable: true,
  90618. configurable: true
  90619. });
  90620. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90621. window.addEventListener("orientationchange", this._orientationChanged);
  90622. window.addEventListener("deviceorientation", this._deviceOrientation);
  90623. //In certain cases, the attach control is called AFTER orientation was changed,
  90624. //So this is needed.
  90625. this._orientationChanged();
  90626. };
  90627. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90628. window.removeEventListener("orientationchange", this._orientationChanged);
  90629. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90630. };
  90631. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90632. //if no device orientation provided, don't update the rotation.
  90633. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90634. if (!this._alpha)
  90635. return;
  90636. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90637. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90638. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90639. //Mirror on XY Plane
  90640. this._camera.rotationQuaternion.z *= -1;
  90641. this._camera.rotationQuaternion.w *= -1;
  90642. };
  90643. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90644. return "FreeCameraDeviceOrientationInput";
  90645. };
  90646. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90647. return "deviceOrientation";
  90648. };
  90649. return FreeCameraDeviceOrientationInput;
  90650. }());
  90651. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90652. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90653. })(BABYLON || (BABYLON = {}));
  90654. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90655. var BABYLON;
  90656. (function (BABYLON) {
  90657. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90658. function ArcRotateCameraVRDeviceOrientationInput() {
  90659. this.alphaCorrection = 1;
  90660. this.betaCorrection = 1;
  90661. this.gammaCorrection = 1;
  90662. this._alpha = 0;
  90663. this._gamma = 0;
  90664. this._dirty = false;
  90665. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90666. }
  90667. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90668. this.camera.attachControl(element, noPreventDefault);
  90669. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90670. };
  90671. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90672. if (evt.alpha !== null) {
  90673. this._alpha = +evt.alpha | 0;
  90674. }
  90675. if (evt.gamma !== null) {
  90676. this._gamma = +evt.gamma | 0;
  90677. }
  90678. this._dirty = true;
  90679. };
  90680. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90681. if (this._dirty) {
  90682. this._dirty = false;
  90683. if (this._gamma < 0) {
  90684. this._gamma = 180 + this._gamma;
  90685. }
  90686. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90687. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90688. }
  90689. };
  90690. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90691. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90692. };
  90693. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90694. return "ArcRotateCameraVRDeviceOrientationInput";
  90695. };
  90696. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90697. return "VRDeviceOrientation";
  90698. };
  90699. return ArcRotateCameraVRDeviceOrientationInput;
  90700. }());
  90701. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90702. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90703. })(BABYLON || (BABYLON = {}));
  90704. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90705. var BABYLON;
  90706. (function (BABYLON) {
  90707. var VRCameraMetrics = /** @class */ (function () {
  90708. function VRCameraMetrics() {
  90709. this.compensateDistortion = true;
  90710. }
  90711. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90712. get: function () {
  90713. return this.hResolution / (2 * this.vResolution);
  90714. },
  90715. enumerable: true,
  90716. configurable: true
  90717. });
  90718. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90719. get: function () {
  90720. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90721. },
  90722. enumerable: true,
  90723. configurable: true
  90724. });
  90725. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90726. get: function () {
  90727. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90728. var h = (4 * meters) / this.hScreenSize;
  90729. return BABYLON.Matrix.Translation(h, 0, 0);
  90730. },
  90731. enumerable: true,
  90732. configurable: true
  90733. });
  90734. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90735. get: function () {
  90736. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90737. var h = (4 * meters) / this.hScreenSize;
  90738. return BABYLON.Matrix.Translation(-h, 0, 0);
  90739. },
  90740. enumerable: true,
  90741. configurable: true
  90742. });
  90743. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90744. get: function () {
  90745. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90746. },
  90747. enumerable: true,
  90748. configurable: true
  90749. });
  90750. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90751. get: function () {
  90752. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90753. },
  90754. enumerable: true,
  90755. configurable: true
  90756. });
  90757. VRCameraMetrics.GetDefault = function () {
  90758. var result = new VRCameraMetrics();
  90759. result.hResolution = 1280;
  90760. result.vResolution = 800;
  90761. result.hScreenSize = 0.149759993;
  90762. result.vScreenSize = 0.0935999975;
  90763. result.vScreenCenter = 0.0467999987;
  90764. result.eyeToScreenDistance = 0.0410000011;
  90765. result.lensSeparationDistance = 0.0635000020;
  90766. result.interpupillaryDistance = 0.0640000030;
  90767. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90768. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90769. result.postProcessScaleFactor = 1.714605507808412;
  90770. result.lensCenterOffset = 0.151976421;
  90771. return result;
  90772. };
  90773. return VRCameraMetrics;
  90774. }());
  90775. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90776. })(BABYLON || (BABYLON = {}));
  90777. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90778. var BABYLON;
  90779. (function (BABYLON) {
  90780. /**
  90781. * This represents a WebVR camera.
  90782. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90783. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90784. */
  90785. var WebVRFreeCamera = /** @class */ (function (_super) {
  90786. __extends(WebVRFreeCamera, _super);
  90787. /**
  90788. * Instantiates a WebVRFreeCamera.
  90789. * @param name The name of the WebVRFreeCamera
  90790. * @param position The starting anchor position for the camera
  90791. * @param scene The scene the camera belongs to
  90792. * @param webVROptions a set of customizable options for the webVRCamera
  90793. */
  90794. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90795. if (webVROptions === void 0) { webVROptions = {}; }
  90796. var _this = _super.call(this, name, position, scene) || this;
  90797. _this.webVROptions = webVROptions;
  90798. /**
  90799. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90800. */
  90801. _this._vrDevice = null;
  90802. /**
  90803. * The rawPose of the vrDevice.
  90804. */
  90805. _this.rawPose = null;
  90806. _this._specsVersion = "1.1";
  90807. _this._attached = false;
  90808. _this._descendants = [];
  90809. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90810. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90811. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90812. _this._standingMatrix = null;
  90813. /**
  90814. * Represents device position in babylon space.
  90815. */
  90816. _this.devicePosition = BABYLON.Vector3.Zero();
  90817. /**
  90818. * Represents device rotation in babylon space.
  90819. */
  90820. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90821. /**
  90822. * The scale of the device to be used when translating from device space to babylon space.
  90823. */
  90824. _this.deviceScaleFactor = 1;
  90825. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90826. _this._worldToDevice = BABYLON.Matrix.Identity();
  90827. /**
  90828. * References to the webVR controllers for the vrDevice.
  90829. */
  90830. _this.controllers = [];
  90831. /**
  90832. * Emits an event when a controller is attached.
  90833. */
  90834. _this.onControllersAttachedObservable = new BABYLON.Observable();
  90835. /**
  90836. * Emits an event when a controller's mesh has been loaded;
  90837. */
  90838. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  90839. /**
  90840. * If the rig cameras be used as parent instead of this camera.
  90841. */
  90842. _this.rigParenting = true;
  90843. _this._defaultHeight = undefined;
  90844. _this._workingVector = BABYLON.Vector3.Zero();
  90845. _this._oneVector = BABYLON.Vector3.One();
  90846. _this._workingMatrix = BABYLON.Matrix.Identity();
  90847. _this._cache.position = BABYLON.Vector3.Zero();
  90848. if (webVROptions.defaultHeight) {
  90849. _this._defaultHeight = webVROptions.defaultHeight;
  90850. _this.position.y = _this._defaultHeight;
  90851. }
  90852. _this.minZ = 0.1;
  90853. //legacy support - the compensation boolean was removed.
  90854. if (arguments.length === 5) {
  90855. _this.webVROptions = arguments[4];
  90856. }
  90857. // default webVR options
  90858. if (_this.webVROptions.trackPosition == undefined) {
  90859. _this.webVROptions.trackPosition = true;
  90860. }
  90861. if (_this.webVROptions.controllerMeshes == undefined) {
  90862. _this.webVROptions.controllerMeshes = true;
  90863. }
  90864. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  90865. _this.webVROptions.defaultLightingOnControllers = true;
  90866. }
  90867. _this.rotationQuaternion = new BABYLON.Quaternion();
  90868. if (_this.webVROptions && _this.webVROptions.positionScale) {
  90869. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  90870. }
  90871. //enable VR
  90872. var engine = _this.getEngine();
  90873. _this._onVREnabled = function (success) { if (success) {
  90874. _this.initControllers();
  90875. } };
  90876. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  90877. engine.initWebVR().add(function (event) {
  90878. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  90879. return;
  90880. }
  90881. _this._vrDevice = event.vrDisplay;
  90882. //reset the rig parameters.
  90883. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  90884. if (_this._attached) {
  90885. _this.getEngine().enableVR();
  90886. }
  90887. });
  90888. if (typeof (VRFrameData) !== "undefined")
  90889. _this._frameData = new VRFrameData();
  90890. /**
  90891. * The idea behind the following lines:
  90892. * objects that have the camera as parent should actually have the rig cameras as a parent.
  90893. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  90894. * the second will not show it correctly.
  90895. *
  90896. * To solve this - each object that has the camera as parent will be added to a protected array.
  90897. * When the rig camera renders, it will take this array and set all of those to be its children.
  90898. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  90899. * Amazing!
  90900. */
  90901. scene.onBeforeCameraRenderObservable.add(function (camera) {
  90902. if (camera.parent === _this && _this.rigParenting) {
  90903. _this._descendants = _this.getDescendants(true, function (n) {
  90904. // don't take the cameras or the controllers!
  90905. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  90906. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  90907. return !isController && !isRigCamera;
  90908. });
  90909. _this._descendants.forEach(function (node) {
  90910. node.parent = camera;
  90911. });
  90912. }
  90913. });
  90914. scene.onAfterCameraRenderObservable.add(function (camera) {
  90915. if (camera.parent === _this && _this.rigParenting) {
  90916. _this._descendants.forEach(function (node) {
  90917. node.parent = _this;
  90918. });
  90919. }
  90920. });
  90921. return _this;
  90922. }
  90923. /**
  90924. * Gets the device distance from the ground in meters.
  90925. * @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.
  90926. */
  90927. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  90928. if (this._standingMatrix) {
  90929. // Add standing matrix offset to get real offset from ground in room
  90930. this._standingMatrix.getTranslationToRef(this._workingVector);
  90931. return this._deviceRoomPosition.y + this._workingVector.y;
  90932. }
  90933. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  90934. return this._defaultHeight || 0;
  90935. };
  90936. /**
  90937. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90938. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  90939. */
  90940. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  90941. var _this = this;
  90942. if (callback === void 0) { callback = function (bool) { }; }
  90943. // Use standing matrix if available
  90944. this.getEngine().initWebVRAsync().then(function (result) {
  90945. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  90946. callback(false);
  90947. }
  90948. else {
  90949. _this._standingMatrix = new BABYLON.Matrix();
  90950. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  90951. if (!_this.getScene().useRightHandedSystem) {
  90952. [2, 6, 8, 9, 14].forEach(function (num) {
  90953. if (_this._standingMatrix) {
  90954. _this._standingMatrix.m[num] *= -1;
  90955. }
  90956. });
  90957. }
  90958. callback(true);
  90959. }
  90960. });
  90961. };
  90962. /**
  90963. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  90964. * @returns A promise with a boolean set to if the standing matrix is supported.
  90965. */
  90966. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  90967. var _this = this;
  90968. return new Promise(function (res, rej) {
  90969. _this.useStandingMatrix(function (supported) {
  90970. res(supported);
  90971. });
  90972. });
  90973. };
  90974. /**
  90975. * Disposes the camera
  90976. */
  90977. WebVRFreeCamera.prototype.dispose = function () {
  90978. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  90979. _super.prototype.dispose.call(this);
  90980. };
  90981. /**
  90982. * Gets a vrController by name.
  90983. * @param name The name of the controller to retreive
  90984. * @returns the controller matching the name specified or null if not found
  90985. */
  90986. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  90987. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  90988. var gp = _a[_i];
  90989. if (gp.hand === name) {
  90990. return gp;
  90991. }
  90992. }
  90993. return null;
  90994. };
  90995. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  90996. /**
  90997. * The controller corrisponding to the users left hand.
  90998. */
  90999. get: function () {
  91000. if (!this._leftController) {
  91001. this._leftController = this.getControllerByName("left");
  91002. }
  91003. return this._leftController;
  91004. },
  91005. enumerable: true,
  91006. configurable: true
  91007. });
  91008. ;
  91009. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91010. /**
  91011. * The controller corrisponding to the users right hand.
  91012. */
  91013. get: function () {
  91014. if (!this._rightController) {
  91015. this._rightController = this.getControllerByName("right");
  91016. }
  91017. return this._rightController;
  91018. },
  91019. enumerable: true,
  91020. configurable: true
  91021. });
  91022. ;
  91023. /**
  91024. * Casts a ray forward from the vrCamera's gaze.
  91025. * @param length Length of the ray (default: 100)
  91026. * @returns the ray corrisponding to the gaze
  91027. */
  91028. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91029. if (length === void 0) { length = 100; }
  91030. if (this.leftCamera) {
  91031. // Use left eye to avoid computation to compute center on every call
  91032. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91033. }
  91034. else {
  91035. return _super.prototype.getForwardRay.call(this, length);
  91036. }
  91037. };
  91038. /**
  91039. * Updates the camera based on device's frame data
  91040. */
  91041. WebVRFreeCamera.prototype._checkInputs = function () {
  91042. if (this._vrDevice && this._vrDevice.isPresenting) {
  91043. this._vrDevice.getFrameData(this._frameData);
  91044. this.updateFromDevice(this._frameData.pose);
  91045. }
  91046. _super.prototype._checkInputs.call(this);
  91047. };
  91048. /**
  91049. * Updates the poseControlled values based on the input device pose.
  91050. * @param poseData Pose coming from the device
  91051. */
  91052. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91053. if (poseData && poseData.orientation) {
  91054. this.rawPose = poseData;
  91055. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91056. if (this.getScene().useRightHandedSystem) {
  91057. this._deviceRoomRotationQuaternion.z *= -1;
  91058. this._deviceRoomRotationQuaternion.w *= -1;
  91059. }
  91060. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91061. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91062. if (this.getScene().useRightHandedSystem) {
  91063. this._deviceRoomPosition.z *= -1;
  91064. }
  91065. }
  91066. }
  91067. };
  91068. /**
  91069. * WebVR's attach control will start broadcasting frames to the device.
  91070. * Note that in certain browsers (chrome for example) this function must be called
  91071. * within a user-interaction callback. Example:
  91072. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91073. *
  91074. * @param element html element to attach the vrDevice to
  91075. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91076. */
  91077. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91078. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91079. this._attached = true;
  91080. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91081. if (this._vrDevice) {
  91082. this.getEngine().enableVR();
  91083. }
  91084. };
  91085. /**
  91086. * Detaches the camera from the html element and disables VR
  91087. *
  91088. * @param element html element to detach from
  91089. */
  91090. WebVRFreeCamera.prototype.detachControl = function (element) {
  91091. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91092. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91093. _super.prototype.detachControl.call(this, element);
  91094. this._attached = false;
  91095. this.getEngine().disableVR();
  91096. };
  91097. /**
  91098. * @returns the name of this class
  91099. */
  91100. WebVRFreeCamera.prototype.getClassName = function () {
  91101. return "WebVRFreeCamera";
  91102. };
  91103. /**
  91104. * Calls resetPose on the vrDisplay
  91105. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91106. */
  91107. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91108. //uses the vrDisplay's "resetPose()".
  91109. //pitch and roll won't be affected.
  91110. this._vrDevice.resetPose();
  91111. };
  91112. /**
  91113. * Updates the rig cameras (left and right eye)
  91114. */
  91115. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91116. var camLeft = this._rigCameras[0];
  91117. var camRight = this._rigCameras[1];
  91118. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91119. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91120. camLeft.position.copyFrom(this._deviceRoomPosition);
  91121. camRight.position.copyFrom(this._deviceRoomPosition);
  91122. };
  91123. /**
  91124. * Updates the cached values of the camera
  91125. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91126. */
  91127. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91128. var _this = this;
  91129. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91130. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91131. if (!this.updateCacheCalled) {
  91132. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91133. this.updateCacheCalled = true;
  91134. this.update();
  91135. }
  91136. // Set working vector to the device position in room space rotated by the new rotation
  91137. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91138. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91139. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91140. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91141. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91142. // Add translation from anchor position
  91143. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91144. this._workingVector.addInPlace(this.position);
  91145. this._workingVector.subtractInPlace(this._cache.position);
  91146. this._deviceToWorld.setTranslation(this._workingVector);
  91147. // Set an inverted matrix to be used when updating the camera
  91148. this._deviceToWorld.invertToRef(this._worldToDevice);
  91149. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91150. this.controllers.forEach(function (controller) {
  91151. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91152. controller.update();
  91153. });
  91154. }
  91155. if (!ignoreParentClass) {
  91156. _super.prototype._updateCache.call(this);
  91157. }
  91158. this.updateCacheCalled = false;
  91159. };
  91160. /**
  91161. * Updates the current device position and rotation in the babylon world
  91162. */
  91163. WebVRFreeCamera.prototype.update = function () {
  91164. // Get current device position in babylon world
  91165. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91166. // Get current device rotation in babylon world
  91167. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91168. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91169. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91170. _super.prototype.update.call(this);
  91171. };
  91172. /**
  91173. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91174. * @returns an identity matrix
  91175. */
  91176. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91177. return BABYLON.Matrix.Identity();
  91178. };
  91179. /**
  91180. * This function is called by the two RIG cameras.
  91181. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91182. */
  91183. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91184. var _this = this;
  91185. // Update the parent camera prior to using a child camera to avoid desynchronization
  91186. var parentCamera = this._cameraRigParams["parentCamera"];
  91187. parentCamera._updateCache();
  91188. //WebVR 1.1
  91189. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91190. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91191. if (!this.getScene().useRightHandedSystem) {
  91192. [2, 6, 8, 9, 14].forEach(function (num) {
  91193. _this._webvrViewMatrix.m[num] *= -1;
  91194. });
  91195. }
  91196. // update the camera rotation matrix
  91197. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91198. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91199. // Computing target and final matrix
  91200. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91201. // should the view matrix be updated with scale and position offset?
  91202. if (parentCamera.deviceScaleFactor !== 1) {
  91203. this._webvrViewMatrix.invert();
  91204. // scale the position, if set
  91205. if (parentCamera.deviceScaleFactor) {
  91206. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91207. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91208. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91209. }
  91210. this._webvrViewMatrix.invert();
  91211. }
  91212. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91213. // Compute global position
  91214. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91215. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91216. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91217. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91218. this._markSyncedWithParent();
  91219. return this._webvrViewMatrix;
  91220. };
  91221. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91222. var _this = this;
  91223. var parentCamera = this.parent;
  91224. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91225. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91226. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91227. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91228. //babylon compatible matrix
  91229. if (!this.getScene().useRightHandedSystem) {
  91230. [8, 9, 10, 11].forEach(function (num) {
  91231. _this._projectionMatrix.m[num] *= -1;
  91232. });
  91233. }
  91234. return this._projectionMatrix;
  91235. };
  91236. /**
  91237. * Initializes the controllers and their meshes
  91238. */
  91239. WebVRFreeCamera.prototype.initControllers = function () {
  91240. var _this = this;
  91241. this.controllers = [];
  91242. var manager = this.getScene().gamepadManager;
  91243. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91244. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91245. var webVrController = gamepad;
  91246. if (webVrController.defaultModel) {
  91247. webVrController.defaultModel.setEnabled(false);
  91248. }
  91249. if (webVrController.hand === "right") {
  91250. _this._rightController = null;
  91251. }
  91252. if (webVrController.hand === "left") {
  91253. _this._leftController = null;
  91254. }
  91255. var controllerIndex = _this.controllers.indexOf(webVrController);
  91256. if (controllerIndex !== -1) {
  91257. _this.controllers.splice(controllerIndex, 1);
  91258. }
  91259. }
  91260. });
  91261. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91262. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91263. var webVrController_1 = gamepad;
  91264. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91265. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91266. if (_this.webVROptions.controllerMeshes) {
  91267. if (webVrController_1.defaultModel) {
  91268. webVrController_1.defaultModel.setEnabled(true);
  91269. }
  91270. else {
  91271. // Load the meshes
  91272. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91273. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91274. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91275. if (_this.webVROptions.defaultLightingOnControllers) {
  91276. if (!_this._lightOnControllers) {
  91277. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91278. }
  91279. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91280. var children = mesh.getChildren();
  91281. if (children.length !== 0) {
  91282. children.forEach(function (mesh) {
  91283. light.includedOnlyMeshes.push(mesh);
  91284. activateLightOnSubMeshes_1(mesh, light);
  91285. });
  91286. }
  91287. };
  91288. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91289. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91290. }
  91291. });
  91292. }
  91293. }
  91294. webVrController_1.attachToPoseControlledCamera(_this);
  91295. // since this is async - sanity check. Is the controller already stored?
  91296. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91297. //add to the controllers array
  91298. _this.controllers.push(webVrController_1);
  91299. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91300. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91301. // So we're overriding setting left & right manually to be sure
  91302. var firstViveWandDetected = false;
  91303. for (var i = 0; i < _this.controllers.length; i++) {
  91304. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91305. if (!firstViveWandDetected) {
  91306. firstViveWandDetected = true;
  91307. _this.controllers[i].hand = "left";
  91308. }
  91309. else {
  91310. _this.controllers[i].hand = "right";
  91311. }
  91312. }
  91313. }
  91314. //did we find enough controllers? Great! let the developer know.
  91315. if (_this.controllers.length >= 2) {
  91316. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91317. }
  91318. }
  91319. }
  91320. });
  91321. };
  91322. return WebVRFreeCamera;
  91323. }(BABYLON.FreeCamera));
  91324. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91325. })(BABYLON || (BABYLON = {}));
  91326. //# sourceMappingURL=babylon.webVRCamera.js.map
  91327. var BABYLON;
  91328. (function (BABYLON) {
  91329. // We're mainly based on the logic defined into the FreeCamera code
  91330. /**
  91331. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91332. * being tilted forward or back and left or right.
  91333. */
  91334. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91335. __extends(DeviceOrientationCamera, _super);
  91336. /**
  91337. * Creates a new device orientation camera
  91338. * @param name The name of the camera
  91339. * @param position The start position camera
  91340. * @param scene The scene the camera belongs to
  91341. */
  91342. function DeviceOrientationCamera(name, position, scene) {
  91343. var _this = _super.call(this, name, position, scene) || this;
  91344. _this._quaternionCache = new BABYLON.Quaternion();
  91345. _this.inputs.addDeviceOrientation();
  91346. return _this;
  91347. }
  91348. /**
  91349. * Gets the current instance class name ("DeviceOrientationCamera").
  91350. * This helps avoiding instanceof at run time.
  91351. * @returns the class name
  91352. */
  91353. DeviceOrientationCamera.prototype.getClassName = function () {
  91354. return "DeviceOrientationCamera";
  91355. };
  91356. /**
  91357. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91358. */
  91359. DeviceOrientationCamera.prototype._checkInputs = function () {
  91360. _super.prototype._checkInputs.call(this);
  91361. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91362. if (this._initialQuaternion) {
  91363. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91364. }
  91365. };
  91366. /**
  91367. * Reset the camera to its default orientation on the specified axis only.
  91368. * @param axis The axis to reset
  91369. */
  91370. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91371. var _this = this;
  91372. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91373. //can only work if this camera has a rotation quaternion already.
  91374. if (!this.rotationQuaternion)
  91375. return;
  91376. if (!this._initialQuaternion) {
  91377. this._initialQuaternion = new BABYLON.Quaternion();
  91378. }
  91379. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91380. ['x', 'y', 'z'].forEach(function (axisName) {
  91381. if (!axis[axisName]) {
  91382. _this._initialQuaternion[axisName] = 0;
  91383. }
  91384. else {
  91385. _this._initialQuaternion[axisName] *= -1;
  91386. }
  91387. });
  91388. this._initialQuaternion.normalize();
  91389. //force rotation update
  91390. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91391. };
  91392. return DeviceOrientationCamera;
  91393. }(BABYLON.FreeCamera));
  91394. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  91395. })(BABYLON || (BABYLON = {}));
  91396. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  91397. var BABYLON;
  91398. (function (BABYLON) {
  91399. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  91400. __extends(VRDeviceOrientationFreeCamera, _super);
  91401. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91402. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91403. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91404. var _this = _super.call(this, name, position, scene) || this;
  91405. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91406. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91407. return _this;
  91408. }
  91409. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  91410. return "VRDeviceOrientationFreeCamera";
  91411. };
  91412. return VRDeviceOrientationFreeCamera;
  91413. }(BABYLON.DeviceOrientationCamera));
  91414. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  91415. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  91416. __extends(VRDeviceOrientationGamepadCamera, _super);
  91417. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91418. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91419. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91420. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  91421. _this.inputs.addGamepad();
  91422. return _this;
  91423. }
  91424. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  91425. return "VRDeviceOrientationGamepadCamera";
  91426. };
  91427. return VRDeviceOrientationGamepadCamera;
  91428. }(VRDeviceOrientationFreeCamera));
  91429. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  91430. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  91431. __extends(VRDeviceOrientationArcRotateCamera, _super);
  91432. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  91433. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91434. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91435. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91436. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91437. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91438. _this.inputs.addVRDeviceOrientation();
  91439. return _this;
  91440. }
  91441. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  91442. return "VRDeviceOrientationArcRotateCamera";
  91443. };
  91444. return VRDeviceOrientationArcRotateCamera;
  91445. }(BABYLON.ArcRotateCamera));
  91446. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  91447. })(BABYLON || (BABYLON = {}));
  91448. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  91449. var BABYLON;
  91450. (function (BABYLON) {
  91451. /**
  91452. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91453. */
  91454. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91455. __extends(AnaglyphFreeCamera, _super);
  91456. /**
  91457. * Creates a new AnaglyphFreeCamera
  91458. * @param name defines camera name
  91459. * @param position defines initial position
  91460. * @param interaxialDistance defines distance between each color axis
  91461. * @param scene defines the hosting scene
  91462. */
  91463. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91464. var _this = _super.call(this, name, position, scene) || this;
  91465. _this.interaxialDistance = interaxialDistance;
  91466. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91467. return _this;
  91468. }
  91469. /**
  91470. * Gets camera class name
  91471. * @returns AnaglyphFreeCamera
  91472. */
  91473. AnaglyphFreeCamera.prototype.getClassName = function () {
  91474. return "AnaglyphFreeCamera";
  91475. };
  91476. return AnaglyphFreeCamera;
  91477. }(BABYLON.FreeCamera));
  91478. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91479. /**
  91480. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91481. */
  91482. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91483. __extends(AnaglyphArcRotateCamera, _super);
  91484. /**
  91485. * Creates a new AnaglyphArcRotateCamera
  91486. * @param name defines camera name
  91487. * @param alpha defines alpha angle (in radians)
  91488. * @param beta defines beta angle (in radians)
  91489. * @param radius defines radius
  91490. * @param target defines camera target
  91491. * @param interaxialDistance defines distance between each color axis
  91492. * @param scene defines the hosting scene
  91493. */
  91494. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91495. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91496. _this.interaxialDistance = interaxialDistance;
  91497. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91498. return _this;
  91499. }
  91500. /**
  91501. * Gets camera class name
  91502. * @returns AnaglyphArcRotateCamera
  91503. */
  91504. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91505. return "AnaglyphArcRotateCamera";
  91506. };
  91507. return AnaglyphArcRotateCamera;
  91508. }(BABYLON.ArcRotateCamera));
  91509. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91510. /**
  91511. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91512. */
  91513. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91514. __extends(AnaglyphGamepadCamera, _super);
  91515. /**
  91516. * Creates a new AnaglyphGamepadCamera
  91517. * @param name defines camera name
  91518. * @param position defines initial position
  91519. * @param interaxialDistance defines distance between each color axis
  91520. * @param scene defines the hosting scene
  91521. */
  91522. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91523. var _this = _super.call(this, name, position, scene) || this;
  91524. _this.interaxialDistance = interaxialDistance;
  91525. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91526. return _this;
  91527. }
  91528. /**
  91529. * Gets camera class name
  91530. * @returns AnaglyphGamepadCamera
  91531. */
  91532. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91533. return "AnaglyphGamepadCamera";
  91534. };
  91535. return AnaglyphGamepadCamera;
  91536. }(BABYLON.GamepadCamera));
  91537. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91538. /**
  91539. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91540. */
  91541. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91542. __extends(AnaglyphUniversalCamera, _super);
  91543. /**
  91544. * Creates a new AnaglyphUniversalCamera
  91545. * @param name defines camera name
  91546. * @param position defines initial position
  91547. * @param interaxialDistance defines distance between each color axis
  91548. * @param scene defines the hosting scene
  91549. */
  91550. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91551. var _this = _super.call(this, name, position, scene) || this;
  91552. _this.interaxialDistance = interaxialDistance;
  91553. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91554. return _this;
  91555. }
  91556. /**
  91557. * Gets camera class name
  91558. * @returns AnaglyphUniversalCamera
  91559. */
  91560. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91561. return "AnaglyphUniversalCamera";
  91562. };
  91563. return AnaglyphUniversalCamera;
  91564. }(BABYLON.UniversalCamera));
  91565. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91566. /**
  91567. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91568. */
  91569. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91570. __extends(StereoscopicFreeCamera, _super);
  91571. /**
  91572. * Creates a new StereoscopicFreeCamera
  91573. * @param name defines camera name
  91574. * @param position defines initial position
  91575. * @param interaxialDistance defines distance between each color axis
  91576. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91577. * @param scene defines the hosting scene
  91578. */
  91579. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91580. var _this = _super.call(this, name, position, scene) || this;
  91581. _this.interaxialDistance = interaxialDistance;
  91582. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91583. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91584. return _this;
  91585. }
  91586. /**
  91587. * Gets camera class name
  91588. * @returns StereoscopicFreeCamera
  91589. */
  91590. StereoscopicFreeCamera.prototype.getClassName = function () {
  91591. return "StereoscopicFreeCamera";
  91592. };
  91593. return StereoscopicFreeCamera;
  91594. }(BABYLON.FreeCamera));
  91595. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91596. /**
  91597. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91598. */
  91599. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91600. __extends(StereoscopicArcRotateCamera, _super);
  91601. /**
  91602. * Creates a new StereoscopicArcRotateCamera
  91603. * @param name defines camera name
  91604. * @param alpha defines alpha angle (in radians)
  91605. * @param beta defines beta angle (in radians)
  91606. * @param radius defines radius
  91607. * @param target defines camera target
  91608. * @param interaxialDistance defines distance between each color axis
  91609. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91610. * @param scene defines the hosting scene
  91611. */
  91612. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91613. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91614. _this.interaxialDistance = interaxialDistance;
  91615. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91616. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91617. return _this;
  91618. }
  91619. /**
  91620. * Gets camera class name
  91621. * @returns StereoscopicArcRotateCamera
  91622. */
  91623. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91624. return "StereoscopicArcRotateCamera";
  91625. };
  91626. return StereoscopicArcRotateCamera;
  91627. }(BABYLON.ArcRotateCamera));
  91628. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91629. /**
  91630. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91631. */
  91632. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91633. __extends(StereoscopicGamepadCamera, _super);
  91634. /**
  91635. * Creates a new StereoscopicGamepadCamera
  91636. * @param name defines camera name
  91637. * @param position defines initial position
  91638. * @param interaxialDistance defines distance between each color axis
  91639. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91640. * @param scene defines the hosting scene
  91641. */
  91642. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91643. var _this = _super.call(this, name, position, scene) || this;
  91644. _this.interaxialDistance = interaxialDistance;
  91645. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91646. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91647. return _this;
  91648. }
  91649. /**
  91650. * Gets camera class name
  91651. * @returns StereoscopicGamepadCamera
  91652. */
  91653. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91654. return "StereoscopicGamepadCamera";
  91655. };
  91656. return StereoscopicGamepadCamera;
  91657. }(BABYLON.GamepadCamera));
  91658. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91659. /**
  91660. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91661. */
  91662. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91663. __extends(StereoscopicUniversalCamera, _super);
  91664. /**
  91665. * Creates a new StereoscopicUniversalCamera
  91666. * @param name defines camera name
  91667. * @param position defines initial position
  91668. * @param interaxialDistance defines distance between each color axis
  91669. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91670. * @param scene defines the hosting scene
  91671. */
  91672. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91673. var _this = _super.call(this, name, position, scene) || this;
  91674. _this.interaxialDistance = interaxialDistance;
  91675. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91676. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91677. return _this;
  91678. }
  91679. /**
  91680. * Gets camera class name
  91681. * @returns StereoscopicUniversalCamera
  91682. */
  91683. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91684. return "StereoscopicUniversalCamera";
  91685. };
  91686. return StereoscopicUniversalCamera;
  91687. }(BABYLON.UniversalCamera));
  91688. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91689. })(BABYLON || (BABYLON = {}));
  91690. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91691. var BABYLON;
  91692. (function (BABYLON) {
  91693. var VRExperienceHelperGazer = /** @class */ (function () {
  91694. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91695. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91696. this.scene = scene;
  91697. this._pointerDownOnMeshAsked = false;
  91698. this._isActionableMesh = false;
  91699. this._teleportationRequestInitiated = false;
  91700. this._teleportationBackRequestInitiated = false;
  91701. this._rotationRightAsked = false;
  91702. this._rotationLeftAsked = false;
  91703. this._dpadPressed = true;
  91704. this._activePointer = false;
  91705. this._id = VRExperienceHelperGazer._idCounter++;
  91706. // Gaze tracker
  91707. if (!gazeTrackerToClone) {
  91708. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91709. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91710. this._gazeTracker.isPickable = false;
  91711. this._gazeTracker.isVisible = false;
  91712. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91713. targetMat.specularColor = BABYLON.Color3.Black();
  91714. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91715. targetMat.backFaceCulling = false;
  91716. this._gazeTracker.material = targetMat;
  91717. }
  91718. else {
  91719. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91720. }
  91721. }
  91722. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91723. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91724. };
  91725. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91726. this._pointerDownOnMeshAsked = true;
  91727. if (this._currentHit) {
  91728. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91729. }
  91730. };
  91731. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91732. if (this._currentHit) {
  91733. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91734. }
  91735. this._pointerDownOnMeshAsked = false;
  91736. };
  91737. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91738. this._activePointer = true;
  91739. };
  91740. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91741. this._activePointer = false;
  91742. };
  91743. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91744. if (distance === void 0) { distance = 100; }
  91745. };
  91746. VRExperienceHelperGazer.prototype.dispose = function () {
  91747. this._interactionsEnabled = false;
  91748. this._teleportationEnabled = false;
  91749. if (this._gazeTracker) {
  91750. this._gazeTracker.dispose();
  91751. }
  91752. };
  91753. VRExperienceHelperGazer._idCounter = 0;
  91754. return VRExperienceHelperGazer;
  91755. }());
  91756. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91757. __extends(VRExperienceHelperControllerGazer, _super);
  91758. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91759. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91760. _this.webVRController = webVRController;
  91761. // Laser pointer
  91762. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91763. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91764. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91765. laserPointerMaterial.alpha = 0.6;
  91766. _this._laserPointer.material = laserPointerMaterial;
  91767. _this._laserPointer.rotation.x = Math.PI / 2;
  91768. _this._laserPointer.position.z = -0.5;
  91769. _this._laserPointer.isVisible = false;
  91770. _this._laserPointer.isPickable = false;
  91771. if (!webVRController.mesh) {
  91772. // Create an empty mesh that is used prior to loading the high quality model
  91773. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91774. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91775. preloadPointerPose.rotation.x = -0.7;
  91776. preloadMesh.addChild(preloadPointerPose);
  91777. webVRController.attachToMesh(preloadMesh);
  91778. }
  91779. _this._setLaserPointerParent(webVRController.mesh);
  91780. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91781. _this._setLaserPointerParent(mesh);
  91782. });
  91783. return _this;
  91784. }
  91785. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91786. return this.webVRController.getForwardRay(length);
  91787. };
  91788. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91789. _super.prototype._activatePointer.call(this);
  91790. this._laserPointer.isVisible = true;
  91791. };
  91792. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91793. _super.prototype._deactivatePointer.call(this);
  91794. this._laserPointer.isVisible = false;
  91795. };
  91796. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91797. this._laserPointer.material.emissiveColor = color;
  91798. };
  91799. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91800. var makeNotPick = function (root) {
  91801. root.name += " laserPointer";
  91802. root.isPickable = false;
  91803. root.getChildMeshes().forEach(function (c) {
  91804. makeNotPick(c);
  91805. });
  91806. };
  91807. makeNotPick(mesh);
  91808. var childMeshes = mesh.getChildMeshes();
  91809. this.webVRController._pointingPoseNode = null;
  91810. for (var i = 0; i < childMeshes.length; i++) {
  91811. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91812. mesh = childMeshes[i];
  91813. this.webVRController._pointingPoseNode = mesh;
  91814. break;
  91815. }
  91816. }
  91817. this._laserPointer.parent = mesh;
  91818. };
  91819. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91820. if (distance === void 0) { distance = 100; }
  91821. this._laserPointer.scaling.y = distance;
  91822. this._laserPointer.position.z = -distance / 2;
  91823. };
  91824. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91825. _super.prototype.dispose.call(this);
  91826. this._laserPointer.dispose();
  91827. if (this._meshAttachedObserver) {
  91828. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  91829. }
  91830. };
  91831. return VRExperienceHelperControllerGazer;
  91832. }(VRExperienceHelperGazer));
  91833. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  91834. __extends(VRExperienceHelperCameraGazer, _super);
  91835. function VRExperienceHelperCameraGazer(getCamera, scene) {
  91836. var _this = _super.call(this, scene) || this;
  91837. _this.getCamera = getCamera;
  91838. return _this;
  91839. }
  91840. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  91841. var camera = this.getCamera();
  91842. if (camera) {
  91843. return camera.getForwardRay(length);
  91844. }
  91845. else {
  91846. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  91847. }
  91848. };
  91849. return VRExperienceHelperCameraGazer;
  91850. }(VRExperienceHelperGazer));
  91851. /**
  91852. * Helps to quickly add VR support to an existing scene.
  91853. * See http://doc.babylonjs.com/how_to/webvr_helper
  91854. */
  91855. var VRExperienceHelper = /** @class */ (function () {
  91856. /**
  91857. * Instantiates a VRExperienceHelper.
  91858. * Helps to quickly add VR support to an existing scene.
  91859. * @param scene The scene the VRExperienceHelper belongs to.
  91860. * @param webVROptions Options to modify the vr experience helper's behavior.
  91861. */
  91862. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  91863. if (webVROptions === void 0) { webVROptions = {}; }
  91864. var _this = this;
  91865. this.webVROptions = webVROptions;
  91866. // Can the system support WebVR, even if a headset isn't plugged in?
  91867. this._webVRsupported = false;
  91868. // If WebVR is supported, is a headset plugged in and are we ready to present?
  91869. this._webVRready = false;
  91870. // Are we waiting for the requestPresent callback to complete?
  91871. this._webVRrequesting = false;
  91872. // Are we presenting to the headset right now?
  91873. this._webVRpresenting = false;
  91874. // Are we presenting in the fullscreen fallback?
  91875. this._fullscreenVRpresenting = false;
  91876. /**
  91877. * Observable raised when entering VR.
  91878. */
  91879. this.onEnteringVRObservable = new BABYLON.Observable();
  91880. /**
  91881. * Observable raised when exiting VR.
  91882. */
  91883. this.onExitingVRObservable = new BABYLON.Observable();
  91884. /**
  91885. * Observable raised when controller mesh is loaded.
  91886. */
  91887. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91888. this._useCustomVRButton = false;
  91889. this._teleportationRequested = false;
  91890. this._teleportActive = false;
  91891. this._floorMeshesCollection = [];
  91892. this._rotationAllowed = true;
  91893. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  91894. this._isDefaultTeleportationTarget = true;
  91895. this._teleportationFillColor = "#444444";
  91896. this._teleportationBorderColor = "#FFFFFF";
  91897. this._rotationAngle = 0;
  91898. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  91899. this._padSensibilityUp = 0.65;
  91900. this._padSensibilityDown = 0.35;
  91901. this.leftController = null;
  91902. this.rightController = null;
  91903. /**
  91904. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  91905. */
  91906. this.onNewMeshSelected = new BABYLON.Observable();
  91907. /**
  91908. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  91909. */
  91910. this.onNewMeshPicked = new BABYLON.Observable();
  91911. /**
  91912. * Observable raised before camera teleportation
  91913. */
  91914. this.onBeforeCameraTeleport = new BABYLON.Observable();
  91915. /**
  91916. * Observable raised after camera teleportation
  91917. */
  91918. this.onAfterCameraTeleport = new BABYLON.Observable();
  91919. /**
  91920. * Observable raised when current selected mesh gets unselected
  91921. */
  91922. this.onSelectedMeshUnselected = new BABYLON.Observable();
  91923. /**
  91924. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  91925. */
  91926. this.teleportationEnabled = true;
  91927. this._teleportationInitialized = false;
  91928. this._interactionsEnabled = false;
  91929. this._interactionsRequested = false;
  91930. this._displayGaze = true;
  91931. this._displayLaserPointer = true;
  91932. this._onResize = function () {
  91933. _this.moveButtonToBottomRight();
  91934. if (_this._fullscreenVRpresenting && _this._webVRready) {
  91935. _this.exitVR();
  91936. }
  91937. };
  91938. this._onFullscreenChange = function () {
  91939. if (document.fullscreen !== undefined) {
  91940. _this._fullscreenVRpresenting = document.fullscreen;
  91941. }
  91942. else if (document.mozFullScreen !== undefined) {
  91943. _this._fullscreenVRpresenting = document.mozFullScreen;
  91944. }
  91945. else if (document.webkitIsFullScreen !== undefined) {
  91946. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  91947. }
  91948. else if (document.msIsFullScreen !== undefined) {
  91949. _this._fullscreenVRpresenting = document.msIsFullScreen;
  91950. }
  91951. else if (document.msFullscreenElement !== undefined) {
  91952. _this._fullscreenVRpresenting = document.msFullscreenElement;
  91953. }
  91954. if (!_this._fullscreenVRpresenting && _this._canvas) {
  91955. _this.exitVR();
  91956. if (!_this._useCustomVRButton) {
  91957. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  91958. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  91959. }
  91960. }
  91961. };
  91962. this.beforeRender = function () {
  91963. if (_this.leftController && _this.leftController._activePointer) {
  91964. _this._castRayAndSelectObject(_this.leftController);
  91965. }
  91966. if (_this.rightController && _this.rightController._activePointer) {
  91967. _this._castRayAndSelectObject(_this.rightController);
  91968. }
  91969. if (_this._noControllerIsActive) {
  91970. _this._castRayAndSelectObject(_this._cameraGazer);
  91971. }
  91972. else {
  91973. _this._cameraGazer._gazeTracker.isVisible = false;
  91974. }
  91975. };
  91976. this._onNewGamepadConnected = function (gamepad) {
  91977. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  91978. if (gamepad.leftStick) {
  91979. gamepad.onleftstickchanged(function (stickValues) {
  91980. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  91981. // Listening to classic/xbox gamepad only if no VR controller is active
  91982. if ((!_this.leftController && !_this.rightController) ||
  91983. ((_this.leftController && !_this.leftController._activePointer) &&
  91984. (_this.rightController && !_this.rightController._activePointer))) {
  91985. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  91986. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  91987. }
  91988. }
  91989. });
  91990. }
  91991. if (gamepad.rightStick) {
  91992. gamepad.onrightstickchanged(function (stickValues) {
  91993. if (_this._teleportationInitialized) {
  91994. _this._checkRotate(stickValues, _this._cameraGazer);
  91995. }
  91996. });
  91997. }
  91998. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  91999. gamepad.onbuttondown(function (buttonPressed) {
  92000. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92001. _this._cameraGazer._selectionPointerDown();
  92002. }
  92003. });
  92004. gamepad.onbuttonup(function (buttonPressed) {
  92005. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92006. _this._cameraGazer._selectionPointerUp();
  92007. }
  92008. });
  92009. }
  92010. }
  92011. else {
  92012. var webVRController = gamepad;
  92013. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92014. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92015. _this.rightController = controller;
  92016. }
  92017. else {
  92018. _this.leftController = controller;
  92019. }
  92020. _this._tryEnableInteractionOnController(controller);
  92021. }
  92022. };
  92023. // 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
  92024. this._tryEnableInteractionOnController = function (controller) {
  92025. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92026. _this._enableInteractionOnController(controller);
  92027. }
  92028. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92029. _this._enableTeleportationOnController(controller);
  92030. }
  92031. };
  92032. this._onNewGamepadDisconnected = function (gamepad) {
  92033. if (gamepad instanceof BABYLON.WebVRController) {
  92034. if (gamepad.hand === "left" && _this.leftController != null) {
  92035. _this.leftController.dispose();
  92036. _this.leftController = null;
  92037. }
  92038. if (gamepad.hand === "right" && _this.rightController != null) {
  92039. _this.rightController.dispose();
  92040. _this.rightController = null;
  92041. }
  92042. }
  92043. };
  92044. this._workingVector = BABYLON.Vector3.Zero();
  92045. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92046. this._workingMatrix = BABYLON.Matrix.Identity();
  92047. this._scene = scene;
  92048. this._canvas = scene.getEngine().getRenderingCanvas();
  92049. // Parse options
  92050. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92051. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92052. }
  92053. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92054. webVROptions.createDeviceOrientationCamera = true;
  92055. }
  92056. if (webVROptions.laserToggle === undefined) {
  92057. webVROptions.laserToggle = true;
  92058. }
  92059. if (webVROptions.defaultHeight === undefined) {
  92060. webVROptions.defaultHeight = 1.7;
  92061. }
  92062. if (webVROptions.useCustomVRButton) {
  92063. this._useCustomVRButton = true;
  92064. if (webVROptions.customVRButton) {
  92065. this._btnVR = webVROptions.customVRButton;
  92066. }
  92067. }
  92068. if (webVROptions.rayLength) {
  92069. this._rayLength = webVROptions.rayLength;
  92070. }
  92071. this._defaultHeight = webVROptions.defaultHeight;
  92072. if (webVROptions.positionScale) {
  92073. this._rayLength *= webVROptions.positionScale;
  92074. this._defaultHeight *= webVROptions.positionScale;
  92075. }
  92076. // Set position
  92077. if (this._scene.activeCamera) {
  92078. this._position = this._scene.activeCamera.position.clone();
  92079. }
  92080. else {
  92081. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92082. }
  92083. // Set non-vr camera
  92084. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92085. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92086. // Copy data from existing camera
  92087. if (this._scene.activeCamera) {
  92088. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92089. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92090. // Set rotation from previous camera
  92091. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92092. var targetCamera = this._scene.activeCamera;
  92093. if (targetCamera.rotationQuaternion) {
  92094. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92095. }
  92096. else {
  92097. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92098. }
  92099. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92100. }
  92101. }
  92102. this._scene.activeCamera = this._deviceOrientationCamera;
  92103. if (this._canvas) {
  92104. this._scene.activeCamera.attachControl(this._canvas);
  92105. }
  92106. }
  92107. else {
  92108. this._existingCamera = this._scene.activeCamera;
  92109. }
  92110. // Create VR cameras
  92111. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92112. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92113. }
  92114. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92115. this._webVRCamera.useStandingMatrix();
  92116. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92117. // Create default button
  92118. if (!this._useCustomVRButton) {
  92119. this._btnVR = document.createElement("BUTTON");
  92120. this._btnVR.className = "babylonVRicon";
  92121. this._btnVR.id = "babylonVRiconbtn";
  92122. this._btnVR.title = "Click to switch to VR";
  92123. 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) }";
  92124. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92125. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92126. // css += ".babylonVRicon.vrdisplaysupported { }";
  92127. // css += ".babylonVRicon.vrdisplayready { }";
  92128. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92129. var style = document.createElement('style');
  92130. style.appendChild(document.createTextNode(css));
  92131. document.getElementsByTagName('head')[0].appendChild(style);
  92132. this.moveButtonToBottomRight();
  92133. }
  92134. // VR button click event
  92135. if (this._btnVR) {
  92136. this._btnVR.addEventListener("click", function () {
  92137. if (!_this.isInVRMode) {
  92138. _this.enterVR();
  92139. }
  92140. else {
  92141. _this.exitVR();
  92142. }
  92143. });
  92144. }
  92145. // Window events
  92146. window.addEventListener("resize", this._onResize);
  92147. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92148. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92149. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92150. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92151. document.onmsfullscreenchange = this._onFullscreenChange;
  92152. // Display vr button when headset is connected
  92153. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92154. this.displayVRButton();
  92155. }
  92156. else {
  92157. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92158. if (e.vrDisplay) {
  92159. _this.displayVRButton();
  92160. }
  92161. });
  92162. }
  92163. // Exiting VR mode using 'ESC' key on desktop
  92164. this._onKeyDown = function (event) {
  92165. if (event.keyCode === 27 && _this.isInVRMode) {
  92166. _this.exitVR();
  92167. }
  92168. };
  92169. document.addEventListener("keydown", this._onKeyDown);
  92170. // Exiting VR mode double tapping the touch screen
  92171. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92172. if (_this.isInVRMode) {
  92173. _this.exitVR();
  92174. if (_this._fullscreenVRpresenting) {
  92175. _this._scene.getEngine().switchFullscreen(true);
  92176. }
  92177. }
  92178. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92179. // Listen for WebVR display changes
  92180. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92181. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92182. this._onVRRequestPresentStart = function () {
  92183. _this._webVRrequesting = true;
  92184. _this.updateButtonVisibility();
  92185. };
  92186. this._onVRRequestPresentComplete = function (success) {
  92187. _this._webVRrequesting = false;
  92188. _this.updateButtonVisibility();
  92189. };
  92190. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92191. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92192. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92193. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92194. scene.onDisposeObservable.add(function () {
  92195. _this.dispose();
  92196. });
  92197. // Gamepad connection events
  92198. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92199. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92200. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92201. this.updateButtonVisibility();
  92202. //create easing functions
  92203. this._circleEase = new BABYLON.CircleEase();
  92204. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92205. if (this.webVROptions.floorMeshes) {
  92206. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92207. }
  92208. }
  92209. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92210. /** Return this.onEnteringVRObservable
  92211. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92212. */
  92213. get: function () {
  92214. return this.onEnteringVRObservable;
  92215. },
  92216. enumerable: true,
  92217. configurable: true
  92218. });
  92219. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92220. /** Return this.onExitingVRObservable
  92221. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92222. */
  92223. get: function () {
  92224. return this.onExitingVRObservable;
  92225. },
  92226. enumerable: true,
  92227. configurable: true
  92228. });
  92229. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92230. /** Return this.onControllerMeshLoadedObservable
  92231. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92232. */
  92233. get: function () {
  92234. return this.onControllerMeshLoadedObservable;
  92235. },
  92236. enumerable: true,
  92237. configurable: true
  92238. });
  92239. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92240. /**
  92241. * The mesh used to display where the user is going to teleport.
  92242. */
  92243. get: function () {
  92244. return this._teleportationTarget;
  92245. },
  92246. /**
  92247. * Sets the mesh to be used to display where the user is going to teleport.
  92248. */
  92249. set: function (value) {
  92250. if (value) {
  92251. value.name = "teleportationTarget";
  92252. this._isDefaultTeleportationTarget = false;
  92253. this._teleportationTarget = value;
  92254. }
  92255. },
  92256. enumerable: true,
  92257. configurable: true
  92258. });
  92259. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92260. /**
  92261. * The mesh used to display where the user is selecting,
  92262. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92263. * See http://doc.babylonjs.com/resources/baking_transformations
  92264. */
  92265. get: function () {
  92266. return this._cameraGazer._gazeTracker;
  92267. },
  92268. set: function (value) {
  92269. if (value) {
  92270. this._cameraGazer._gazeTracker = value;
  92271. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92272. this._cameraGazer._gazeTracker.isPickable = false;
  92273. this._cameraGazer._gazeTracker.isVisible = false;
  92274. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92275. if (this.leftController) {
  92276. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92277. }
  92278. if (this.rightController) {
  92279. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92280. }
  92281. }
  92282. },
  92283. enumerable: true,
  92284. configurable: true
  92285. });
  92286. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92287. /**
  92288. * If the ray of the gaze should be displayed.
  92289. */
  92290. get: function () {
  92291. return this._displayGaze;
  92292. },
  92293. /**
  92294. * Sets if the ray of the gaze should be displayed.
  92295. */
  92296. set: function (value) {
  92297. this._displayGaze = value;
  92298. if (!value) {
  92299. this._cameraGazer._gazeTracker.isVisible = false;
  92300. if (this.leftController) {
  92301. this.leftController._gazeTracker.isVisible = false;
  92302. }
  92303. if (this.rightController) {
  92304. this.rightController._gazeTracker.isVisible = false;
  92305. }
  92306. }
  92307. },
  92308. enumerable: true,
  92309. configurable: true
  92310. });
  92311. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92312. /**
  92313. * If the ray of the LaserPointer should be displayed.
  92314. */
  92315. get: function () {
  92316. return this._displayLaserPointer;
  92317. },
  92318. /**
  92319. * Sets if the ray of the LaserPointer should be displayed.
  92320. */
  92321. set: function (value) {
  92322. this._displayLaserPointer = value;
  92323. if (!value) {
  92324. if (this.rightController) {
  92325. this.rightController._deactivatePointer();
  92326. this.rightController._gazeTracker.isVisible = false;
  92327. }
  92328. if (this.leftController) {
  92329. this.leftController._deactivatePointer();
  92330. this.leftController._gazeTracker.isVisible = false;
  92331. }
  92332. }
  92333. else {
  92334. if (this.rightController) {
  92335. this.rightController._activatePointer();
  92336. }
  92337. if (this.leftController) {
  92338. this.leftController._activatePointer();
  92339. }
  92340. }
  92341. },
  92342. enumerable: true,
  92343. configurable: true
  92344. });
  92345. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92346. /**
  92347. * The deviceOrientationCamera used as the camera when not in VR.
  92348. */
  92349. get: function () {
  92350. return this._deviceOrientationCamera;
  92351. },
  92352. enumerable: true,
  92353. configurable: true
  92354. });
  92355. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92356. /**
  92357. * Based on the current WebVR support, returns the current VR camera used.
  92358. */
  92359. get: function () {
  92360. if (this._webVRready) {
  92361. return this._webVRCamera;
  92362. }
  92363. else {
  92364. return this._scene.activeCamera;
  92365. }
  92366. },
  92367. enumerable: true,
  92368. configurable: true
  92369. });
  92370. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92371. /**
  92372. * The webVRCamera which is used when in VR.
  92373. */
  92374. get: function () {
  92375. return this._webVRCamera;
  92376. },
  92377. enumerable: true,
  92378. configurable: true
  92379. });
  92380. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92381. /**
  92382. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92383. */
  92384. get: function () {
  92385. return this._vrDeviceOrientationCamera;
  92386. },
  92387. enumerable: true,
  92388. configurable: true
  92389. });
  92390. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92391. get: function () {
  92392. var result = this._cameraGazer._teleportationRequestInitiated
  92393. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92394. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92395. return result;
  92396. },
  92397. enumerable: true,
  92398. configurable: true
  92399. });
  92400. // Raised when one of the controller has loaded successfully its associated default mesh
  92401. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92402. if (this.leftController && this.leftController.webVRController == webVRController) {
  92403. if (webVRController.mesh) {
  92404. this.leftController._setLaserPointerParent(webVRController.mesh);
  92405. }
  92406. }
  92407. if (this.rightController && this.rightController.webVRController == webVRController) {
  92408. if (webVRController.mesh) {
  92409. this.rightController._setLaserPointerParent(webVRController.mesh);
  92410. }
  92411. }
  92412. try {
  92413. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  92414. }
  92415. catch (err) {
  92416. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  92417. }
  92418. };
  92419. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  92420. /**
  92421. * Gets a value indicating if we are currently in VR mode.
  92422. */
  92423. get: function () {
  92424. return this._webVRpresenting || this._fullscreenVRpresenting;
  92425. },
  92426. enumerable: true,
  92427. configurable: true
  92428. });
  92429. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92430. var vrDisplay = this._scene.getEngine().getVRDevice();
  92431. if (vrDisplay) {
  92432. var wasPresenting = this._webVRpresenting;
  92433. // A VR display is connected
  92434. this._webVRpresenting = vrDisplay.isPresenting;
  92435. if (wasPresenting && !this._webVRpresenting)
  92436. this.exitVR();
  92437. }
  92438. else {
  92439. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92440. }
  92441. this.updateButtonVisibility();
  92442. };
  92443. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92444. this._webVRsupported = eventArgs.vrSupported;
  92445. this._webVRready = !!eventArgs.vrDisplay;
  92446. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92447. this.updateButtonVisibility();
  92448. };
  92449. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92450. if (this._canvas && !this._useCustomVRButton) {
  92451. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92452. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92453. }
  92454. };
  92455. VRExperienceHelper.prototype.displayVRButton = function () {
  92456. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92457. document.body.appendChild(this._btnVR);
  92458. this._btnVRDisplayed = true;
  92459. }
  92460. };
  92461. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92462. if (!this._btnVR || this._useCustomVRButton) {
  92463. return;
  92464. }
  92465. this._btnVR.className = "babylonVRicon";
  92466. if (this.isInVRMode) {
  92467. this._btnVR.className += " vrdisplaypresenting";
  92468. }
  92469. else {
  92470. if (this._webVRready)
  92471. this._btnVR.className += " vrdisplayready";
  92472. if (this._webVRsupported)
  92473. this._btnVR.className += " vrdisplaysupported";
  92474. if (this._webVRrequesting)
  92475. this._btnVR.className += " vrdisplayrequesting";
  92476. }
  92477. };
  92478. /**
  92479. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92480. * Otherwise, will use the fullscreen API.
  92481. */
  92482. VRExperienceHelper.prototype.enterVR = function () {
  92483. if (this.onEnteringVRObservable) {
  92484. try {
  92485. this.onEnteringVRObservable.notifyObservers(this);
  92486. }
  92487. catch (err) {
  92488. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92489. }
  92490. }
  92491. if (this._scene.activeCamera) {
  92492. this._position = this._scene.activeCamera.position.clone();
  92493. // make sure that we return to the last active camera
  92494. this._existingCamera = this._scene.activeCamera;
  92495. }
  92496. if (this._webVRrequesting)
  92497. return;
  92498. // If WebVR is supported and a headset is connected
  92499. if (this._webVRready) {
  92500. if (!this._webVRpresenting) {
  92501. this._webVRCamera.position = this._position;
  92502. this._scene.activeCamera = this._webVRCamera;
  92503. }
  92504. }
  92505. else if (this._vrDeviceOrientationCamera) {
  92506. this._vrDeviceOrientationCamera.position = this._position;
  92507. if (this._scene.activeCamera) {
  92508. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92509. }
  92510. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92511. this._scene.getEngine().switchFullscreen(true);
  92512. this.updateButtonVisibility();
  92513. }
  92514. if (this._scene.activeCamera && this._canvas) {
  92515. this._scene.activeCamera.attachControl(this._canvas);
  92516. }
  92517. if (this._interactionsEnabled) {
  92518. this._scene.registerBeforeRender(this.beforeRender);
  92519. }
  92520. };
  92521. /**
  92522. * Attempt to exit VR, or fullscreen.
  92523. */
  92524. VRExperienceHelper.prototype.exitVR = function () {
  92525. if (this.onExitingVRObservable) {
  92526. try {
  92527. this.onExitingVRObservable.notifyObservers(this);
  92528. }
  92529. catch (err) {
  92530. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92531. }
  92532. }
  92533. if (this._webVRpresenting) {
  92534. this._scene.getEngine().disableVR();
  92535. }
  92536. if (this._scene.activeCamera) {
  92537. this._position = this._scene.activeCamera.position.clone();
  92538. }
  92539. if (this._deviceOrientationCamera) {
  92540. this._deviceOrientationCamera.position = this._position;
  92541. this._scene.activeCamera = this._deviceOrientationCamera;
  92542. if (this._canvas) {
  92543. this._scene.activeCamera.attachControl(this._canvas);
  92544. }
  92545. }
  92546. else if (this._existingCamera) {
  92547. this._existingCamera.position = this._position;
  92548. this._scene.activeCamera = this._existingCamera;
  92549. }
  92550. this.updateButtonVisibility();
  92551. if (this._interactionsEnabled) {
  92552. this._scene.unregisterBeforeRender(this.beforeRender);
  92553. }
  92554. // resize to update width and height when exiting vr exits fullscreen
  92555. this._scene.getEngine().resize();
  92556. };
  92557. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92558. /**
  92559. * The position of the vr experience helper.
  92560. */
  92561. get: function () {
  92562. return this._position;
  92563. },
  92564. /**
  92565. * Sets the position of the vr experience helper.
  92566. */
  92567. set: function (value) {
  92568. this._position = value;
  92569. if (this._scene.activeCamera) {
  92570. this._scene.activeCamera.position = value;
  92571. }
  92572. },
  92573. enumerable: true,
  92574. configurable: true
  92575. });
  92576. /**
  92577. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92578. */
  92579. VRExperienceHelper.prototype.enableInteractions = function () {
  92580. var _this = this;
  92581. if (!this._interactionsEnabled) {
  92582. this._interactionsRequested = true;
  92583. if (this.leftController) {
  92584. this._enableInteractionOnController(this.leftController);
  92585. }
  92586. if (this.rightController) {
  92587. this._enableInteractionOnController(this.rightController);
  92588. }
  92589. this.raySelectionPredicate = function (mesh) {
  92590. return mesh.isVisible;
  92591. };
  92592. this.meshSelectionPredicate = function (mesh) {
  92593. return true;
  92594. };
  92595. this._raySelectionPredicate = function (mesh) {
  92596. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92597. && mesh.name.indexOf("teleportationTarget") === -1
  92598. && mesh.name.indexOf("torusTeleportation") === -1
  92599. && mesh.name.indexOf("laserPointer") === -1)) {
  92600. return _this.raySelectionPredicate(mesh);
  92601. }
  92602. return false;
  92603. };
  92604. this._interactionsEnabled = true;
  92605. }
  92606. };
  92607. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  92608. get: function () {
  92609. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  92610. },
  92611. enumerable: true,
  92612. configurable: true
  92613. });
  92614. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92615. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92616. if (this._floorMeshesCollection[i].id === mesh.id) {
  92617. return true;
  92618. }
  92619. }
  92620. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92621. return true;
  92622. }
  92623. return false;
  92624. };
  92625. /**
  92626. * Adds a floor mesh to be used for teleportation.
  92627. * @param floorMesh the mesh to be used for teleportation.
  92628. */
  92629. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92630. if (!this._floorMeshesCollection) {
  92631. return;
  92632. }
  92633. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92634. return;
  92635. }
  92636. this._floorMeshesCollection.push(floorMesh);
  92637. };
  92638. /**
  92639. * Removes a floor mesh from being used for teleportation.
  92640. * @param floorMesh the mesh to be removed.
  92641. */
  92642. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92643. if (!this._floorMeshesCollection) {
  92644. return;
  92645. }
  92646. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92647. if (meshIndex !== -1) {
  92648. this._floorMeshesCollection.splice(meshIndex, 1);
  92649. }
  92650. };
  92651. /**
  92652. * Enables interactions and teleportation using the VR controllers and gaze.
  92653. * @param vrTeleportationOptions options to modify teleportation behavior.
  92654. */
  92655. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92656. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92657. if (!this._teleportationInitialized) {
  92658. this._teleportationRequested = true;
  92659. this.enableInteractions();
  92660. if (vrTeleportationOptions.floorMeshName) {
  92661. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92662. }
  92663. if (vrTeleportationOptions.floorMeshes) {
  92664. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92665. }
  92666. if (this.leftController != null) {
  92667. this._enableTeleportationOnController(this.leftController);
  92668. }
  92669. if (this.rightController != null) {
  92670. this._enableTeleportationOnController(this.rightController);
  92671. }
  92672. // Creates an image processing post process for the vignette not relying
  92673. // on the main scene configuration for image processing to reduce setup and spaces
  92674. // (gamma/linear) conflicts.
  92675. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92676. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92677. imageProcessingConfiguration.vignetteEnabled = true;
  92678. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92679. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92680. this._teleportationInitialized = true;
  92681. if (this._isDefaultTeleportationTarget) {
  92682. this._createTeleportationCircles();
  92683. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92684. }
  92685. }
  92686. };
  92687. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92688. var _this = this;
  92689. var controllerMesh = controller.webVRController.mesh;
  92690. if (controllerMesh) {
  92691. controller._interactionsEnabled = true;
  92692. controller._activatePointer();
  92693. if (this.webVROptions.laserToggle) {
  92694. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92695. // Enabling / disabling laserPointer
  92696. if (_this._displayLaserPointer && stateObject.value === 1) {
  92697. if (controller._activePointer) {
  92698. controller._deactivatePointer();
  92699. }
  92700. else {
  92701. controller._activatePointer();
  92702. }
  92703. if (_this.displayGaze) {
  92704. controller._gazeTracker.isVisible = controller._activePointer;
  92705. }
  92706. }
  92707. });
  92708. }
  92709. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92710. var gazer = controller;
  92711. if (_this._noControllerIsActive) {
  92712. gazer = _this._cameraGazer;
  92713. }
  92714. if (!gazer._pointerDownOnMeshAsked) {
  92715. if (stateObject.value > _this._padSensibilityUp) {
  92716. gazer._selectionPointerDown();
  92717. }
  92718. }
  92719. else if (stateObject.value < _this._padSensibilityDown) {
  92720. gazer._selectionPointerUp();
  92721. }
  92722. });
  92723. }
  92724. };
  92725. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92726. // Dont teleport if another gaze already requested teleportation
  92727. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92728. return;
  92729. }
  92730. if (!gazer._teleportationRequestInitiated) {
  92731. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92732. gazer._activatePointer();
  92733. gazer._teleportationRequestInitiated = true;
  92734. }
  92735. }
  92736. else {
  92737. // Listening to the proper controller values changes to confirm teleportation
  92738. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92739. if (this._teleportActive) {
  92740. this._teleportCamera(this._haloCenter);
  92741. }
  92742. gazer._teleportationRequestInitiated = false;
  92743. }
  92744. }
  92745. };
  92746. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92747. // Only rotate when user is not currently selecting a teleportation location
  92748. if (gazer._teleportationRequestInitiated) {
  92749. return;
  92750. }
  92751. if (!gazer._rotationLeftAsked) {
  92752. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92753. gazer._rotationLeftAsked = true;
  92754. if (this._rotationAllowed) {
  92755. this._rotateCamera(false);
  92756. }
  92757. }
  92758. }
  92759. else {
  92760. if (stateObject.x > -this._padSensibilityDown) {
  92761. gazer._rotationLeftAsked = false;
  92762. }
  92763. }
  92764. if (!gazer._rotationRightAsked) {
  92765. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92766. gazer._rotationRightAsked = true;
  92767. if (this._rotationAllowed) {
  92768. this._rotateCamera(true);
  92769. }
  92770. }
  92771. }
  92772. else {
  92773. if (stateObject.x < this._padSensibilityDown) {
  92774. gazer._rotationRightAsked = false;
  92775. }
  92776. }
  92777. };
  92778. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92779. // Only teleport backwards when user is not currently selecting a teleportation location
  92780. if (gazer._teleportationRequestInitiated) {
  92781. return;
  92782. }
  92783. // Teleport backwards
  92784. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92785. if (!gazer._teleportationBackRequestInitiated) {
  92786. if (!this.currentVRCamera) {
  92787. return;
  92788. }
  92789. // Get rotation and position of the current camera
  92790. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92791. var position = this.currentVRCamera.position;
  92792. // If the camera has device position, use that instead
  92793. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92794. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92795. position = this.currentVRCamera.devicePosition;
  92796. }
  92797. // Get matrix with only the y rotation of the device rotation
  92798. rotation.toEulerAnglesToRef(this._workingVector);
  92799. this._workingVector.z = 0;
  92800. this._workingVector.x = 0;
  92801. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92802. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92803. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92804. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92805. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92806. var ray = new BABYLON.Ray(position, this._workingVector);
  92807. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92808. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92809. this._teleportCamera(hit.pickedPoint);
  92810. }
  92811. gazer._teleportationBackRequestInitiated = true;
  92812. }
  92813. }
  92814. else {
  92815. gazer._teleportationBackRequestInitiated = false;
  92816. }
  92817. };
  92818. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92819. var _this = this;
  92820. var controllerMesh = controller.webVRController.mesh;
  92821. if (controllerMesh) {
  92822. if (!controller._interactionsEnabled) {
  92823. this._enableInteractionOnController(controller);
  92824. }
  92825. controller._interactionsEnabled = true;
  92826. controller._teleportationEnabled = true;
  92827. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  92828. controller._dpadPressed = false;
  92829. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  92830. controller._dpadPressed = stateObject.pressed;
  92831. if (!controller._dpadPressed) {
  92832. controller._rotationLeftAsked = false;
  92833. controller._rotationRightAsked = false;
  92834. controller._teleportationBackRequestInitiated = false;
  92835. }
  92836. });
  92837. }
  92838. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  92839. if (_this.teleportationEnabled) {
  92840. _this._checkTeleportBackwards(stateObject, controller);
  92841. _this._checkTeleportWithRay(stateObject, controller);
  92842. }
  92843. _this._checkRotate(stateObject, controller);
  92844. });
  92845. }
  92846. };
  92847. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  92848. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  92849. this._teleportationTarget.isPickable = false;
  92850. var length = 512;
  92851. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  92852. dynamicTexture.hasAlpha = true;
  92853. var context = dynamicTexture.getContext();
  92854. var centerX = length / 2;
  92855. var centerY = length / 2;
  92856. var radius = 200;
  92857. context.beginPath();
  92858. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  92859. context.fillStyle = this._teleportationFillColor;
  92860. context.fill();
  92861. context.lineWidth = 10;
  92862. context.strokeStyle = this._teleportationBorderColor;
  92863. context.stroke();
  92864. context.closePath();
  92865. dynamicTexture.update();
  92866. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  92867. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  92868. this._teleportationTarget.material = teleportationCircleMaterial;
  92869. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  92870. torus.isPickable = false;
  92871. torus.parent = this._teleportationTarget;
  92872. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  92873. var keys = [];
  92874. keys.push({
  92875. frame: 0,
  92876. value: 0
  92877. });
  92878. keys.push({
  92879. frame: 30,
  92880. value: 0.4
  92881. });
  92882. keys.push({
  92883. frame: 60,
  92884. value: 0
  92885. });
  92886. animationInnerCircle.setKeys(keys);
  92887. var easingFunction = new BABYLON.SineEase();
  92888. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92889. animationInnerCircle.setEasingFunction(easingFunction);
  92890. torus.animations = [];
  92891. torus.animations.push(animationInnerCircle);
  92892. this._scene.beginAnimation(torus, 0, 60, true);
  92893. this._hideTeleportationTarget();
  92894. };
  92895. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  92896. this._teleportActive = true;
  92897. if (this._teleportationInitialized) {
  92898. this._teleportationTarget.isVisible = true;
  92899. if (this._isDefaultTeleportationTarget) {
  92900. this._teleportationTarget.getChildren()[0].isVisible = true;
  92901. }
  92902. }
  92903. };
  92904. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  92905. this._teleportActive = false;
  92906. if (this._teleportationInitialized) {
  92907. this._teleportationTarget.isVisible = false;
  92908. if (this._isDefaultTeleportationTarget) {
  92909. this._teleportationTarget.getChildren()[0].isVisible = false;
  92910. }
  92911. }
  92912. };
  92913. VRExperienceHelper.prototype._rotateCamera = function (right) {
  92914. var _this = this;
  92915. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  92916. return;
  92917. }
  92918. if (right) {
  92919. this._rotationAngle++;
  92920. }
  92921. else {
  92922. this._rotationAngle--;
  92923. }
  92924. this.currentVRCamera.animations = [];
  92925. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  92926. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92927. var animationRotationKeys = [];
  92928. animationRotationKeys.push({
  92929. frame: 0,
  92930. value: this.currentVRCamera.rotationQuaternion
  92931. });
  92932. animationRotationKeys.push({
  92933. frame: 6,
  92934. value: target
  92935. });
  92936. animationRotation.setKeys(animationRotationKeys);
  92937. animationRotation.setEasingFunction(this._circleEase);
  92938. this.currentVRCamera.animations.push(animationRotation);
  92939. this._postProcessMove.animations = [];
  92940. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92941. var vignetteWeightKeys = [];
  92942. vignetteWeightKeys.push({
  92943. frame: 0,
  92944. value: 0
  92945. });
  92946. vignetteWeightKeys.push({
  92947. frame: 3,
  92948. value: 4
  92949. });
  92950. vignetteWeightKeys.push({
  92951. frame: 6,
  92952. value: 0
  92953. });
  92954. animationPP.setKeys(vignetteWeightKeys);
  92955. animationPP.setEasingFunction(this._circleEase);
  92956. this._postProcessMove.animations.push(animationPP);
  92957. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  92958. var vignetteStretchKeys = [];
  92959. vignetteStretchKeys.push({
  92960. frame: 0,
  92961. value: 0
  92962. });
  92963. vignetteStretchKeys.push({
  92964. frame: 3,
  92965. value: 10
  92966. });
  92967. vignetteStretchKeys.push({
  92968. frame: 6,
  92969. value: 0
  92970. });
  92971. animationPP2.setKeys(vignetteStretchKeys);
  92972. animationPP2.setEasingFunction(this._circleEase);
  92973. this._postProcessMove.animations.push(animationPP2);
  92974. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  92975. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  92976. this._postProcessMove.samples = 4;
  92977. this._webVRCamera.attachPostProcess(this._postProcessMove);
  92978. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  92979. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  92980. });
  92981. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  92982. };
  92983. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  92984. if (hit.pickedPoint) {
  92985. if (gazer._teleportationRequestInitiated) {
  92986. this._displayTeleportationTarget();
  92987. this._haloCenter.copyFrom(hit.pickedPoint);
  92988. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  92989. }
  92990. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  92991. if (pickNormal) {
  92992. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  92993. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  92994. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  92995. }
  92996. this._teleportationTarget.position.y += 0.1;
  92997. }
  92998. };
  92999. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93000. var _this = this;
  93001. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93002. return;
  93003. }
  93004. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93005. // offset of the headset from the anchor.
  93006. if (this.webVRCamera.leftCamera) {
  93007. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93008. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93009. location.subtractToRef(this._workingVector, this._workingVector);
  93010. }
  93011. else {
  93012. this._workingVector.copyFrom(location);
  93013. }
  93014. // Add height to account for user's height offset
  93015. if (this.isInVRMode) {
  93016. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93017. }
  93018. else {
  93019. this._workingVector.y += this._defaultHeight;
  93020. }
  93021. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93022. // Create animation from the camera's position to the new location
  93023. this.currentVRCamera.animations = [];
  93024. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93025. var animationCameraTeleportationKeys = [{
  93026. frame: 0,
  93027. value: this.currentVRCamera.position
  93028. },
  93029. {
  93030. frame: 11,
  93031. value: this._workingVector
  93032. }
  93033. ];
  93034. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93035. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93036. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93037. this._postProcessMove.animations = [];
  93038. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93039. var vignetteWeightKeys = [];
  93040. vignetteWeightKeys.push({
  93041. frame: 0,
  93042. value: 0
  93043. });
  93044. vignetteWeightKeys.push({
  93045. frame: 5,
  93046. value: 8
  93047. });
  93048. vignetteWeightKeys.push({
  93049. frame: 11,
  93050. value: 0
  93051. });
  93052. animationPP.setKeys(vignetteWeightKeys);
  93053. this._postProcessMove.animations.push(animationPP);
  93054. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93055. var vignetteStretchKeys = [];
  93056. vignetteStretchKeys.push({
  93057. frame: 0,
  93058. value: 0
  93059. });
  93060. vignetteStretchKeys.push({
  93061. frame: 5,
  93062. value: 10
  93063. });
  93064. vignetteStretchKeys.push({
  93065. frame: 11,
  93066. value: 0
  93067. });
  93068. animationPP2.setKeys(vignetteStretchKeys);
  93069. this._postProcessMove.animations.push(animationPP2);
  93070. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93071. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93072. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93073. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93074. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93075. });
  93076. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93077. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93078. });
  93079. this._hideTeleportationTarget();
  93080. };
  93081. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93082. if (normal) {
  93083. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93084. if (angle < Math.PI / 2) {
  93085. normal.scaleInPlace(-1);
  93086. }
  93087. }
  93088. return normal;
  93089. };
  93090. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93091. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93092. return;
  93093. }
  93094. var ray = gazer._getForwardRay(this._rayLength);
  93095. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93096. if (hit) {
  93097. // Populate the contrllers mesh that can be used for drag/drop
  93098. if (gazer._laserPointer) {
  93099. hit.originMesh = gazer._laserPointer.parent;
  93100. }
  93101. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93102. }
  93103. gazer._currentHit = hit;
  93104. // Moving the gazeTracker on the mesh face targetted
  93105. if (hit && hit.pickedPoint) {
  93106. if (this._displayGaze) {
  93107. var multiplier = 1;
  93108. gazer._gazeTracker.isVisible = true;
  93109. if (gazer._isActionableMesh) {
  93110. multiplier = 3;
  93111. }
  93112. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93113. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93114. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93115. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93116. // To avoid z-fighting
  93117. var deltaFighting = 0.002;
  93118. if (pickNormal) {
  93119. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93120. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93121. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93122. }
  93123. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93124. if (gazer._gazeTracker.position.x < 0) {
  93125. gazer._gazeTracker.position.x += deltaFighting;
  93126. }
  93127. else {
  93128. gazer._gazeTracker.position.x -= deltaFighting;
  93129. }
  93130. if (gazer._gazeTracker.position.y < 0) {
  93131. gazer._gazeTracker.position.y += deltaFighting;
  93132. }
  93133. else {
  93134. gazer._gazeTracker.position.y -= deltaFighting;
  93135. }
  93136. if (gazer._gazeTracker.position.z < 0) {
  93137. gazer._gazeTracker.position.z += deltaFighting;
  93138. }
  93139. else {
  93140. gazer._gazeTracker.position.z -= deltaFighting;
  93141. }
  93142. }
  93143. // Changing the size of the laser pointer based on the distance from the targetted point
  93144. gazer._updatePointerDistance(hit.distance);
  93145. }
  93146. else {
  93147. gazer._updatePointerDistance();
  93148. gazer._gazeTracker.isVisible = false;
  93149. }
  93150. if (hit && hit.pickedMesh) {
  93151. // The object selected is the floor, we're in a teleportation scenario
  93152. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93153. // Moving the teleportation area to this targetted point
  93154. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93155. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93156. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93157. }
  93158. gazer._currentMeshSelected = null;
  93159. if (gazer._teleportationRequestInitiated) {
  93160. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93161. }
  93162. return;
  93163. }
  93164. // If not, we're in a selection scenario
  93165. //this._teleportationAllowed = false;
  93166. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93167. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93168. this.onNewMeshPicked.notifyObservers(hit);
  93169. gazer._currentMeshSelected = hit.pickedMesh;
  93170. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93171. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93172. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93173. gazer._isActionableMesh = true;
  93174. }
  93175. else {
  93176. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93177. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93178. gazer._isActionableMesh = false;
  93179. }
  93180. try {
  93181. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93182. }
  93183. catch (err) {
  93184. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93185. }
  93186. }
  93187. else {
  93188. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93189. gazer._currentMeshSelected = null;
  93190. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93191. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93192. }
  93193. }
  93194. }
  93195. else {
  93196. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93197. gazer._currentMeshSelected = null;
  93198. //this._teleportationAllowed = false;
  93199. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93200. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93201. }
  93202. };
  93203. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93204. if (mesh) {
  93205. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93206. }
  93207. };
  93208. /**
  93209. * Sets the color of the laser ray from the vr controllers.
  93210. * @param color new color for the ray.
  93211. */
  93212. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93213. if (this.leftController) {
  93214. this.leftController._setLaserPointerColor(color);
  93215. }
  93216. if (this.rightController) {
  93217. this.rightController._setLaserPointerColor(color);
  93218. }
  93219. };
  93220. /**
  93221. * Sets the color of the ray from the vr headsets gaze.
  93222. * @param color new color for the ray.
  93223. */
  93224. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93225. if (!this._cameraGazer._gazeTracker.material) {
  93226. return;
  93227. }
  93228. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93229. if (this.leftController) {
  93230. this.leftController._gazeTracker.material.emissiveColor = color;
  93231. }
  93232. if (this.rightController) {
  93233. this.rightController._gazeTracker.material.emissiveColor = color;
  93234. }
  93235. };
  93236. /**
  93237. * Exits VR and disposes of the vr experience helper
  93238. */
  93239. VRExperienceHelper.prototype.dispose = function () {
  93240. if (this.isInVRMode) {
  93241. this.exitVR();
  93242. }
  93243. if (this._postProcessMove) {
  93244. this._postProcessMove.dispose();
  93245. }
  93246. if (this._webVRCamera) {
  93247. this._webVRCamera.dispose();
  93248. }
  93249. if (this._vrDeviceOrientationCamera) {
  93250. this._vrDeviceOrientationCamera.dispose();
  93251. }
  93252. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93253. document.body.removeChild(this._btnVR);
  93254. }
  93255. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93256. this._deviceOrientationCamera.dispose();
  93257. }
  93258. if (this._cameraGazer) {
  93259. this._cameraGazer.dispose();
  93260. }
  93261. if (this.leftController) {
  93262. this.leftController.dispose();
  93263. }
  93264. if (this.rightController) {
  93265. this.rightController.dispose();
  93266. }
  93267. if (this._teleportationTarget) {
  93268. this._teleportationTarget.dispose();
  93269. }
  93270. this._floorMeshesCollection = [];
  93271. document.removeEventListener("keydown", this._onKeyDown);
  93272. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93273. window.removeEventListener("resize", this._onResize);
  93274. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93275. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93276. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93277. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93278. document.onmsfullscreenchange = null;
  93279. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93280. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93281. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93282. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93283. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93284. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93285. this._scene.unregisterBeforeRender(this.beforeRender);
  93286. };
  93287. /**
  93288. * Gets the name of the VRExperienceHelper class
  93289. * @returns "VRExperienceHelper"
  93290. */
  93291. VRExperienceHelper.prototype.getClassName = function () {
  93292. return "VRExperienceHelper";
  93293. };
  93294. return VRExperienceHelper;
  93295. }());
  93296. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93297. })(BABYLON || (BABYLON = {}));
  93298. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93299. // Mainly based on these 2 articles :
  93300. // 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
  93301. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93302. var BABYLON;
  93303. (function (BABYLON) {
  93304. /**
  93305. * Defines the potential axis of a Joystick
  93306. */
  93307. var JoystickAxis;
  93308. (function (JoystickAxis) {
  93309. /** X axis */
  93310. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93311. /** Y axis */
  93312. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93313. /** Z axis */
  93314. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93315. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93316. /**
  93317. * Class used to define virtual joystick (used in touch mode)
  93318. */
  93319. var VirtualJoystick = /** @class */ (function () {
  93320. /**
  93321. * Creates a new virtual joystick
  93322. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93323. */
  93324. function VirtualJoystick(leftJoystick) {
  93325. var _this = this;
  93326. if (leftJoystick) {
  93327. this._leftJoystick = true;
  93328. }
  93329. else {
  93330. this._leftJoystick = false;
  93331. }
  93332. VirtualJoystick._globalJoystickIndex++;
  93333. // By default left & right arrow keys are moving the X
  93334. // and up & down keys are moving the Y
  93335. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93336. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93337. this.reverseLeftRight = false;
  93338. this.reverseUpDown = false;
  93339. // collections of pointers
  93340. this._touches = new BABYLON.StringDictionary();
  93341. this.deltaPosition = BABYLON.Vector3.Zero();
  93342. this._joystickSensibility = 25;
  93343. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93344. this._onResize = function (evt) {
  93345. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93346. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93347. if (VirtualJoystick.vjCanvas) {
  93348. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93349. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93350. }
  93351. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93352. };
  93353. // injecting a canvas element on top of the canvas 3D game
  93354. if (!VirtualJoystick.vjCanvas) {
  93355. window.addEventListener("resize", this._onResize, false);
  93356. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93357. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93358. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93359. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93360. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93361. VirtualJoystick.vjCanvas.style.width = "100%";
  93362. VirtualJoystick.vjCanvas.style.height = "100%";
  93363. VirtualJoystick.vjCanvas.style.position = "absolute";
  93364. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93365. VirtualJoystick.vjCanvas.style.top = "0px";
  93366. VirtualJoystick.vjCanvas.style.left = "0px";
  93367. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93368. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93369. // Support for jQuery PEP polyfill
  93370. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93371. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93372. if (!context) {
  93373. throw new Error("Unable to create canvas for virtual joystick");
  93374. }
  93375. VirtualJoystick.vjCanvasContext = context;
  93376. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93377. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93378. document.body.appendChild(VirtualJoystick.vjCanvas);
  93379. }
  93380. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93381. this.pressed = false;
  93382. // default joystick color
  93383. this._joystickColor = "cyan";
  93384. this._joystickPointerID = -1;
  93385. // current joystick position
  93386. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93387. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93388. // origin joystick position
  93389. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93390. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93391. this._onPointerDownHandlerRef = function (evt) {
  93392. _this._onPointerDown(evt);
  93393. };
  93394. this._onPointerMoveHandlerRef = function (evt) {
  93395. _this._onPointerMove(evt);
  93396. };
  93397. this._onPointerUpHandlerRef = function (evt) {
  93398. _this._onPointerUp(evt);
  93399. };
  93400. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93401. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93402. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93403. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93404. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93405. evt.preventDefault(); // Disables system menu
  93406. }, false);
  93407. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93408. }
  93409. /**
  93410. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93411. * @param newJoystickSensibility defines the new sensibility
  93412. */
  93413. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  93414. this._joystickSensibility = newJoystickSensibility;
  93415. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93416. };
  93417. VirtualJoystick.prototype._onPointerDown = function (e) {
  93418. var positionOnScreenCondition;
  93419. e.preventDefault();
  93420. if (this._leftJoystick === true) {
  93421. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  93422. }
  93423. else {
  93424. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  93425. }
  93426. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93427. // First contact will be dedicated to the virtual joystick
  93428. this._joystickPointerID = e.pointerId;
  93429. this._joystickPointerStartPos.x = e.clientX;
  93430. this._joystickPointerStartPos.y = e.clientY;
  93431. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93432. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93433. this._deltaJoystickVector.x = 0;
  93434. this._deltaJoystickVector.y = 0;
  93435. this.pressed = true;
  93436. this._touches.add(e.pointerId.toString(), e);
  93437. }
  93438. else {
  93439. // You can only trigger the action buttons with a joystick declared
  93440. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93441. this._action();
  93442. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93443. }
  93444. }
  93445. };
  93446. VirtualJoystick.prototype._onPointerMove = function (e) {
  93447. // If the current pointer is the one associated to the joystick (first touch contact)
  93448. if (this._joystickPointerID == e.pointerId) {
  93449. this._joystickPointerPos.x = e.clientX;
  93450. this._joystickPointerPos.y = e.clientY;
  93451. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93452. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93453. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93454. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93455. switch (this._axisTargetedByLeftAndRight) {
  93456. case JoystickAxis.X:
  93457. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93458. break;
  93459. case JoystickAxis.Y:
  93460. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93461. break;
  93462. case JoystickAxis.Z:
  93463. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93464. break;
  93465. }
  93466. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93467. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93468. switch (this._axisTargetedByUpAndDown) {
  93469. case JoystickAxis.X:
  93470. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93471. break;
  93472. case JoystickAxis.Y:
  93473. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93474. break;
  93475. case JoystickAxis.Z:
  93476. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93477. break;
  93478. }
  93479. }
  93480. else {
  93481. var data = this._touches.get(e.pointerId.toString());
  93482. if (data) {
  93483. data.x = e.clientX;
  93484. data.y = e.clientY;
  93485. }
  93486. }
  93487. };
  93488. VirtualJoystick.prototype._onPointerUp = function (e) {
  93489. if (this._joystickPointerID == e.pointerId) {
  93490. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93491. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93492. this._joystickPointerID = -1;
  93493. this.pressed = false;
  93494. }
  93495. else {
  93496. var touch = this._touches.get(e.pointerId.toString());
  93497. if (touch) {
  93498. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93499. }
  93500. }
  93501. this._deltaJoystickVector.x = 0;
  93502. this._deltaJoystickVector.y = 0;
  93503. this._touches.remove(e.pointerId.toString());
  93504. };
  93505. /**
  93506. * Change the color of the virtual joystick
  93507. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93508. */
  93509. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93510. this._joystickColor = newColor;
  93511. };
  93512. /**
  93513. * Defines a callback to call when the joystick is touched
  93514. * @param action defines the callback
  93515. */
  93516. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93517. this._action = action;
  93518. };
  93519. /**
  93520. * Defines which axis you'd like to control for left & right
  93521. * @param axis defines the axis to use
  93522. */
  93523. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93524. switch (axis) {
  93525. case JoystickAxis.X:
  93526. case JoystickAxis.Y:
  93527. case JoystickAxis.Z:
  93528. this._axisTargetedByLeftAndRight = axis;
  93529. break;
  93530. default:
  93531. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93532. break;
  93533. }
  93534. };
  93535. /**
  93536. * Defines which axis you'd like to control for up & down
  93537. * @param axis defines the axis to use
  93538. */
  93539. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93540. switch (axis) {
  93541. case JoystickAxis.X:
  93542. case JoystickAxis.Y:
  93543. case JoystickAxis.Z:
  93544. this._axisTargetedByUpAndDown = axis;
  93545. break;
  93546. default:
  93547. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93548. break;
  93549. }
  93550. };
  93551. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93552. var _this = this;
  93553. if (this.pressed) {
  93554. this._touches.forEach(function (key, touch) {
  93555. if (touch.pointerId === _this._joystickPointerID) {
  93556. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93557. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93558. VirtualJoystick.vjCanvasContext.beginPath();
  93559. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93560. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93561. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93562. VirtualJoystick.vjCanvasContext.stroke();
  93563. VirtualJoystick.vjCanvasContext.closePath();
  93564. VirtualJoystick.vjCanvasContext.beginPath();
  93565. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93566. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93567. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93568. VirtualJoystick.vjCanvasContext.stroke();
  93569. VirtualJoystick.vjCanvasContext.closePath();
  93570. VirtualJoystick.vjCanvasContext.beginPath();
  93571. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93572. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93573. VirtualJoystick.vjCanvasContext.stroke();
  93574. VirtualJoystick.vjCanvasContext.closePath();
  93575. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93576. }
  93577. else {
  93578. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93579. VirtualJoystick.vjCanvasContext.beginPath();
  93580. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93581. VirtualJoystick.vjCanvasContext.beginPath();
  93582. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93583. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93584. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93585. VirtualJoystick.vjCanvasContext.stroke();
  93586. VirtualJoystick.vjCanvasContext.closePath();
  93587. touch.prevX = touch.x;
  93588. touch.prevY = touch.y;
  93589. }
  93590. ;
  93591. });
  93592. }
  93593. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93594. };
  93595. /**
  93596. * Release internal HTML canvas
  93597. */
  93598. VirtualJoystick.prototype.releaseCanvas = function () {
  93599. if (VirtualJoystick.vjCanvas) {
  93600. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93601. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93602. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93603. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  93604. window.removeEventListener("resize", this._onResize);
  93605. document.body.removeChild(VirtualJoystick.vjCanvas);
  93606. VirtualJoystick.vjCanvas = null;
  93607. }
  93608. };
  93609. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  93610. VirtualJoystick._globalJoystickIndex = 0;
  93611. return VirtualJoystick;
  93612. }());
  93613. BABYLON.VirtualJoystick = VirtualJoystick;
  93614. })(BABYLON || (BABYLON = {}));
  93615. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93616. var BABYLON;
  93617. (function (BABYLON) {
  93618. // We're mainly based on the logic defined into the FreeCamera code
  93619. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93620. __extends(VirtualJoysticksCamera, _super);
  93621. function VirtualJoysticksCamera(name, position, scene) {
  93622. var _this = _super.call(this, name, position, scene) || this;
  93623. _this.inputs.addVirtualJoystick();
  93624. return _this;
  93625. }
  93626. VirtualJoysticksCamera.prototype.getClassName = function () {
  93627. return "VirtualJoysticksCamera";
  93628. };
  93629. return VirtualJoysticksCamera;
  93630. }(BABYLON.FreeCamera));
  93631. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93632. })(BABYLON || (BABYLON = {}));
  93633. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93634. var BABYLON;
  93635. (function (BABYLON) {
  93636. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93637. function FreeCameraVirtualJoystickInput() {
  93638. }
  93639. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93640. return this._leftjoystick;
  93641. };
  93642. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93643. return this._rightjoystick;
  93644. };
  93645. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93646. if (this._leftjoystick) {
  93647. var camera = this.camera;
  93648. var speed = camera._computeLocalCameraSpeed() * 50;
  93649. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93650. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93651. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93652. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93653. if (!this._leftjoystick.pressed) {
  93654. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93655. }
  93656. if (!this._rightjoystick.pressed) {
  93657. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93658. }
  93659. }
  93660. };
  93661. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93662. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93663. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93664. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93665. this._leftjoystick.setJoystickSensibility(0.15);
  93666. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93667. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93668. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93669. this._rightjoystick.reverseUpDown = true;
  93670. this._rightjoystick.setJoystickSensibility(0.05);
  93671. this._rightjoystick.setJoystickColor("yellow");
  93672. };
  93673. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93674. this._leftjoystick.releaseCanvas();
  93675. this._rightjoystick.releaseCanvas();
  93676. };
  93677. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93678. return "FreeCameraVirtualJoystickInput";
  93679. };
  93680. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93681. return "virtualJoystick";
  93682. };
  93683. return FreeCameraVirtualJoystickInput;
  93684. }());
  93685. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93686. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93687. })(BABYLON || (BABYLON = {}));
  93688. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93689. var BABYLON;
  93690. (function (BABYLON) {
  93691. var SimplificationSettings = /** @class */ (function () {
  93692. function SimplificationSettings(quality, distance, optimizeMesh) {
  93693. this.quality = quality;
  93694. this.distance = distance;
  93695. this.optimizeMesh = optimizeMesh;
  93696. }
  93697. return SimplificationSettings;
  93698. }());
  93699. BABYLON.SimplificationSettings = SimplificationSettings;
  93700. var SimplificationQueue = /** @class */ (function () {
  93701. function SimplificationQueue() {
  93702. this.running = false;
  93703. this._simplificationArray = [];
  93704. }
  93705. SimplificationQueue.prototype.addTask = function (task) {
  93706. this._simplificationArray.push(task);
  93707. };
  93708. SimplificationQueue.prototype.executeNext = function () {
  93709. var task = this._simplificationArray.pop();
  93710. if (task) {
  93711. this.running = true;
  93712. this.runSimplification(task);
  93713. }
  93714. else {
  93715. this.running = false;
  93716. }
  93717. };
  93718. SimplificationQueue.prototype.runSimplification = function (task) {
  93719. var _this = this;
  93720. if (task.parallelProcessing) {
  93721. //parallel simplifier
  93722. task.settings.forEach(function (setting) {
  93723. var simplifier = _this.getSimplifier(task);
  93724. simplifier.simplify(setting, function (newMesh) {
  93725. task.mesh.addLODLevel(setting.distance, newMesh);
  93726. newMesh.isVisible = true;
  93727. //check if it is the last
  93728. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93729. //all done, run the success callback.
  93730. task.successCallback();
  93731. }
  93732. _this.executeNext();
  93733. });
  93734. });
  93735. }
  93736. else {
  93737. //single simplifier.
  93738. var simplifier = this.getSimplifier(task);
  93739. var runDecimation = function (setting, callback) {
  93740. simplifier.simplify(setting, function (newMesh) {
  93741. task.mesh.addLODLevel(setting.distance, newMesh);
  93742. newMesh.isVisible = true;
  93743. //run the next quality level
  93744. callback();
  93745. });
  93746. };
  93747. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93748. runDecimation(task.settings[loop.index], function () {
  93749. loop.executeNext();
  93750. });
  93751. }, function () {
  93752. //execution ended, run the success callback.
  93753. if (task.successCallback) {
  93754. task.successCallback();
  93755. }
  93756. _this.executeNext();
  93757. });
  93758. }
  93759. };
  93760. SimplificationQueue.prototype.getSimplifier = function (task) {
  93761. switch (task.simplificationType) {
  93762. case SimplificationType.QUADRATIC:
  93763. default:
  93764. return new QuadraticErrorSimplification(task.mesh);
  93765. }
  93766. };
  93767. return SimplificationQueue;
  93768. }());
  93769. BABYLON.SimplificationQueue = SimplificationQueue;
  93770. /**
  93771. * The implemented types of simplification
  93772. * At the moment only Quadratic Error Decimation is implemented
  93773. */
  93774. var SimplificationType;
  93775. (function (SimplificationType) {
  93776. /** Quadratic error decimation */
  93777. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93778. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93779. var DecimationTriangle = /** @class */ (function () {
  93780. function DecimationTriangle(vertices) {
  93781. this.vertices = vertices;
  93782. this.error = new Array(4);
  93783. this.deleted = false;
  93784. this.isDirty = false;
  93785. this.deletePending = false;
  93786. this.borderFactor = 0;
  93787. }
  93788. return DecimationTriangle;
  93789. }());
  93790. BABYLON.DecimationTriangle = DecimationTriangle;
  93791. var DecimationVertex = /** @class */ (function () {
  93792. function DecimationVertex(position, id) {
  93793. this.position = position;
  93794. this.id = id;
  93795. this.isBorder = true;
  93796. this.q = new QuadraticMatrix();
  93797. this.triangleCount = 0;
  93798. this.triangleStart = 0;
  93799. this.originalOffsets = [];
  93800. }
  93801. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93802. this.position.copyFrom(newPosition);
  93803. };
  93804. return DecimationVertex;
  93805. }());
  93806. BABYLON.DecimationVertex = DecimationVertex;
  93807. var QuadraticMatrix = /** @class */ (function () {
  93808. function QuadraticMatrix(data) {
  93809. this.data = new Array(10);
  93810. for (var i = 0; i < 10; ++i) {
  93811. if (data && data[i]) {
  93812. this.data[i] = data[i];
  93813. }
  93814. else {
  93815. this.data[i] = 0;
  93816. }
  93817. }
  93818. }
  93819. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93820. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93821. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93822. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93823. return det;
  93824. };
  93825. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93826. for (var i = 0; i < 10; ++i) {
  93827. this.data[i] += matrix.data[i];
  93828. }
  93829. };
  93830. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  93831. for (var i = 0; i < 10; ++i) {
  93832. this.data[i] += data[i];
  93833. }
  93834. };
  93835. QuadraticMatrix.prototype.add = function (matrix) {
  93836. var m = new QuadraticMatrix();
  93837. for (var i = 0; i < 10; ++i) {
  93838. m.data[i] = this.data[i] + matrix.data[i];
  93839. }
  93840. return m;
  93841. };
  93842. QuadraticMatrix.FromData = function (a, b, c, d) {
  93843. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  93844. };
  93845. //returning an array to avoid garbage collection
  93846. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  93847. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  93848. };
  93849. return QuadraticMatrix;
  93850. }());
  93851. BABYLON.QuadraticMatrix = QuadraticMatrix;
  93852. var Reference = /** @class */ (function () {
  93853. function Reference(vertexId, triangleId) {
  93854. this.vertexId = vertexId;
  93855. this.triangleId = triangleId;
  93856. }
  93857. return Reference;
  93858. }());
  93859. BABYLON.Reference = Reference;
  93860. /**
  93861. * An implementation of the Quadratic Error simplification algorithm.
  93862. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  93863. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  93864. * @author RaananW
  93865. */
  93866. var QuadraticErrorSimplification = /** @class */ (function () {
  93867. function QuadraticErrorSimplification(_mesh) {
  93868. this._mesh = _mesh;
  93869. this.syncIterations = 5000;
  93870. this.aggressiveness = 7;
  93871. this.decimationIterations = 100;
  93872. this.boundingBoxEpsilon = BABYLON.Epsilon;
  93873. }
  93874. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  93875. var _this = this;
  93876. this.initDecimatedMesh();
  93877. //iterating through the submeshes array, one after the other.
  93878. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  93879. _this.initWithMesh(loop.index, function () {
  93880. _this.runDecimation(settings, loop.index, function () {
  93881. loop.executeNext();
  93882. });
  93883. }, settings.optimizeMesh);
  93884. }, function () {
  93885. setTimeout(function () {
  93886. successCallback(_this._reconstructedMesh);
  93887. }, 0);
  93888. });
  93889. };
  93890. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  93891. var _this = this;
  93892. var targetCount = ~~(this.triangles.length * settings.quality);
  93893. var deletedTriangles = 0;
  93894. var triangleCount = this.triangles.length;
  93895. var iterationFunction = function (iteration, callback) {
  93896. setTimeout(function () {
  93897. if (iteration % 5 === 0) {
  93898. _this.updateMesh(iteration === 0);
  93899. }
  93900. for (var i = 0; i < _this.triangles.length; ++i) {
  93901. _this.triangles[i].isDirty = false;
  93902. }
  93903. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  93904. var trianglesIterator = function (i) {
  93905. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  93906. var t = _this.triangles[tIdx];
  93907. if (!t)
  93908. return;
  93909. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  93910. return;
  93911. }
  93912. for (var j = 0; j < 3; ++j) {
  93913. if (t.error[j] < threshold) {
  93914. var deleted0 = [];
  93915. var deleted1 = [];
  93916. var v0 = t.vertices[j];
  93917. var v1 = t.vertices[(j + 1) % 3];
  93918. if (v0.isBorder || v1.isBorder)
  93919. continue;
  93920. var p = BABYLON.Vector3.Zero();
  93921. var n = BABYLON.Vector3.Zero();
  93922. var uv = BABYLON.Vector2.Zero();
  93923. var color = new BABYLON.Color4(0, 0, 0, 1);
  93924. _this.calculateError(v0, v1, p, n, uv, color);
  93925. var delTr = new Array();
  93926. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  93927. continue;
  93928. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  93929. continue;
  93930. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  93931. continue;
  93932. var uniqueArray = new Array();
  93933. delTr.forEach(function (deletedT) {
  93934. if (uniqueArray.indexOf(deletedT) === -1) {
  93935. deletedT.deletePending = true;
  93936. uniqueArray.push(deletedT);
  93937. }
  93938. });
  93939. if (uniqueArray.length % 2 !== 0) {
  93940. continue;
  93941. }
  93942. v0.q = v1.q.add(v0.q);
  93943. v0.updatePosition(p);
  93944. var tStart = _this.references.length;
  93945. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  93946. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  93947. var tCount = _this.references.length - tStart;
  93948. if (tCount <= v0.triangleCount) {
  93949. if (tCount) {
  93950. for (var c = 0; c < tCount; c++) {
  93951. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  93952. }
  93953. }
  93954. }
  93955. else {
  93956. v0.triangleStart = tStart;
  93957. }
  93958. v0.triangleCount = tCount;
  93959. break;
  93960. }
  93961. }
  93962. };
  93963. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  93964. }, 0);
  93965. };
  93966. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  93967. if (triangleCount - deletedTriangles <= targetCount)
  93968. loop.breakLoop();
  93969. else {
  93970. iterationFunction(loop.index, function () {
  93971. loop.executeNext();
  93972. });
  93973. }
  93974. }, function () {
  93975. setTimeout(function () {
  93976. //reconstruct this part of the mesh
  93977. _this.reconstructMesh(submeshIndex);
  93978. successCallback();
  93979. }, 0);
  93980. });
  93981. };
  93982. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  93983. var _this = this;
  93984. this.vertices = [];
  93985. this.triangles = [];
  93986. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  93987. var indices = this._mesh.getIndices();
  93988. var submesh = this._mesh.subMeshes[submeshIndex];
  93989. var findInVertices = function (positionToSearch) {
  93990. if (optimizeMesh) {
  93991. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  93992. if (_this.vertices[ii].position.equals(positionToSearch)) {
  93993. return _this.vertices[ii];
  93994. }
  93995. }
  93996. }
  93997. return null;
  93998. };
  93999. var vertexReferences = [];
  94000. var vertexInit = function (i) {
  94001. if (!positionData) {
  94002. return;
  94003. }
  94004. var offset = i + submesh.verticesStart;
  94005. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94006. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94007. vertex.originalOffsets.push(offset);
  94008. if (vertex.id === _this.vertices.length) {
  94009. _this.vertices.push(vertex);
  94010. }
  94011. vertexReferences.push(vertex.id);
  94012. };
  94013. //var totalVertices = mesh.getTotalVertices();
  94014. var totalVertices = submesh.verticesCount;
  94015. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94016. var indicesInit = function (i) {
  94017. if (!indices) {
  94018. return;
  94019. }
  94020. var offset = (submesh.indexStart / 3) + i;
  94021. var pos = (offset * 3);
  94022. var i0 = indices[pos + 0];
  94023. var i1 = indices[pos + 1];
  94024. var i2 = indices[pos + 2];
  94025. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94026. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94027. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94028. var triangle = new DecimationTriangle([v0, v1, v2]);
  94029. triangle.originalOffset = pos;
  94030. _this.triangles.push(triangle);
  94031. };
  94032. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94033. _this.init(callback);
  94034. });
  94035. });
  94036. };
  94037. QuadraticErrorSimplification.prototype.init = function (callback) {
  94038. var _this = this;
  94039. var triangleInit1 = function (i) {
  94040. var t = _this.triangles[i];
  94041. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94042. for (var j = 0; j < 3; j++) {
  94043. 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))));
  94044. }
  94045. };
  94046. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94047. var triangleInit2 = function (i) {
  94048. var t = _this.triangles[i];
  94049. for (var j = 0; j < 3; ++j) {
  94050. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94051. }
  94052. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94053. };
  94054. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94055. callback();
  94056. });
  94057. });
  94058. };
  94059. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94060. var newTriangles = [];
  94061. var i;
  94062. for (i = 0; i < this.vertices.length; ++i) {
  94063. this.vertices[i].triangleCount = 0;
  94064. }
  94065. var t;
  94066. var j;
  94067. for (i = 0; i < this.triangles.length; ++i) {
  94068. if (!this.triangles[i].deleted) {
  94069. t = this.triangles[i];
  94070. for (j = 0; j < 3; ++j) {
  94071. t.vertices[j].triangleCount = 1;
  94072. }
  94073. newTriangles.push(t);
  94074. }
  94075. }
  94076. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94077. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94078. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94079. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94080. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94081. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94082. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94083. var vertexCount = 0;
  94084. for (i = 0; i < this.vertices.length; ++i) {
  94085. var vertex = this.vertices[i];
  94086. vertex.id = vertexCount;
  94087. if (vertex.triangleCount) {
  94088. vertex.originalOffsets.forEach(function (originalOffset) {
  94089. if (!normalData) {
  94090. return;
  94091. }
  94092. newPositionData.push(vertex.position.x);
  94093. newPositionData.push(vertex.position.y);
  94094. newPositionData.push(vertex.position.z);
  94095. newNormalData.push(normalData[originalOffset * 3]);
  94096. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94097. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94098. if (uvs && uvs.length) {
  94099. newUVsData.push(uvs[(originalOffset * 2)]);
  94100. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94101. }
  94102. else if (colorsData && colorsData.length) {
  94103. newColorsData.push(colorsData[(originalOffset * 4)]);
  94104. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94105. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94106. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94107. }
  94108. ++vertexCount;
  94109. });
  94110. }
  94111. }
  94112. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94113. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94114. var submeshesArray = this._reconstructedMesh.subMeshes;
  94115. this._reconstructedMesh.subMeshes = [];
  94116. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94117. var originalIndices = this._mesh.getIndices();
  94118. for (i = 0; i < newTriangles.length; ++i) {
  94119. t = newTriangles[i]; //now get the new referencing point for each vertex
  94120. [0, 1, 2].forEach(function (idx) {
  94121. var id = originalIndices[t.originalOffset + idx];
  94122. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94123. if (offset < 0)
  94124. offset = 0;
  94125. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94126. });
  94127. }
  94128. //overwriting the old vertex buffers and indices.
  94129. this._reconstructedMesh.setIndices(newIndicesArray);
  94130. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94131. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94132. if (newUVsData.length > 0)
  94133. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94134. if (newColorsData.length > 0)
  94135. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94136. //create submesh
  94137. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94138. if (submeshIndex > 0) {
  94139. this._reconstructedMesh.subMeshes = [];
  94140. submeshesArray.forEach(function (submesh) {
  94141. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94142. });
  94143. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94144. }
  94145. };
  94146. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94147. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94148. this._reconstructedMesh.material = this._mesh.material;
  94149. this._reconstructedMesh.parent = this._mesh.parent;
  94150. this._reconstructedMesh.isVisible = false;
  94151. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94152. };
  94153. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94154. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94155. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94156. if (t.deleted)
  94157. continue;
  94158. var s = this.references[vertex1.triangleStart + i].vertexId;
  94159. var v1 = t.vertices[(s + 1) % 3];
  94160. var v2 = t.vertices[(s + 2) % 3];
  94161. if ((v1 === vertex2 || v2 === vertex2)) {
  94162. deletedArray[i] = true;
  94163. delTr.push(t);
  94164. continue;
  94165. }
  94166. var d1 = v1.position.subtract(point);
  94167. d1 = d1.normalize();
  94168. var d2 = v2.position.subtract(point);
  94169. d2 = d2.normalize();
  94170. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94171. return true;
  94172. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94173. deletedArray[i] = false;
  94174. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94175. return true;
  94176. }
  94177. return false;
  94178. };
  94179. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94180. var newDeleted = deletedTriangles;
  94181. for (var i = 0; i < vertex.triangleCount; ++i) {
  94182. var ref = this.references[vertex.triangleStart + i];
  94183. var t = this.triangles[ref.triangleId];
  94184. if (t.deleted)
  94185. continue;
  94186. if (deletedArray[i] && t.deletePending) {
  94187. t.deleted = true;
  94188. newDeleted++;
  94189. continue;
  94190. }
  94191. t.vertices[ref.vertexId] = origVertex;
  94192. t.isDirty = true;
  94193. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94194. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94195. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94196. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94197. this.references.push(ref);
  94198. }
  94199. return newDeleted;
  94200. };
  94201. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94202. for (var i = 0; i < this.vertices.length; ++i) {
  94203. var vCount = [];
  94204. var vId = [];
  94205. var v = this.vertices[i];
  94206. var j;
  94207. for (j = 0; j < v.triangleCount; ++j) {
  94208. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94209. for (var ii = 0; ii < 3; ii++) {
  94210. var ofs = 0;
  94211. var vv = triangle.vertices[ii];
  94212. while (ofs < vCount.length) {
  94213. if (vId[ofs] === vv.id)
  94214. break;
  94215. ++ofs;
  94216. }
  94217. if (ofs === vCount.length) {
  94218. vCount.push(1);
  94219. vId.push(vv.id);
  94220. }
  94221. else {
  94222. vCount[ofs]++;
  94223. }
  94224. }
  94225. }
  94226. for (j = 0; j < vCount.length; ++j) {
  94227. if (vCount[j] === 1) {
  94228. this.vertices[vId[j]].isBorder = true;
  94229. }
  94230. else {
  94231. this.vertices[vId[j]].isBorder = false;
  94232. }
  94233. }
  94234. }
  94235. };
  94236. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94237. if (identifyBorders === void 0) { identifyBorders = false; }
  94238. var i;
  94239. if (!identifyBorders) {
  94240. var newTrianglesVector = [];
  94241. for (i = 0; i < this.triangles.length; ++i) {
  94242. if (!this.triangles[i].deleted) {
  94243. newTrianglesVector.push(this.triangles[i]);
  94244. }
  94245. }
  94246. this.triangles = newTrianglesVector;
  94247. }
  94248. for (i = 0; i < this.vertices.length; ++i) {
  94249. this.vertices[i].triangleCount = 0;
  94250. this.vertices[i].triangleStart = 0;
  94251. }
  94252. var t;
  94253. var j;
  94254. var v;
  94255. for (i = 0; i < this.triangles.length; ++i) {
  94256. t = this.triangles[i];
  94257. for (j = 0; j < 3; ++j) {
  94258. v = t.vertices[j];
  94259. v.triangleCount++;
  94260. }
  94261. }
  94262. var tStart = 0;
  94263. for (i = 0; i < this.vertices.length; ++i) {
  94264. this.vertices[i].triangleStart = tStart;
  94265. tStart += this.vertices[i].triangleCount;
  94266. this.vertices[i].triangleCount = 0;
  94267. }
  94268. var newReferences = new Array(this.triangles.length * 3);
  94269. for (i = 0; i < this.triangles.length; ++i) {
  94270. t = this.triangles[i];
  94271. for (j = 0; j < 3; ++j) {
  94272. v = t.vertices[j];
  94273. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94274. v.triangleCount++;
  94275. }
  94276. }
  94277. this.references = newReferences;
  94278. if (identifyBorders) {
  94279. this.identifyBorder();
  94280. }
  94281. };
  94282. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94283. var x = point.x;
  94284. var y = point.y;
  94285. var z = point.z;
  94286. 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
  94287. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94288. };
  94289. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94290. var q = vertex1.q.add(vertex2.q);
  94291. var border = vertex1.isBorder && vertex2.isBorder;
  94292. var error = 0;
  94293. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94294. if (qDet !== 0 && !border) {
  94295. if (!pointResult) {
  94296. pointResult = BABYLON.Vector3.Zero();
  94297. }
  94298. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94299. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94300. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94301. error = this.vertexError(q, pointResult);
  94302. }
  94303. else {
  94304. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94305. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94306. var error1 = this.vertexError(q, vertex1.position);
  94307. var error2 = this.vertexError(q, vertex2.position);
  94308. var error3 = this.vertexError(q, p3);
  94309. error = Math.min(error1, error2, error3);
  94310. if (error === error1) {
  94311. if (pointResult) {
  94312. pointResult.copyFrom(vertex1.position);
  94313. }
  94314. }
  94315. else if (error === error2) {
  94316. if (pointResult) {
  94317. pointResult.copyFrom(vertex2.position);
  94318. }
  94319. }
  94320. else {
  94321. if (pointResult) {
  94322. pointResult.copyFrom(p3);
  94323. }
  94324. }
  94325. }
  94326. return error;
  94327. };
  94328. return QuadraticErrorSimplification;
  94329. }());
  94330. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94331. })(BABYLON || (BABYLON = {}));
  94332. //# sourceMappingURL=babylon.meshSimplification.js.map
  94333. var BABYLON;
  94334. (function (BABYLON) {
  94335. var MeshLODLevel = /** @class */ (function () {
  94336. function MeshLODLevel(distance, mesh) {
  94337. this.distance = distance;
  94338. this.mesh = mesh;
  94339. }
  94340. return MeshLODLevel;
  94341. }());
  94342. BABYLON.MeshLODLevel = MeshLODLevel;
  94343. })(BABYLON || (BABYLON = {}));
  94344. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94345. var BABYLON;
  94346. (function (BABYLON) {
  94347. /**
  94348. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94349. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94350. */
  94351. var SceneOptimization = /** @class */ (function () {
  94352. /**
  94353. * Creates the SceneOptimization object
  94354. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94355. * @param desc defines the description associated with the optimization
  94356. */
  94357. function SceneOptimization(
  94358. /**
  94359. * Defines the priority of this optimization (0 by default which means first in the list)
  94360. */
  94361. priority) {
  94362. if (priority === void 0) { priority = 0; }
  94363. this.priority = priority;
  94364. }
  94365. /**
  94366. * Gets a string describing the action executed by the current optimization
  94367. * @returns description string
  94368. */
  94369. SceneOptimization.prototype.getDescription = function () {
  94370. return "";
  94371. };
  94372. /**
  94373. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94374. * @param scene defines the current scene where to apply this optimization
  94375. * @param optimizer defines the current optimizer
  94376. * @returns true if everything that can be done was applied
  94377. */
  94378. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94379. return true;
  94380. };
  94381. ;
  94382. return SceneOptimization;
  94383. }());
  94384. BABYLON.SceneOptimization = SceneOptimization;
  94385. /**
  94386. * Defines an optimization used to reduce the size of render target textures
  94387. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94388. */
  94389. var TextureOptimization = /** @class */ (function (_super) {
  94390. __extends(TextureOptimization, _super);
  94391. /**
  94392. * Creates the TextureOptimization object
  94393. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94394. * @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
  94395. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94396. */
  94397. function TextureOptimization(
  94398. /**
  94399. * Defines the priority of this optimization (0 by default which means first in the list)
  94400. */
  94401. priority,
  94402. /**
  94403. * 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
  94404. */
  94405. maximumSize,
  94406. /**
  94407. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94408. */
  94409. step) {
  94410. if (priority === void 0) { priority = 0; }
  94411. if (maximumSize === void 0) { maximumSize = 1024; }
  94412. if (step === void 0) { step = 0.5; }
  94413. var _this = _super.call(this, priority) || this;
  94414. _this.priority = priority;
  94415. _this.maximumSize = maximumSize;
  94416. _this.step = step;
  94417. return _this;
  94418. }
  94419. /**
  94420. * Gets a string describing the action executed by the current optimization
  94421. * @returns description string
  94422. */
  94423. TextureOptimization.prototype.getDescription = function () {
  94424. return "Reducing render target texture size to " + this.maximumSize;
  94425. };
  94426. /**
  94427. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94428. * @param scene defines the current scene where to apply this optimization
  94429. * @param optimizer defines the current optimizer
  94430. * @returns true if everything that can be done was applied
  94431. */
  94432. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94433. var allDone = true;
  94434. for (var index = 0; index < scene.textures.length; index++) {
  94435. var texture = scene.textures[index];
  94436. if (!texture.canRescale || texture.getContext) {
  94437. continue;
  94438. }
  94439. var currentSize = texture.getSize();
  94440. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94441. if (maxDimension > this.maximumSize) {
  94442. texture.scale(this.step);
  94443. allDone = false;
  94444. }
  94445. }
  94446. return allDone;
  94447. };
  94448. return TextureOptimization;
  94449. }(SceneOptimization));
  94450. BABYLON.TextureOptimization = TextureOptimization;
  94451. /**
  94452. * Defines an optimization used to increase or decrease the rendering resolution
  94453. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94454. */
  94455. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94456. __extends(HardwareScalingOptimization, _super);
  94457. /**
  94458. * Creates the HardwareScalingOptimization object
  94459. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94460. * @param maximumScale defines the maximum scale to use (2 by default)
  94461. * @param step defines the step to use between two passes (0.5 by default)
  94462. */
  94463. function HardwareScalingOptimization(
  94464. /**
  94465. * Defines the priority of this optimization (0 by default which means first in the list)
  94466. */
  94467. priority,
  94468. /**
  94469. * Defines the maximum scale to use (2 by default)
  94470. */
  94471. maximumScale,
  94472. /**
  94473. * Defines the step to use between two passes (0.5 by default)
  94474. */
  94475. step) {
  94476. if (priority === void 0) { priority = 0; }
  94477. if (maximumScale === void 0) { maximumScale = 2; }
  94478. if (step === void 0) { step = 0.25; }
  94479. var _this = _super.call(this, priority) || this;
  94480. _this.priority = priority;
  94481. _this.maximumScale = maximumScale;
  94482. _this.step = step;
  94483. _this._currentScale = -1;
  94484. _this._directionOffset = 1;
  94485. return _this;
  94486. }
  94487. /**
  94488. * Gets a string describing the action executed by the current optimization
  94489. * @return description string
  94490. */
  94491. HardwareScalingOptimization.prototype.getDescription = function () {
  94492. return "Setting hardware scaling level to " + this._currentScale;
  94493. };
  94494. /**
  94495. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94496. * @param scene defines the current scene where to apply this optimization
  94497. * @param optimizer defines the current optimizer
  94498. * @returns true if everything that can be done was applied
  94499. */
  94500. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94501. if (this._currentScale === -1) {
  94502. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94503. if (this._currentScale > this.maximumScale) {
  94504. this._directionOffset = -1;
  94505. }
  94506. }
  94507. this._currentScale += this._directionOffset * this.step;
  94508. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94509. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94510. };
  94511. ;
  94512. return HardwareScalingOptimization;
  94513. }(SceneOptimization));
  94514. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94515. /**
  94516. * Defines an optimization used to remove shadows
  94517. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94518. */
  94519. var ShadowsOptimization = /** @class */ (function (_super) {
  94520. __extends(ShadowsOptimization, _super);
  94521. function ShadowsOptimization() {
  94522. return _super !== null && _super.apply(this, arguments) || this;
  94523. }
  94524. /**
  94525. * Gets a string describing the action executed by the current optimization
  94526. * @return description string
  94527. */
  94528. ShadowsOptimization.prototype.getDescription = function () {
  94529. return "Turning shadows on/off";
  94530. };
  94531. /**
  94532. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94533. * @param scene defines the current scene where to apply this optimization
  94534. * @param optimizer defines the current optimizer
  94535. * @returns true if everything that can be done was applied
  94536. */
  94537. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94538. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94539. return true;
  94540. };
  94541. ;
  94542. return ShadowsOptimization;
  94543. }(SceneOptimization));
  94544. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94545. /**
  94546. * Defines an optimization used to turn post-processes off
  94547. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94548. */
  94549. var PostProcessesOptimization = /** @class */ (function (_super) {
  94550. __extends(PostProcessesOptimization, _super);
  94551. function PostProcessesOptimization() {
  94552. return _super !== null && _super.apply(this, arguments) || this;
  94553. }
  94554. /**
  94555. * Gets a string describing the action executed by the current optimization
  94556. * @return description string
  94557. */
  94558. PostProcessesOptimization.prototype.getDescription = function () {
  94559. return "Turning post-processes on/off";
  94560. };
  94561. /**
  94562. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94563. * @param scene defines the current scene where to apply this optimization
  94564. * @param optimizer defines the current optimizer
  94565. * @returns true if everything that can be done was applied
  94566. */
  94567. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94568. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94569. return true;
  94570. };
  94571. ;
  94572. return PostProcessesOptimization;
  94573. }(SceneOptimization));
  94574. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94575. /**
  94576. * Defines an optimization used to turn lens flares off
  94577. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94578. */
  94579. var LensFlaresOptimization = /** @class */ (function (_super) {
  94580. __extends(LensFlaresOptimization, _super);
  94581. function LensFlaresOptimization() {
  94582. return _super !== null && _super.apply(this, arguments) || this;
  94583. }
  94584. /**
  94585. * Gets a string describing the action executed by the current optimization
  94586. * @return description string
  94587. */
  94588. LensFlaresOptimization.prototype.getDescription = function () {
  94589. return "Turning lens flares on/off";
  94590. };
  94591. /**
  94592. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94593. * @param scene defines the current scene where to apply this optimization
  94594. * @param optimizer defines the current optimizer
  94595. * @returns true if everything that can be done was applied
  94596. */
  94597. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94598. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94599. return true;
  94600. };
  94601. ;
  94602. return LensFlaresOptimization;
  94603. }(SceneOptimization));
  94604. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  94605. /**
  94606. * Defines an optimization based on user defined callback.
  94607. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94608. */
  94609. var CustomOptimization = /** @class */ (function (_super) {
  94610. __extends(CustomOptimization, _super);
  94611. function CustomOptimization() {
  94612. return _super !== null && _super.apply(this, arguments) || this;
  94613. }
  94614. /**
  94615. * Gets a string describing the action executed by the current optimization
  94616. * @returns description string
  94617. */
  94618. CustomOptimization.prototype.getDescription = function () {
  94619. if (this.onGetDescription) {
  94620. return this.onGetDescription();
  94621. }
  94622. return "Running user defined callback";
  94623. };
  94624. /**
  94625. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94626. * @param scene defines the current scene where to apply this optimization
  94627. * @param optimizer defines the current optimizer
  94628. * @returns true if everything that can be done was applied
  94629. */
  94630. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94631. if (this.onApply) {
  94632. return this.onApply(scene, optimizer);
  94633. }
  94634. return true;
  94635. };
  94636. ;
  94637. return CustomOptimization;
  94638. }(SceneOptimization));
  94639. BABYLON.CustomOptimization = CustomOptimization;
  94640. /**
  94641. * Defines an optimization used to turn particles off
  94642. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94643. */
  94644. var ParticlesOptimization = /** @class */ (function (_super) {
  94645. __extends(ParticlesOptimization, _super);
  94646. function ParticlesOptimization() {
  94647. return _super !== null && _super.apply(this, arguments) || this;
  94648. }
  94649. /**
  94650. * Gets a string describing the action executed by the current optimization
  94651. * @return description string
  94652. */
  94653. ParticlesOptimization.prototype.getDescription = function () {
  94654. return "Turning particles on/off";
  94655. };
  94656. /**
  94657. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94658. * @param scene defines the current scene where to apply this optimization
  94659. * @param optimizer defines the current optimizer
  94660. * @returns true if everything that can be done was applied
  94661. */
  94662. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94663. scene.particlesEnabled = optimizer.isInImprovementMode;
  94664. return true;
  94665. };
  94666. ;
  94667. return ParticlesOptimization;
  94668. }(SceneOptimization));
  94669. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94670. /**
  94671. * Defines an optimization used to turn render targets off
  94672. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94673. */
  94674. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94675. __extends(RenderTargetsOptimization, _super);
  94676. function RenderTargetsOptimization() {
  94677. return _super !== null && _super.apply(this, arguments) || this;
  94678. }
  94679. /**
  94680. * Gets a string describing the action executed by the current optimization
  94681. * @return description string
  94682. */
  94683. RenderTargetsOptimization.prototype.getDescription = function () {
  94684. return "Turning render targets off";
  94685. };
  94686. /**
  94687. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94688. * @param scene defines the current scene where to apply this optimization
  94689. * @param optimizer defines the current optimizer
  94690. * @returns true if everything that can be done was applied
  94691. */
  94692. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94693. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94694. return true;
  94695. };
  94696. ;
  94697. return RenderTargetsOptimization;
  94698. }(SceneOptimization));
  94699. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94700. /**
  94701. * Defines an optimization used to merge meshes with compatible materials
  94702. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94703. */
  94704. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94705. __extends(MergeMeshesOptimization, _super);
  94706. function MergeMeshesOptimization() {
  94707. var _this = _super !== null && _super.apply(this, arguments) || this;
  94708. _this._canBeMerged = function (abstractMesh) {
  94709. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94710. return false;
  94711. }
  94712. var mesh = abstractMesh;
  94713. if (!mesh.isVisible || !mesh.isEnabled()) {
  94714. return false;
  94715. }
  94716. if (mesh.instances.length > 0) {
  94717. return false;
  94718. }
  94719. if (mesh.skeleton || mesh.hasLODLevels) {
  94720. return false;
  94721. }
  94722. if (mesh.parent) {
  94723. return false;
  94724. }
  94725. return true;
  94726. };
  94727. return _this;
  94728. }
  94729. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94730. /**
  94731. * Gets or sets a boolean which defines if optimization octree has to be updated
  94732. */
  94733. get: function () {
  94734. return MergeMeshesOptimization._UpdateSelectionTree;
  94735. },
  94736. /**
  94737. * Gets or sets a boolean which defines if optimization octree has to be updated
  94738. */
  94739. set: function (value) {
  94740. MergeMeshesOptimization._UpdateSelectionTree = value;
  94741. },
  94742. enumerable: true,
  94743. configurable: true
  94744. });
  94745. /**
  94746. * Gets a string describing the action executed by the current optimization
  94747. * @return description string
  94748. */
  94749. MergeMeshesOptimization.prototype.getDescription = function () {
  94750. return "Merging similar meshes together";
  94751. };
  94752. /**
  94753. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94754. * @param scene defines the current scene where to apply this optimization
  94755. * @param optimizer defines the current optimizer
  94756. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94757. * @returns true if everything that can be done was applied
  94758. */
  94759. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94760. var globalPool = scene.meshes.slice(0);
  94761. var globalLength = globalPool.length;
  94762. for (var index = 0; index < globalLength; index++) {
  94763. var currentPool = new Array();
  94764. var current = globalPool[index];
  94765. // Checks
  94766. if (!this._canBeMerged(current)) {
  94767. continue;
  94768. }
  94769. currentPool.push(current);
  94770. // Find compatible meshes
  94771. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94772. var otherMesh = globalPool[subIndex];
  94773. if (!this._canBeMerged(otherMesh)) {
  94774. continue;
  94775. }
  94776. if (otherMesh.material !== current.material) {
  94777. continue;
  94778. }
  94779. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94780. continue;
  94781. }
  94782. currentPool.push(otherMesh);
  94783. globalLength--;
  94784. globalPool.splice(subIndex, 1);
  94785. subIndex--;
  94786. }
  94787. if (currentPool.length < 2) {
  94788. continue;
  94789. }
  94790. // Merge meshes
  94791. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94792. }
  94793. if (updateSelectionTree != undefined) {
  94794. if (updateSelectionTree) {
  94795. scene.createOrUpdateSelectionOctree();
  94796. }
  94797. }
  94798. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94799. scene.createOrUpdateSelectionOctree();
  94800. }
  94801. return true;
  94802. };
  94803. ;
  94804. MergeMeshesOptimization._UpdateSelectionTree = false;
  94805. return MergeMeshesOptimization;
  94806. }(SceneOptimization));
  94807. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94808. /**
  94809. * Defines a list of options used by SceneOptimizer
  94810. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94811. */
  94812. var SceneOptimizerOptions = /** @class */ (function () {
  94813. /**
  94814. * Creates a new list of options used by SceneOptimizer
  94815. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94816. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94817. */
  94818. function SceneOptimizerOptions(
  94819. /**
  94820. * Defines the target frame rate to reach (60 by default)
  94821. */
  94822. targetFrameRate,
  94823. /**
  94824. * Defines the interval between two checkes (2000ms by default)
  94825. */
  94826. trackerDuration) {
  94827. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  94828. if (trackerDuration === void 0) { trackerDuration = 2000; }
  94829. this.targetFrameRate = targetFrameRate;
  94830. this.trackerDuration = trackerDuration;
  94831. /**
  94832. * Gets the list of optimizations to apply
  94833. */
  94834. this.optimizations = new Array();
  94835. }
  94836. /**
  94837. * Add a new optimization
  94838. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  94839. * @returns the current SceneOptimizerOptions
  94840. */
  94841. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  94842. this.optimizations.push(optimization);
  94843. return this;
  94844. };
  94845. /**
  94846. * Add a new custom optimization
  94847. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  94848. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  94849. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94850. * @returns the current SceneOptimizerOptions
  94851. */
  94852. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  94853. if (priority === void 0) { priority = 0; }
  94854. var optimization = new CustomOptimization(priority);
  94855. optimization.onApply = onApply;
  94856. optimization.onGetDescription = onGetDescription;
  94857. this.optimizations.push(optimization);
  94858. return this;
  94859. };
  94860. /**
  94861. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  94862. * @param targetFrameRate defines the target frame rate (60 by default)
  94863. * @returns a SceneOptimizerOptions object
  94864. */
  94865. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  94866. var result = new SceneOptimizerOptions(targetFrameRate);
  94867. var priority = 0;
  94868. result.addOptimization(new MergeMeshesOptimization(priority));
  94869. result.addOptimization(new ShadowsOptimization(priority));
  94870. result.addOptimization(new LensFlaresOptimization(priority));
  94871. // Next priority
  94872. priority++;
  94873. result.addOptimization(new PostProcessesOptimization(priority));
  94874. result.addOptimization(new ParticlesOptimization(priority));
  94875. // Next priority
  94876. priority++;
  94877. result.addOptimization(new TextureOptimization(priority, 1024));
  94878. return result;
  94879. };
  94880. /**
  94881. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  94882. * @param targetFrameRate defines the target frame rate (60 by default)
  94883. * @returns a SceneOptimizerOptions object
  94884. */
  94885. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  94886. var result = new SceneOptimizerOptions(targetFrameRate);
  94887. var priority = 0;
  94888. result.addOptimization(new MergeMeshesOptimization(priority));
  94889. result.addOptimization(new ShadowsOptimization(priority));
  94890. result.addOptimization(new LensFlaresOptimization(priority));
  94891. // Next priority
  94892. priority++;
  94893. result.addOptimization(new PostProcessesOptimization(priority));
  94894. result.addOptimization(new ParticlesOptimization(priority));
  94895. // Next priority
  94896. priority++;
  94897. result.addOptimization(new TextureOptimization(priority, 512));
  94898. // Next priority
  94899. priority++;
  94900. result.addOptimization(new RenderTargetsOptimization(priority));
  94901. // Next priority
  94902. priority++;
  94903. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  94904. return result;
  94905. };
  94906. /**
  94907. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  94908. * @param targetFrameRate defines the target frame rate (60 by default)
  94909. * @returns a SceneOptimizerOptions object
  94910. */
  94911. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  94912. var result = new SceneOptimizerOptions(targetFrameRate);
  94913. var priority = 0;
  94914. result.addOptimization(new MergeMeshesOptimization(priority));
  94915. result.addOptimization(new ShadowsOptimization(priority));
  94916. result.addOptimization(new LensFlaresOptimization(priority));
  94917. // Next priority
  94918. priority++;
  94919. result.addOptimization(new PostProcessesOptimization(priority));
  94920. result.addOptimization(new ParticlesOptimization(priority));
  94921. // Next priority
  94922. priority++;
  94923. result.addOptimization(new TextureOptimization(priority, 256));
  94924. // Next priority
  94925. priority++;
  94926. result.addOptimization(new RenderTargetsOptimization(priority));
  94927. // Next priority
  94928. priority++;
  94929. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  94930. return result;
  94931. };
  94932. return SceneOptimizerOptions;
  94933. }());
  94934. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  94935. /**
  94936. * Class used to run optimizations in order to reach a target frame rate
  94937. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94938. */
  94939. var SceneOptimizer = /** @class */ (function () {
  94940. /**
  94941. * Creates a new SceneOptimizer
  94942. * @param scene defines the scene to work on
  94943. * @param options defines the options to use with the SceneOptimizer
  94944. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  94945. * @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)
  94946. */
  94947. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  94948. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  94949. if (improvementMode === void 0) { improvementMode = false; }
  94950. var _this = this;
  94951. this._isRunning = false;
  94952. this._currentPriorityLevel = 0;
  94953. this._targetFrameRate = 60;
  94954. this._trackerDuration = 2000;
  94955. this._currentFrameRate = 0;
  94956. this._improvementMode = false;
  94957. /**
  94958. * Defines an observable called when the optimizer reaches the target frame rate
  94959. */
  94960. this.onSuccessObservable = new BABYLON.Observable();
  94961. /**
  94962. * Defines an observable called when the optimizer enables an optimization
  94963. */
  94964. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  94965. /**
  94966. * Defines an observable called when the optimizer is not able to reach the target frame rate
  94967. */
  94968. this.onFailureObservable = new BABYLON.Observable();
  94969. if (!options) {
  94970. this._options = new SceneOptimizerOptions();
  94971. }
  94972. else {
  94973. this._options = options;
  94974. }
  94975. if (this._options.targetFrameRate) {
  94976. this._targetFrameRate = this._options.targetFrameRate;
  94977. }
  94978. if (this._options.trackerDuration) {
  94979. this._trackerDuration = this._options.trackerDuration;
  94980. }
  94981. if (autoGeneratePriorities) {
  94982. var priority = 0;
  94983. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  94984. var optim = _a[_i];
  94985. optim.priority = priority++;
  94986. }
  94987. }
  94988. this._improvementMode = improvementMode;
  94989. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  94990. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  94991. _this._sceneDisposeObserver = null;
  94992. _this.dispose();
  94993. });
  94994. }
  94995. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  94996. /**
  94997. * Gets a boolean indicating if the optimizer is in improvement mode
  94998. */
  94999. get: function () {
  95000. return this._improvementMode;
  95001. },
  95002. enumerable: true,
  95003. configurable: true
  95004. });
  95005. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95006. /**
  95007. * Gets the current priority level (0 at start)
  95008. */
  95009. get: function () {
  95010. return this._currentPriorityLevel;
  95011. },
  95012. enumerable: true,
  95013. configurable: true
  95014. });
  95015. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95016. /**
  95017. * Gets the current frame rate checked by the SceneOptimizer
  95018. */
  95019. get: function () {
  95020. return this._currentFrameRate;
  95021. },
  95022. enumerable: true,
  95023. configurable: true
  95024. });
  95025. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95026. /**
  95027. * Gets or sets the current target frame rate (60 by default)
  95028. */
  95029. get: function () {
  95030. return this._targetFrameRate;
  95031. },
  95032. /**
  95033. * Gets or sets the current target frame rate (60 by default)
  95034. */
  95035. set: function (value) {
  95036. this._targetFrameRate = value;
  95037. },
  95038. enumerable: true,
  95039. configurable: true
  95040. });
  95041. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95042. /**
  95043. * Gets or sets the current interval between two checks (every 2000ms by default)
  95044. */
  95045. get: function () {
  95046. return this._trackerDuration;
  95047. },
  95048. /**
  95049. * Gets or sets the current interval between two checks (every 2000ms by default)
  95050. */
  95051. set: function (value) {
  95052. this._trackerDuration = value;
  95053. },
  95054. enumerable: true,
  95055. configurable: true
  95056. });
  95057. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95058. /**
  95059. * Gets the list of active optimizations
  95060. */
  95061. get: function () {
  95062. return this._options.optimizations;
  95063. },
  95064. enumerable: true,
  95065. configurable: true
  95066. });
  95067. /**
  95068. * Stops the current optimizer
  95069. */
  95070. SceneOptimizer.prototype.stop = function () {
  95071. this._isRunning = false;
  95072. };
  95073. /**
  95074. * Reset the optimizer to initial step (current priority level = 0)
  95075. */
  95076. SceneOptimizer.prototype.reset = function () {
  95077. this._currentPriorityLevel = 0;
  95078. };
  95079. /**
  95080. * Start the optimizer. By default it will try to reach a specific framerate
  95081. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95082. */
  95083. SceneOptimizer.prototype.start = function () {
  95084. var _this = this;
  95085. if (this._isRunning) {
  95086. return;
  95087. }
  95088. this._isRunning = true;
  95089. // Let's wait for the scene to be ready before running our check
  95090. this._scene.executeWhenReady(function () {
  95091. setTimeout(function () {
  95092. _this._checkCurrentState();
  95093. }, _this._trackerDuration);
  95094. });
  95095. };
  95096. SceneOptimizer.prototype._checkCurrentState = function () {
  95097. var _this = this;
  95098. if (!this._isRunning) {
  95099. return;
  95100. }
  95101. var scene = this._scene;
  95102. var options = this._options;
  95103. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95104. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95105. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95106. this._isRunning = false;
  95107. this.onSuccessObservable.notifyObservers(this);
  95108. return;
  95109. }
  95110. // Apply current level of optimizations
  95111. var allDone = true;
  95112. var noOptimizationApplied = true;
  95113. for (var index = 0; index < options.optimizations.length; index++) {
  95114. var optimization = options.optimizations[index];
  95115. if (optimization.priority === this._currentPriorityLevel) {
  95116. noOptimizationApplied = false;
  95117. allDone = allDone && optimization.apply(scene, this);
  95118. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95119. }
  95120. }
  95121. // If no optimization was applied, this is a failure :(
  95122. if (noOptimizationApplied) {
  95123. this._isRunning = false;
  95124. this.onFailureObservable.notifyObservers(this);
  95125. return;
  95126. }
  95127. // If all optimizations were done, move to next level
  95128. if (allDone) {
  95129. this._currentPriorityLevel++;
  95130. }
  95131. // Let's the system running for a specific amount of time before checking FPS
  95132. scene.executeWhenReady(function () {
  95133. setTimeout(function () {
  95134. _this._checkCurrentState();
  95135. }, _this._trackerDuration);
  95136. });
  95137. };
  95138. /**
  95139. * Release all resources
  95140. */
  95141. SceneOptimizer.prototype.dispose = function () {
  95142. this.stop();
  95143. this.onSuccessObservable.clear();
  95144. this.onFailureObservable.clear();
  95145. this.onNewOptimizationAppliedObservable.clear();
  95146. if (this._sceneDisposeObserver) {
  95147. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95148. }
  95149. };
  95150. /**
  95151. * Helper function to create a SceneOptimizer with one single line of code
  95152. * @param scene defines the scene to work on
  95153. * @param options defines the options to use with the SceneOptimizer
  95154. * @param onSuccess defines a callback to call on success
  95155. * @param onFailure defines a callback to call on failure
  95156. * @returns the new SceneOptimizer object
  95157. */
  95158. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95159. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95160. if (onSuccess) {
  95161. optimizer.onSuccessObservable.add(function () {
  95162. onSuccess();
  95163. });
  95164. }
  95165. if (onFailure) {
  95166. optimizer.onFailureObservable.add(function () {
  95167. onFailure();
  95168. });
  95169. }
  95170. optimizer.start();
  95171. return optimizer;
  95172. };
  95173. return SceneOptimizer;
  95174. }());
  95175. BABYLON.SceneOptimizer = SceneOptimizer;
  95176. })(BABYLON || (BABYLON = {}));
  95177. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95178. var BABYLON;
  95179. (function (BABYLON) {
  95180. var OutlineRenderer = /** @class */ (function () {
  95181. function OutlineRenderer(scene) {
  95182. this.zOffset = 1;
  95183. this._scene = scene;
  95184. }
  95185. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95186. var _this = this;
  95187. if (useOverlay === void 0) { useOverlay = false; }
  95188. var scene = this._scene;
  95189. var engine = this._scene.getEngine();
  95190. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95191. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95192. return;
  95193. }
  95194. var mesh = subMesh.getRenderingMesh();
  95195. var material = subMesh.getMaterial();
  95196. if (!material || !scene.activeCamera) {
  95197. return;
  95198. }
  95199. engine.enableEffect(this._effect);
  95200. // Logarithmic depth
  95201. if (material.useLogarithmicDepth) {
  95202. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95203. }
  95204. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95205. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95206. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95207. // Bones
  95208. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95209. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95210. }
  95211. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95212. // Alpha test
  95213. if (material && material.needAlphaTesting()) {
  95214. var alphaTexture = material.getAlphaTestTexture();
  95215. if (alphaTexture) {
  95216. this._effect.setTexture("diffuseSampler", alphaTexture);
  95217. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95218. }
  95219. }
  95220. engine.setZOffset(-this.zOffset);
  95221. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95222. engine.setZOffset(0);
  95223. };
  95224. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95225. var defines = [];
  95226. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95227. var mesh = subMesh.getMesh();
  95228. var material = subMesh.getMaterial();
  95229. if (material) {
  95230. // Alpha test
  95231. if (material.needAlphaTesting()) {
  95232. defines.push("#define ALPHATEST");
  95233. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95234. attribs.push(BABYLON.VertexBuffer.UVKind);
  95235. defines.push("#define UV1");
  95236. }
  95237. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95238. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95239. defines.push("#define UV2");
  95240. }
  95241. }
  95242. //Logarithmic depth
  95243. if (material.useLogarithmicDepth) {
  95244. defines.push("#define LOGARITHMICDEPTH");
  95245. }
  95246. }
  95247. // Bones
  95248. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95249. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95250. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95251. if (mesh.numBoneInfluencers > 4) {
  95252. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95253. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95254. }
  95255. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95256. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95257. }
  95258. else {
  95259. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95260. }
  95261. // Instances
  95262. if (useInstances) {
  95263. defines.push("#define INSTANCES");
  95264. attribs.push("world0");
  95265. attribs.push("world1");
  95266. attribs.push("world2");
  95267. attribs.push("world3");
  95268. }
  95269. // Get correct effect
  95270. var join = defines.join("\n");
  95271. if (this._cachedDefines !== join) {
  95272. this._cachedDefines = join;
  95273. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95274. }
  95275. return this._effect.isReady();
  95276. };
  95277. return OutlineRenderer;
  95278. }());
  95279. BABYLON.OutlineRenderer = OutlineRenderer;
  95280. })(BABYLON || (BABYLON = {}));
  95281. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95282. var BABYLON;
  95283. (function (BABYLON) {
  95284. var FaceAdjacencies = /** @class */ (function () {
  95285. function FaceAdjacencies() {
  95286. this.edges = new Array();
  95287. this.edgesConnectedCount = 0;
  95288. }
  95289. return FaceAdjacencies;
  95290. }());
  95291. var EdgesRenderer = /** @class */ (function () {
  95292. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95293. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95294. if (epsilon === void 0) { epsilon = 0.95; }
  95295. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95296. this.edgesWidthScalerForOrthographic = 1000.0;
  95297. this.edgesWidthScalerForPerspective = 50.0;
  95298. this._linesPositions = new Array();
  95299. this._linesNormals = new Array();
  95300. this._linesIndices = new Array();
  95301. this._buffers = {};
  95302. this._checkVerticesInsteadOfIndices = false;
  95303. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95304. this.isEnabled = true;
  95305. this._source = source;
  95306. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95307. this._epsilon = epsilon;
  95308. this._prepareRessources();
  95309. this._generateEdgesLines();
  95310. }
  95311. EdgesRenderer.prototype._prepareRessources = function () {
  95312. if (this._lineShader) {
  95313. return;
  95314. }
  95315. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95316. attributes: ["position", "normal"],
  95317. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95318. });
  95319. this._lineShader.disableDepthWrite = true;
  95320. this._lineShader.backFaceCulling = false;
  95321. };
  95322. EdgesRenderer.prototype._rebuild = function () {
  95323. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95324. if (buffer) {
  95325. buffer._rebuild();
  95326. }
  95327. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95328. if (buffer) {
  95329. buffer._rebuild();
  95330. }
  95331. var scene = this._source.getScene();
  95332. var engine = scene.getEngine();
  95333. this._ib = engine.createIndexBuffer(this._linesIndices);
  95334. };
  95335. EdgesRenderer.prototype.dispose = function () {
  95336. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95337. if (buffer) {
  95338. buffer.dispose();
  95339. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95340. }
  95341. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95342. if (buffer) {
  95343. buffer.dispose();
  95344. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95345. }
  95346. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95347. this._lineShader.dispose();
  95348. };
  95349. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95350. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95351. return 0;
  95352. }
  95353. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95354. return 1;
  95355. }
  95356. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95357. return 2;
  95358. }
  95359. return -1;
  95360. };
  95361. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95362. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95363. return 0;
  95364. }
  95365. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95366. return 1;
  95367. }
  95368. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95369. return 2;
  95370. }
  95371. return -1;
  95372. };
  95373. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95374. var needToCreateLine;
  95375. if (edge === undefined) {
  95376. needToCreateLine = true;
  95377. }
  95378. else {
  95379. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95380. needToCreateLine = dotProduct < this._epsilon;
  95381. }
  95382. if (needToCreateLine) {
  95383. var offset = this._linesPositions.length / 3;
  95384. var normal = p0.subtract(p1);
  95385. normal.normalize();
  95386. // Positions
  95387. this._linesPositions.push(p0.x);
  95388. this._linesPositions.push(p0.y);
  95389. this._linesPositions.push(p0.z);
  95390. this._linesPositions.push(p0.x);
  95391. this._linesPositions.push(p0.y);
  95392. this._linesPositions.push(p0.z);
  95393. this._linesPositions.push(p1.x);
  95394. this._linesPositions.push(p1.y);
  95395. this._linesPositions.push(p1.z);
  95396. this._linesPositions.push(p1.x);
  95397. this._linesPositions.push(p1.y);
  95398. this._linesPositions.push(p1.z);
  95399. // Normals
  95400. this._linesNormals.push(p1.x);
  95401. this._linesNormals.push(p1.y);
  95402. this._linesNormals.push(p1.z);
  95403. this._linesNormals.push(-1);
  95404. this._linesNormals.push(p1.x);
  95405. this._linesNormals.push(p1.y);
  95406. this._linesNormals.push(p1.z);
  95407. this._linesNormals.push(1);
  95408. this._linesNormals.push(p0.x);
  95409. this._linesNormals.push(p0.y);
  95410. this._linesNormals.push(p0.z);
  95411. this._linesNormals.push(-1);
  95412. this._linesNormals.push(p0.x);
  95413. this._linesNormals.push(p0.y);
  95414. this._linesNormals.push(p0.z);
  95415. this._linesNormals.push(1);
  95416. // Indices
  95417. this._linesIndices.push(offset);
  95418. this._linesIndices.push(offset + 1);
  95419. this._linesIndices.push(offset + 2);
  95420. this._linesIndices.push(offset);
  95421. this._linesIndices.push(offset + 2);
  95422. this._linesIndices.push(offset + 3);
  95423. }
  95424. };
  95425. EdgesRenderer.prototype._generateEdgesLines = function () {
  95426. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95427. var indices = this._source.getIndices();
  95428. if (!indices || !positions) {
  95429. return;
  95430. }
  95431. // First let's find adjacencies
  95432. var adjacencies = new Array();
  95433. var faceNormals = new Array();
  95434. var index;
  95435. var faceAdjacencies;
  95436. // Prepare faces
  95437. for (index = 0; index < indices.length; index += 3) {
  95438. faceAdjacencies = new FaceAdjacencies();
  95439. var p0Index = indices[index];
  95440. var p1Index = indices[index + 1];
  95441. var p2Index = indices[index + 2];
  95442. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95443. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95444. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95445. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95446. faceNormal.normalize();
  95447. faceNormals.push(faceNormal);
  95448. adjacencies.push(faceAdjacencies);
  95449. }
  95450. // Scan
  95451. for (index = 0; index < adjacencies.length; index++) {
  95452. faceAdjacencies = adjacencies[index];
  95453. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95454. var otherFaceAdjacencies = adjacencies[otherIndex];
  95455. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95456. break;
  95457. }
  95458. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95459. continue;
  95460. }
  95461. var otherP0 = indices[otherIndex * 3];
  95462. var otherP1 = indices[otherIndex * 3 + 1];
  95463. var otherP2 = indices[otherIndex * 3 + 2];
  95464. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95465. var otherEdgeIndex = 0;
  95466. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95467. continue;
  95468. }
  95469. switch (edgeIndex) {
  95470. case 0:
  95471. if (this._checkVerticesInsteadOfIndices) {
  95472. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95473. }
  95474. else {
  95475. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95476. }
  95477. break;
  95478. case 1:
  95479. if (this._checkVerticesInsteadOfIndices) {
  95480. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95481. }
  95482. else {
  95483. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95484. }
  95485. break;
  95486. case 2:
  95487. if (this._checkVerticesInsteadOfIndices) {
  95488. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95489. }
  95490. else {
  95491. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95492. }
  95493. break;
  95494. }
  95495. if (otherEdgeIndex === -1) {
  95496. continue;
  95497. }
  95498. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95499. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95500. faceAdjacencies.edgesConnectedCount++;
  95501. otherFaceAdjacencies.edgesConnectedCount++;
  95502. if (faceAdjacencies.edgesConnectedCount === 3) {
  95503. break;
  95504. }
  95505. }
  95506. }
  95507. }
  95508. // Create lines
  95509. for (index = 0; index < adjacencies.length; index++) {
  95510. // 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
  95511. var current = adjacencies[index];
  95512. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95513. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95514. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95515. }
  95516. // Merge into a single mesh
  95517. var engine = this._source.getScene().getEngine();
  95518. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95519. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95520. this._ib = engine.createIndexBuffer(this._linesIndices);
  95521. this._indicesCount = this._linesIndices.length;
  95522. };
  95523. EdgesRenderer.prototype.render = function () {
  95524. var scene = this._source.getScene();
  95525. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95526. return;
  95527. }
  95528. var engine = scene.getEngine();
  95529. this._lineShader._preBind();
  95530. // VBOs
  95531. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95532. scene.resetCachedMaterial();
  95533. this._lineShader.setColor4("color", this._source.edgesColor);
  95534. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95535. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95536. }
  95537. else {
  95538. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95539. }
  95540. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95541. this._lineShader.bind(this._source.getWorldMatrix());
  95542. // Draw order
  95543. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95544. this._lineShader.unbind();
  95545. engine.setDepthWrite(true);
  95546. };
  95547. return EdgesRenderer;
  95548. }());
  95549. BABYLON.EdgesRenderer = EdgesRenderer;
  95550. })(BABYLON || (BABYLON = {}));
  95551. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95552. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95553. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95554. s = arguments[i];
  95555. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95556. t[p] = s[p];
  95557. }
  95558. return t;
  95559. };
  95560. var BABYLON;
  95561. (function (BABYLON) {
  95562. /**
  95563. * The effect layer Helps adding post process effect blended with the main pass.
  95564. *
  95565. * This can be for instance use to generate glow or higlight effects on the scene.
  95566. *
  95567. * The effect layer class can not be used directly and is intented to inherited from to be
  95568. * customized per effects.
  95569. */
  95570. var EffectLayer = /** @class */ (function () {
  95571. /**
  95572. * Instantiates a new effect Layer and references it in the scene.
  95573. * @param name The name of the layer
  95574. * @param scene The scene to use the layer in
  95575. */
  95576. function EffectLayer(
  95577. /** The Friendly of the effect in the scene */
  95578. name, scene) {
  95579. this._vertexBuffers = {};
  95580. this._maxSize = 0;
  95581. this._mainTextureDesiredSize = { width: 0, height: 0 };
  95582. this._shouldRender = true;
  95583. this._postProcesses = [];
  95584. this._textures = [];
  95585. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  95586. /**
  95587. * The clear color of the texture used to generate the glow map.
  95588. */
  95589. this.neutralColor = new BABYLON.Color4();
  95590. /**
  95591. * Specifies wether the highlight layer is enabled or not.
  95592. */
  95593. this.isEnabled = true;
  95594. /**
  95595. * An event triggered when the effect layer has been disposed.
  95596. */
  95597. this.onDisposeObservable = new BABYLON.Observable();
  95598. /**
  95599. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  95600. */
  95601. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  95602. /**
  95603. * An event triggered when the generated texture is being merged in the scene.
  95604. */
  95605. this.onBeforeComposeObservable = new BABYLON.Observable();
  95606. /**
  95607. * An event triggered when the generated texture has been merged in the scene.
  95608. */
  95609. this.onAfterComposeObservable = new BABYLON.Observable();
  95610. /**
  95611. * An event triggered when the efffect layer changes its size.
  95612. */
  95613. this.onSizeChangedObservable = new BABYLON.Observable();
  95614. this.name = name;
  95615. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95616. this._engine = scene.getEngine();
  95617. this._maxSize = this._engine.getCaps().maxTextureSize;
  95618. this._scene.effectLayers.push(this);
  95619. // Generate Buffers
  95620. this._generateIndexBuffer();
  95621. this._genrateVertexBuffer();
  95622. }
  95623. Object.defineProperty(EffectLayer.prototype, "camera", {
  95624. /**
  95625. * Gets the camera attached to the layer.
  95626. */
  95627. get: function () {
  95628. return this._effectLayerOptions.camera;
  95629. },
  95630. enumerable: true,
  95631. configurable: true
  95632. });
  95633. /**
  95634. * Initializes the effect layer with the required options.
  95635. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95636. */
  95637. EffectLayer.prototype._init = function (options) {
  95638. // Adapt options
  95639. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95640. this._setMainTextureSize();
  95641. this._createMainTexture();
  95642. this._createTextureAndPostProcesses();
  95643. this._mergeEffect = this._createMergeEffect();
  95644. };
  95645. /**
  95646. * Generates the index buffer of the full screen quad blending to the main canvas.
  95647. */
  95648. EffectLayer.prototype._generateIndexBuffer = function () {
  95649. // Indices
  95650. var indices = [];
  95651. indices.push(0);
  95652. indices.push(1);
  95653. indices.push(2);
  95654. indices.push(0);
  95655. indices.push(2);
  95656. indices.push(3);
  95657. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95658. };
  95659. /**
  95660. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95661. */
  95662. EffectLayer.prototype._genrateVertexBuffer = function () {
  95663. // VBO
  95664. var vertices = [];
  95665. vertices.push(1, 1);
  95666. vertices.push(-1, 1);
  95667. vertices.push(-1, -1);
  95668. vertices.push(1, -1);
  95669. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95670. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95671. };
  95672. /**
  95673. * Sets the main texture desired size which is the closest power of two
  95674. * of the engine canvas size.
  95675. */
  95676. EffectLayer.prototype._setMainTextureSize = function () {
  95677. if (this._effectLayerOptions.mainTextureFixedSize) {
  95678. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  95679. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  95680. }
  95681. else {
  95682. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  95683. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  95684. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  95685. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  95686. }
  95687. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  95688. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  95689. };
  95690. /**
  95691. * Creates the main texture for the effect layer.
  95692. */
  95693. EffectLayer.prototype._createMainTexture = function () {
  95694. var _this = this;
  95695. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  95696. width: this._mainTextureDesiredSize.width,
  95697. height: this._mainTextureDesiredSize.height
  95698. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95699. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  95700. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95701. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95702. this._mainTexture.anisotropicFilteringLevel = 1;
  95703. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95704. this._mainTexture.renderParticles = false;
  95705. this._mainTexture.renderList = null;
  95706. this._mainTexture.ignoreCameraViewport = true;
  95707. // Custom render function
  95708. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  95709. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  95710. var index;
  95711. var engine = _this._scene.getEngine();
  95712. if (depthOnlySubMeshes.length) {
  95713. engine.setColorWrite(false);
  95714. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  95715. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  95716. }
  95717. engine.setColorWrite(true);
  95718. }
  95719. for (index = 0; index < opaqueSubMeshes.length; index++) {
  95720. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  95721. }
  95722. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  95723. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  95724. }
  95725. for (index = 0; index < transparentSubMeshes.length; index++) {
  95726. _this._renderSubMesh(transparentSubMeshes.data[index]);
  95727. }
  95728. };
  95729. this._mainTexture.onClearObservable.add(function (engine) {
  95730. engine.clear(_this.neutralColor, true, true, true);
  95731. });
  95732. };
  95733. /**
  95734. * Checks for the readiness of the element composing the layer.
  95735. * @param subMesh the mesh to check for
  95736. * @param useInstances specify wether or not to use instances to render the mesh
  95737. * @param emissiveTexture the associated emissive texture used to generate the glow
  95738. * @return true if ready otherwise, false
  95739. */
  95740. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  95741. var material = subMesh.getMaterial();
  95742. if (!material) {
  95743. return false;
  95744. }
  95745. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  95746. return false;
  95747. }
  95748. var defines = [];
  95749. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95750. var mesh = subMesh.getMesh();
  95751. var uv1 = false;
  95752. var uv2 = false;
  95753. // Alpha test
  95754. if (material && material.needAlphaTesting()) {
  95755. var alphaTexture = material.getAlphaTestTexture();
  95756. if (alphaTexture) {
  95757. defines.push("#define ALPHATEST");
  95758. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95759. alphaTexture.coordinatesIndex === 1) {
  95760. defines.push("#define DIFFUSEUV2");
  95761. uv2 = true;
  95762. }
  95763. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95764. defines.push("#define DIFFUSEUV1");
  95765. uv1 = true;
  95766. }
  95767. }
  95768. }
  95769. // Emissive
  95770. if (emissiveTexture) {
  95771. defines.push("#define EMISSIVE");
  95772. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95773. emissiveTexture.coordinatesIndex === 1) {
  95774. defines.push("#define EMISSIVEUV2");
  95775. uv2 = true;
  95776. }
  95777. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95778. defines.push("#define EMISSIVEUV1");
  95779. uv1 = true;
  95780. }
  95781. }
  95782. if (uv1) {
  95783. attribs.push(BABYLON.VertexBuffer.UVKind);
  95784. defines.push("#define UV1");
  95785. }
  95786. if (uv2) {
  95787. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95788. defines.push("#define UV2");
  95789. }
  95790. // Bones
  95791. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95792. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95793. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95794. if (mesh.numBoneInfluencers > 4) {
  95795. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95796. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95797. }
  95798. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95799. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  95800. }
  95801. else {
  95802. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95803. }
  95804. // Morph targets
  95805. var manager = mesh.morphTargetManager;
  95806. var morphInfluencers = 0;
  95807. if (manager) {
  95808. if (manager.numInfluencers > 0) {
  95809. defines.push("#define MORPHTARGETS");
  95810. morphInfluencers = manager.numInfluencers;
  95811. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  95812. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  95813. }
  95814. }
  95815. // Instances
  95816. if (useInstances) {
  95817. defines.push("#define INSTANCES");
  95818. attribs.push("world0");
  95819. attribs.push("world1");
  95820. attribs.push("world2");
  95821. attribs.push("world3");
  95822. }
  95823. // Get correct effect
  95824. var join = defines.join("\n");
  95825. if (this._cachedDefines !== join) {
  95826. this._cachedDefines = join;
  95827. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  95828. }
  95829. return this._effectLayerMapGenerationEffect.isReady();
  95830. };
  95831. /**
  95832. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  95833. */
  95834. EffectLayer.prototype.render = function () {
  95835. var currentEffect = this._mergeEffect;
  95836. // Check
  95837. if (!currentEffect.isReady())
  95838. return;
  95839. for (var i = 0; i < this._postProcesses.length; i++) {
  95840. if (!this._postProcesses[i].isReady()) {
  95841. return;
  95842. }
  95843. }
  95844. var engine = this._scene.getEngine();
  95845. this.onBeforeComposeObservable.notifyObservers(this);
  95846. // Render
  95847. engine.enableEffect(currentEffect);
  95848. engine.setState(false);
  95849. // VBOs
  95850. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  95851. // Cache
  95852. var previousAlphaMode = engine.getAlphaMode();
  95853. // Go Blend.
  95854. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  95855. // Blends the map on the main canvas.
  95856. this._internalRender(currentEffect);
  95857. // Restore Alpha
  95858. engine.setAlphaMode(previousAlphaMode);
  95859. this.onAfterComposeObservable.notifyObservers(this);
  95860. // Handle size changes.
  95861. var size = this._mainTexture.getSize();
  95862. this._setMainTextureSize();
  95863. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  95864. // Recreate RTT and post processes on size change.
  95865. this.onSizeChangedObservable.notifyObservers(this);
  95866. this._disposeTextureAndPostProcesses();
  95867. this._createMainTexture();
  95868. this._createTextureAndPostProcesses();
  95869. }
  95870. };
  95871. /**
  95872. * Determine if a given mesh will be used in the current effect.
  95873. * @param mesh mesh to test
  95874. * @returns true if the mesh will be used
  95875. */
  95876. EffectLayer.prototype.hasMesh = function (mesh) {
  95877. return true;
  95878. };
  95879. /**
  95880. * Returns true if the layer contains information to display, otherwise false.
  95881. * @returns true if the glow layer should be rendered
  95882. */
  95883. EffectLayer.prototype.shouldRender = function () {
  95884. return this.isEnabled && this._shouldRender;
  95885. };
  95886. /**
  95887. * Returns true if the mesh should render, otherwise false.
  95888. * @param mesh The mesh to render
  95889. * @returns true if it should render otherwise false
  95890. */
  95891. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  95892. return true;
  95893. };
  95894. /**
  95895. * Returns true if the mesh should render, otherwise false.
  95896. * @param mesh The mesh to render
  95897. * @returns true if it should render otherwise false
  95898. */
  95899. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  95900. return true;
  95901. };
  95902. /**
  95903. * Renders the submesh passed in parameter to the generation map.
  95904. */
  95905. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  95906. var _this = this;
  95907. if (!this.shouldRender()) {
  95908. return;
  95909. }
  95910. var material = subMesh.getMaterial();
  95911. var mesh = subMesh.getRenderingMesh();
  95912. var scene = this._scene;
  95913. var engine = scene.getEngine();
  95914. if (!material) {
  95915. return;
  95916. }
  95917. // Do not block in blend mode.
  95918. if (material.needAlphaBlendingForMesh(mesh)) {
  95919. return;
  95920. }
  95921. // Culling
  95922. engine.setState(material.backFaceCulling);
  95923. // Managing instances
  95924. var batch = mesh._getInstancesRenderList(subMesh._id);
  95925. if (batch.mustReturn) {
  95926. return;
  95927. }
  95928. // Early Exit per mesh
  95929. if (!this._shouldRenderMesh(mesh)) {
  95930. return;
  95931. }
  95932. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95933. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  95934. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  95935. engine.enableEffect(this._effectLayerMapGenerationEffect);
  95936. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  95937. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  95938. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  95939. // Alpha test
  95940. if (material && material.needAlphaTesting()) {
  95941. var alphaTexture = material.getAlphaTestTexture();
  95942. if (alphaTexture) {
  95943. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  95944. var textureMatrix = alphaTexture.getTextureMatrix();
  95945. if (textureMatrix) {
  95946. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  95947. }
  95948. }
  95949. }
  95950. // Glow emissive only
  95951. if (this._emissiveTextureAndColor.texture) {
  95952. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  95953. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  95954. }
  95955. // Bones
  95956. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95957. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95958. }
  95959. // Morph targets
  95960. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  95961. // Draw
  95962. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  95963. }
  95964. else {
  95965. // Need to reset refresh rate of the shadowMap
  95966. this._mainTexture.resetRefreshCounter();
  95967. }
  95968. };
  95969. /**
  95970. * Rebuild the required buffers.
  95971. * @hidden Internal use only.
  95972. */
  95973. EffectLayer.prototype._rebuild = function () {
  95974. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  95975. if (vb) {
  95976. vb._rebuild();
  95977. }
  95978. this._generateIndexBuffer();
  95979. };
  95980. /**
  95981. * Dispose only the render target textures and post process.
  95982. */
  95983. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  95984. this._mainTexture.dispose();
  95985. for (var i = 0; i < this._postProcesses.length; i++) {
  95986. if (this._postProcesses[i]) {
  95987. this._postProcesses[i].dispose();
  95988. }
  95989. }
  95990. this._postProcesses = [];
  95991. for (var i = 0; i < this._textures.length; i++) {
  95992. if (this._textures[i]) {
  95993. this._textures[i].dispose();
  95994. }
  95995. }
  95996. this._textures = [];
  95997. };
  95998. /**
  95999. * Dispose the highlight layer and free resources.
  96000. */
  96001. EffectLayer.prototype.dispose = function () {
  96002. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96003. if (vertexBuffer) {
  96004. vertexBuffer.dispose();
  96005. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96006. }
  96007. if (this._indexBuffer) {
  96008. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96009. this._indexBuffer = null;
  96010. }
  96011. // Clean textures and post processes
  96012. this._disposeTextureAndPostProcesses();
  96013. // Remove from scene
  96014. var index = this._scene.effectLayers.indexOf(this, 0);
  96015. if (index > -1) {
  96016. this._scene.effectLayers.splice(index, 1);
  96017. }
  96018. // Callback
  96019. this.onDisposeObservable.notifyObservers(this);
  96020. this.onDisposeObservable.clear();
  96021. this.onBeforeRenderMainTextureObservable.clear();
  96022. this.onBeforeComposeObservable.clear();
  96023. this.onAfterComposeObservable.clear();
  96024. this.onSizeChangedObservable.clear();
  96025. };
  96026. /**
  96027. * Gets the class name of the effect layer
  96028. * @returns the string with the class name of the effect layer
  96029. */
  96030. EffectLayer.prototype.getClassName = function () {
  96031. return "EffectLayer";
  96032. };
  96033. /**
  96034. * Creates an effect layer from parsed effect layer data
  96035. * @param parsedEffectLayer defines effect layer data
  96036. * @param scene defines the current scene
  96037. * @param rootUrl defines the root URL containing the effect layer information
  96038. * @returns a parsed effect Layer
  96039. */
  96040. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96041. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96042. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96043. };
  96044. __decorate([
  96045. BABYLON.serialize()
  96046. ], EffectLayer.prototype, "name", void 0);
  96047. __decorate([
  96048. BABYLON.serializeAsColor4()
  96049. ], EffectLayer.prototype, "neutralColor", void 0);
  96050. __decorate([
  96051. BABYLON.serialize()
  96052. ], EffectLayer.prototype, "isEnabled", void 0);
  96053. __decorate([
  96054. BABYLON.serializeAsCameraReference()
  96055. ], EffectLayer.prototype, "camera", null);
  96056. return EffectLayer;
  96057. }());
  96058. BABYLON.EffectLayer = EffectLayer;
  96059. })(BABYLON || (BABYLON = {}));
  96060. //# sourceMappingURL=babylon.effectLayer.js.map
  96061. var BABYLON;
  96062. (function (BABYLON) {
  96063. /**
  96064. * Special Glow Blur post process only blurring the alpha channel
  96065. * It enforces keeping the most luminous color in the color channel.
  96066. */
  96067. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96068. __extends(GlowBlurPostProcess, _super);
  96069. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96070. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96071. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96072. _this.direction = direction;
  96073. _this.kernel = kernel;
  96074. _this.onApplyObservable.add(function (effect) {
  96075. effect.setFloat2("screenSize", _this.width, _this.height);
  96076. effect.setVector2("direction", _this.direction);
  96077. effect.setFloat("blurWidth", _this.kernel);
  96078. });
  96079. return _this;
  96080. }
  96081. return GlowBlurPostProcess;
  96082. }(BABYLON.PostProcess));
  96083. /**
  96084. * The highlight layer Helps adding a glow effect around a mesh.
  96085. *
  96086. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96087. * glowy meshes to your scene.
  96088. *
  96089. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96090. */
  96091. var HighlightLayer = /** @class */ (function (_super) {
  96092. __extends(HighlightLayer, _super);
  96093. /**
  96094. * Instantiates a new highlight Layer and references it to the scene..
  96095. * @param name The name of the layer
  96096. * @param scene The scene to use the layer in
  96097. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96098. */
  96099. function HighlightLayer(name, scene, options) {
  96100. var _this = _super.call(this, name, scene) || this;
  96101. _this.name = name;
  96102. /**
  96103. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96104. */
  96105. _this.innerGlow = true;
  96106. /**
  96107. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96108. */
  96109. _this.outerGlow = true;
  96110. /**
  96111. * An event triggered when the highlight layer is being blurred.
  96112. */
  96113. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96114. /**
  96115. * An event triggered when the highlight layer has been blurred.
  96116. */
  96117. _this.onAfterBlurObservable = new BABYLON.Observable();
  96118. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96119. _this._meshes = {};
  96120. _this._excludedMeshes = {};
  96121. _this.neutralColor = HighlightLayer.NeutralColor;
  96122. // Warn on stencil
  96123. if (!_this._engine.isStencilEnable) {
  96124. 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 }");
  96125. }
  96126. // Adapt options
  96127. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  96128. // Initialize the layer
  96129. _this._init({
  96130. alphaBlendingMode: _this._options.alphaBlendingMode,
  96131. camera: _this._options.camera,
  96132. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96133. mainTextureRatio: _this._options.mainTextureRatio
  96134. });
  96135. // Do not render as long as no meshes have been added
  96136. _this._shouldRender = false;
  96137. return _this;
  96138. }
  96139. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96140. /**
  96141. * Gets the horizontal size of the blur.
  96142. */
  96143. get: function () {
  96144. return this._horizontalBlurPostprocess.kernel;
  96145. },
  96146. /**
  96147. * Specifies the horizontal size of the blur.
  96148. */
  96149. set: function (value) {
  96150. this._horizontalBlurPostprocess.kernel = value;
  96151. },
  96152. enumerable: true,
  96153. configurable: true
  96154. });
  96155. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96156. /**
  96157. * Gets the vertical size of the blur.
  96158. */
  96159. get: function () {
  96160. return this._verticalBlurPostprocess.kernel;
  96161. },
  96162. /**
  96163. * Specifies the vertical size of the blur.
  96164. */
  96165. set: function (value) {
  96166. this._verticalBlurPostprocess.kernel = value;
  96167. },
  96168. enumerable: true,
  96169. configurable: true
  96170. });
  96171. /**
  96172. * Get the effect name of the layer.
  96173. * @return The effect name
  96174. */
  96175. HighlightLayer.prototype.getEffectName = function () {
  96176. return HighlightLayer.EffectName;
  96177. };
  96178. /**
  96179. * Create the merge effect. This is the shader use to blit the information back
  96180. * to the main canvas at the end of the scene rendering.
  96181. */
  96182. HighlightLayer.prototype._createMergeEffect = function () {
  96183. // Effect
  96184. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  96185. };
  96186. /**
  96187. * Creates the render target textures and post processes used in the highlight layer.
  96188. */
  96189. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  96190. var _this = this;
  96191. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  96192. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  96193. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96194. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96195. var textureType = 0;
  96196. if (this._engine.getCaps().textureHalfFloatRender) {
  96197. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96198. }
  96199. else {
  96200. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96201. }
  96202. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  96203. width: blurTextureWidth,
  96204. height: blurTextureHeight
  96205. }, this._scene, false, true, textureType);
  96206. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96207. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96208. this._blurTexture.anisotropicFilteringLevel = 16;
  96209. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  96210. this._blurTexture.renderParticles = false;
  96211. this._blurTexture.ignoreCameraViewport = true;
  96212. this._textures = [this._blurTexture];
  96213. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  96214. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96215. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  96216. effect.setTexture("textureSampler", _this._mainTexture);
  96217. });
  96218. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96219. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96220. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96221. });
  96222. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96223. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  96224. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96225. });
  96226. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96227. }
  96228. else {
  96229. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  96230. width: blurTextureWidth,
  96231. height: blurTextureHeight
  96232. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96233. this._horizontalBlurPostprocess.width = blurTextureWidth;
  96234. this._horizontalBlurPostprocess.height = blurTextureHeight;
  96235. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96236. effect.setTexture("textureSampler", _this._mainTexture);
  96237. });
  96238. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  96239. width: blurTextureWidth,
  96240. height: blurTextureHeight
  96241. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96242. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96243. }
  96244. this._mainTexture.onAfterUnbindObservable.add(function () {
  96245. _this.onBeforeBlurObservable.notifyObservers(_this);
  96246. var internalTexture = _this._blurTexture.getInternalTexture();
  96247. if (internalTexture) {
  96248. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  96249. }
  96250. _this.onAfterBlurObservable.notifyObservers(_this);
  96251. });
  96252. // Prevent autoClear.
  96253. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96254. };
  96255. /**
  96256. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96257. */
  96258. HighlightLayer.prototype.needStencil = function () {
  96259. return true;
  96260. };
  96261. /**
  96262. * Checks for the readiness of the element composing the layer.
  96263. * @param subMesh the mesh to check for
  96264. * @param useInstances specify wether or not to use instances to render the mesh
  96265. * @param emissiveTexture the associated emissive texture used to generate the glow
  96266. * @return true if ready otherwise, false
  96267. */
  96268. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  96269. var material = subMesh.getMaterial();
  96270. var mesh = subMesh.getRenderingMesh();
  96271. if (!material || !mesh || !this._meshes) {
  96272. return false;
  96273. }
  96274. var emissiveTexture = null;
  96275. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96276. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96277. emissiveTexture = material.emissiveTexture;
  96278. }
  96279. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96280. };
  96281. /**
  96282. * Implementation specific of rendering the generating effect on the main canvas.
  96283. * @param effect The effect used to render through
  96284. */
  96285. HighlightLayer.prototype._internalRender = function (effect) {
  96286. // Texture
  96287. effect.setTexture("textureSampler", this._blurTexture);
  96288. // Cache
  96289. var engine = this._engine;
  96290. var previousStencilBuffer = engine.getStencilBuffer();
  96291. var previousStencilFunction = engine.getStencilFunction();
  96292. var previousStencilMask = engine.getStencilMask();
  96293. var previousStencilOperationPass = engine.getStencilOperationPass();
  96294. var previousStencilOperationFail = engine.getStencilOperationFail();
  96295. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  96296. var previousStencilReference = engine.getStencilFunctionReference();
  96297. // Stencil operations
  96298. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  96299. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  96300. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  96301. // Draw order
  96302. engine.setStencilMask(0x00);
  96303. engine.setStencilBuffer(true);
  96304. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  96305. // 2 passes inner outer
  96306. if (this.outerGlow) {
  96307. effect.setFloat("offset", 0);
  96308. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  96309. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96310. }
  96311. if (this.innerGlow) {
  96312. effect.setFloat("offset", 1);
  96313. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  96314. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96315. }
  96316. // Restore Cache
  96317. engine.setStencilFunction(previousStencilFunction);
  96318. engine.setStencilMask(previousStencilMask);
  96319. engine.setStencilBuffer(previousStencilBuffer);
  96320. engine.setStencilOperationPass(previousStencilOperationPass);
  96321. engine.setStencilOperationFail(previousStencilOperationFail);
  96322. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  96323. engine.setStencilFunctionReference(previousStencilReference);
  96324. };
  96325. /**
  96326. * Returns true if the layer contains information to display, otherwise false.
  96327. */
  96328. HighlightLayer.prototype.shouldRender = function () {
  96329. if (_super.prototype.shouldRender.call(this)) {
  96330. return this._meshes ? true : false;
  96331. }
  96332. return false;
  96333. };
  96334. /**
  96335. * Returns true if the mesh should render, otherwise false.
  96336. * @param mesh The mesh to render
  96337. * @returns true if it should render otherwise false
  96338. */
  96339. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  96340. // Excluded Mesh
  96341. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  96342. return false;
  96343. }
  96344. ;
  96345. return true;
  96346. };
  96347. /**
  96348. * Sets the required values for both the emissive texture and and the main color.
  96349. */
  96350. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96351. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96352. if (highlightLayerMesh) {
  96353. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  96354. }
  96355. else {
  96356. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96357. }
  96358. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96359. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96360. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  96361. }
  96362. else {
  96363. this._emissiveTextureAndColor.texture = null;
  96364. }
  96365. };
  96366. /**
  96367. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  96368. * @param mesh The mesh to exclude from the highlight layer
  96369. */
  96370. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  96371. if (!this._excludedMeshes) {
  96372. return;
  96373. }
  96374. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96375. if (!meshExcluded) {
  96376. this._excludedMeshes[mesh.uniqueId] = {
  96377. mesh: mesh,
  96378. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  96379. mesh.getEngine().setStencilBuffer(false);
  96380. }),
  96381. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  96382. mesh.getEngine().setStencilBuffer(true);
  96383. }),
  96384. };
  96385. }
  96386. };
  96387. /**
  96388. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  96389. * @param mesh The mesh to highlight
  96390. */
  96391. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  96392. if (!this._excludedMeshes) {
  96393. return;
  96394. }
  96395. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96396. if (meshExcluded) {
  96397. if (meshExcluded.beforeRender) {
  96398. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  96399. }
  96400. if (meshExcluded.afterRender) {
  96401. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  96402. }
  96403. }
  96404. this._excludedMeshes[mesh.uniqueId] = null;
  96405. };
  96406. /**
  96407. * Determine if a given mesh will be highlighted by the current HighlightLayer
  96408. * @param mesh mesh to test
  96409. * @returns true if the mesh will be highlighted by the current HighlightLayer
  96410. */
  96411. HighlightLayer.prototype.hasMesh = function (mesh) {
  96412. if (!this._meshes) {
  96413. return false;
  96414. }
  96415. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  96416. };
  96417. /**
  96418. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  96419. * @param mesh The mesh to highlight
  96420. * @param color The color of the highlight
  96421. * @param glowEmissiveOnly Extract the glow from the emissive texture
  96422. */
  96423. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  96424. var _this = this;
  96425. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  96426. if (!this._meshes) {
  96427. return;
  96428. }
  96429. var meshHighlight = this._meshes[mesh.uniqueId];
  96430. if (meshHighlight) {
  96431. meshHighlight.color = color;
  96432. }
  96433. else {
  96434. this._meshes[mesh.uniqueId] = {
  96435. mesh: mesh,
  96436. color: color,
  96437. // Lambda required for capture due to Observable this context
  96438. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  96439. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  96440. _this._defaultStencilReference(mesh);
  96441. }
  96442. else {
  96443. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  96444. }
  96445. }),
  96446. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  96447. glowEmissiveOnly: glowEmissiveOnly
  96448. };
  96449. }
  96450. this._shouldRender = true;
  96451. };
  96452. /**
  96453. * Remove a mesh from the highlight layer in order to make it stop glowing.
  96454. * @param mesh The mesh to highlight
  96455. */
  96456. HighlightLayer.prototype.removeMesh = function (mesh) {
  96457. if (!this._meshes) {
  96458. return;
  96459. }
  96460. var meshHighlight = this._meshes[mesh.uniqueId];
  96461. if (meshHighlight) {
  96462. if (meshHighlight.observerHighlight) {
  96463. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96464. }
  96465. if (meshHighlight.observerDefault) {
  96466. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96467. }
  96468. delete this._meshes[mesh.uniqueId];
  96469. }
  96470. this._shouldRender = false;
  96471. for (var meshHighlightToCheck in this._meshes) {
  96472. if (this._meshes[meshHighlightToCheck]) {
  96473. this._shouldRender = true;
  96474. break;
  96475. }
  96476. }
  96477. };
  96478. /**
  96479. * Force the stencil to the normal expected value for none glowing parts
  96480. */
  96481. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  96482. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  96483. };
  96484. /**
  96485. * Free any resources and references associated to a mesh.
  96486. * Internal use
  96487. * @param mesh The mesh to free.
  96488. */
  96489. HighlightLayer.prototype._disposeMesh = function (mesh) {
  96490. this.removeMesh(mesh);
  96491. this.removeExcludedMesh(mesh);
  96492. };
  96493. /**
  96494. * Dispose the highlight layer and free resources.
  96495. */
  96496. HighlightLayer.prototype.dispose = function () {
  96497. if (this._meshes) {
  96498. // Clean mesh references
  96499. for (var id in this._meshes) {
  96500. var meshHighlight = this._meshes[id];
  96501. if (meshHighlight && meshHighlight.mesh) {
  96502. if (meshHighlight.observerHighlight) {
  96503. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96504. }
  96505. if (meshHighlight.observerDefault) {
  96506. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96507. }
  96508. }
  96509. }
  96510. this._meshes = null;
  96511. }
  96512. if (this._excludedMeshes) {
  96513. for (var id in this._excludedMeshes) {
  96514. var meshHighlight = this._excludedMeshes[id];
  96515. if (meshHighlight) {
  96516. if (meshHighlight.beforeRender) {
  96517. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  96518. }
  96519. if (meshHighlight.afterRender) {
  96520. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  96521. }
  96522. }
  96523. }
  96524. this._excludedMeshes = null;
  96525. }
  96526. _super.prototype.dispose.call(this);
  96527. };
  96528. /**
  96529. * Gets the class name of the effect layer
  96530. * @returns the string with the class name of the effect layer
  96531. */
  96532. HighlightLayer.prototype.getClassName = function () {
  96533. return "HighlightLayer";
  96534. };
  96535. /**
  96536. * Serializes this Highlight layer
  96537. * @returns a serialized Highlight layer object
  96538. */
  96539. HighlightLayer.prototype.serialize = function () {
  96540. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96541. serializationObject.customType = "BABYLON.HighlightLayer";
  96542. // Highlighted meshes
  96543. serializationObject.meshes = [];
  96544. if (this._meshes) {
  96545. for (var m in this._meshes) {
  96546. var mesh = this._meshes[m];
  96547. if (mesh) {
  96548. serializationObject.meshes.push({
  96549. glowEmissiveOnly: mesh.glowEmissiveOnly,
  96550. color: mesh.color.asArray(),
  96551. meshId: mesh.mesh.id
  96552. });
  96553. }
  96554. }
  96555. }
  96556. // Excluded meshes
  96557. serializationObject.excludedMeshes = [];
  96558. if (this._excludedMeshes) {
  96559. for (var e in this._excludedMeshes) {
  96560. var excludedMesh = this._excludedMeshes[e];
  96561. if (excludedMesh) {
  96562. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  96563. }
  96564. }
  96565. }
  96566. return serializationObject;
  96567. };
  96568. /**
  96569. * Creates a Highlight layer from parsed Highlight layer data
  96570. * @param parsedHightlightLayer defines the Highlight layer data
  96571. * @param scene defines the current scene
  96572. * @param rootUrl defines the root URL containing the Highlight layer information
  96573. * @returns a parsed Highlight layer
  96574. */
  96575. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  96576. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  96577. var index;
  96578. // Excluded meshes
  96579. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  96580. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  96581. if (mesh) {
  96582. hl.addExcludedMesh(mesh);
  96583. }
  96584. }
  96585. // Included meshes
  96586. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  96587. var highlightedMesh = parsedHightlightLayer.meshes[index];
  96588. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  96589. if (mesh) {
  96590. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  96591. }
  96592. }
  96593. return hl;
  96594. };
  96595. /**
  96596. * Effect Name of the highlight layer.
  96597. */
  96598. HighlightLayer.EffectName = "HighlightLayer";
  96599. /**
  96600. * The neutral color used during the preparation of the glow effect.
  96601. * This is black by default as the blend operation is a blend operation.
  96602. */
  96603. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  96604. /**
  96605. * Stencil value used for glowing meshes.
  96606. */
  96607. HighlightLayer.GlowingMeshStencilReference = 0x02;
  96608. /**
  96609. * Stencil value used for the other meshes in the scene.
  96610. */
  96611. HighlightLayer.NormalMeshStencilReference = 0x01;
  96612. __decorate([
  96613. BABYLON.serialize()
  96614. ], HighlightLayer.prototype, "innerGlow", void 0);
  96615. __decorate([
  96616. BABYLON.serialize()
  96617. ], HighlightLayer.prototype, "outerGlow", void 0);
  96618. __decorate([
  96619. BABYLON.serialize()
  96620. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96621. __decorate([
  96622. BABYLON.serialize()
  96623. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96624. __decorate([
  96625. BABYLON.serialize("options")
  96626. ], HighlightLayer.prototype, "_options", void 0);
  96627. return HighlightLayer;
  96628. }(BABYLON.EffectLayer));
  96629. BABYLON.HighlightLayer = HighlightLayer;
  96630. })(BABYLON || (BABYLON = {}));
  96631. //# sourceMappingURL=babylon.highlightLayer.js.map
  96632. var BABYLON;
  96633. (function (BABYLON) {
  96634. /**
  96635. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96636. *
  96637. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96638. * glowy meshes to your scene.
  96639. *
  96640. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96641. */
  96642. var GlowLayer = /** @class */ (function (_super) {
  96643. __extends(GlowLayer, _super);
  96644. /**
  96645. * Instantiates a new glow Layer and references it to the scene.
  96646. * @param name The name of the layer
  96647. * @param scene The scene to use the layer in
  96648. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96649. */
  96650. function GlowLayer(name, scene, options) {
  96651. var _this = _super.call(this, name, scene) || this;
  96652. _this._intensity = 1.0;
  96653. _this._includedOnlyMeshes = [];
  96654. _this._excludedMeshes = [];
  96655. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96656. // Adapt options
  96657. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  96658. // Initialize the layer
  96659. _this._init({
  96660. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  96661. camera: _this._options.camera,
  96662. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96663. mainTextureRatio: _this._options.mainTextureRatio
  96664. });
  96665. return _this;
  96666. }
  96667. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  96668. /**
  96669. * Gets the kernel size of the blur.
  96670. */
  96671. get: function () {
  96672. return this._horizontalBlurPostprocess1.kernel;
  96673. },
  96674. /**
  96675. * Sets the kernel size of the blur.
  96676. */
  96677. set: function (value) {
  96678. this._horizontalBlurPostprocess1.kernel = value;
  96679. this._verticalBlurPostprocess1.kernel = value;
  96680. this._horizontalBlurPostprocess2.kernel = value;
  96681. this._verticalBlurPostprocess2.kernel = value;
  96682. },
  96683. enumerable: true,
  96684. configurable: true
  96685. });
  96686. Object.defineProperty(GlowLayer.prototype, "intensity", {
  96687. /**
  96688. * Gets the glow intensity.
  96689. */
  96690. get: function () {
  96691. return this._intensity;
  96692. },
  96693. /**
  96694. * Sets the glow intensity.
  96695. */
  96696. set: function (value) {
  96697. this._intensity = value;
  96698. },
  96699. enumerable: true,
  96700. configurable: true
  96701. });
  96702. /**
  96703. * Get the effect name of the layer.
  96704. * @return The effect name
  96705. */
  96706. GlowLayer.prototype.getEffectName = function () {
  96707. return GlowLayer.EffectName;
  96708. };
  96709. /**
  96710. * Create the merge effect. This is the shader use to blit the information back
  96711. * to the main canvas at the end of the scene rendering.
  96712. */
  96713. GlowLayer.prototype._createMergeEffect = function () {
  96714. // Effect
  96715. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  96716. };
  96717. /**
  96718. * Creates the render target textures and post processes used in the glow layer.
  96719. */
  96720. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  96721. var _this = this;
  96722. var blurTextureWidth = this._mainTextureDesiredSize.width;
  96723. var blurTextureHeight = this._mainTextureDesiredSize.height;
  96724. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96725. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96726. var textureType = 0;
  96727. if (this._engine.getCaps().textureHalfFloatRender) {
  96728. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96729. }
  96730. else {
  96731. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96732. }
  96733. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  96734. width: blurTextureWidth,
  96735. height: blurTextureHeight
  96736. }, this._scene, false, true, textureType);
  96737. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96738. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96739. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96740. this._blurTexture1.renderParticles = false;
  96741. this._blurTexture1.ignoreCameraViewport = true;
  96742. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  96743. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  96744. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  96745. width: blurTextureWidth2,
  96746. height: blurTextureHeight2
  96747. }, this._scene, false, true, textureType);
  96748. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96749. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96750. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96751. this._blurTexture2.renderParticles = false;
  96752. this._blurTexture2.ignoreCameraViewport = true;
  96753. this._textures = [this._blurTexture1, this._blurTexture2];
  96754. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96755. width: blurTextureWidth,
  96756. height: blurTextureHeight
  96757. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96758. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  96759. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  96760. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  96761. effect.setTexture("textureSampler", _this._mainTexture);
  96762. });
  96763. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96764. width: blurTextureWidth,
  96765. height: blurTextureHeight
  96766. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96767. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96768. width: blurTextureWidth2,
  96769. height: blurTextureHeight2
  96770. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96771. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  96772. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  96773. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  96774. effect.setTexture("textureSampler", _this._blurTexture1);
  96775. });
  96776. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96777. width: blurTextureWidth2,
  96778. height: blurTextureHeight2
  96779. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96780. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96781. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  96782. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96783. this._mainTexture.samples = this._options.mainTextureSamples;
  96784. this._mainTexture.onAfterUnbindObservable.add(function () {
  96785. var internalTexture = _this._blurTexture1.getInternalTexture();
  96786. if (internalTexture) {
  96787. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  96788. internalTexture = _this._blurTexture2.getInternalTexture();
  96789. if (internalTexture) {
  96790. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  96791. }
  96792. }
  96793. });
  96794. // Prevent autoClear.
  96795. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96796. };
  96797. /**
  96798. * Checks for the readiness of the element composing the layer.
  96799. * @param subMesh the mesh to check for
  96800. * @param useInstances specify wether or not to use instances to render the mesh
  96801. * @param emissiveTexture the associated emissive texture used to generate the glow
  96802. * @return true if ready otherwise, false
  96803. */
  96804. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  96805. var material = subMesh.getMaterial();
  96806. var mesh = subMesh.getRenderingMesh();
  96807. if (!material || !mesh) {
  96808. return false;
  96809. }
  96810. var emissiveTexture = material.emissiveTexture;
  96811. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96812. };
  96813. /**
  96814. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96815. */
  96816. GlowLayer.prototype.needStencil = function () {
  96817. return false;
  96818. };
  96819. /**
  96820. * Implementation specific of rendering the generating effect on the main canvas.
  96821. * @param effect The effect used to render through
  96822. */
  96823. GlowLayer.prototype._internalRender = function (effect) {
  96824. // Texture
  96825. effect.setTexture("textureSampler", this._blurTexture1);
  96826. effect.setTexture("textureSampler2", this._blurTexture2);
  96827. effect.setFloat("offset", this._intensity);
  96828. // Cache
  96829. var engine = this._engine;
  96830. var previousStencilBuffer = engine.getStencilBuffer();
  96831. // Draw order
  96832. engine.setStencilBuffer(false);
  96833. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96834. // Draw order
  96835. engine.setStencilBuffer(previousStencilBuffer);
  96836. };
  96837. /**
  96838. * Sets the required values for both the emissive texture and and the main color.
  96839. */
  96840. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96841. var textureLevel = 1.0;
  96842. if (this.customEmissiveTextureSelector) {
  96843. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  96844. }
  96845. else {
  96846. if (material) {
  96847. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96848. if (this._emissiveTextureAndColor.texture) {
  96849. textureLevel = this._emissiveTextureAndColor.texture.level;
  96850. }
  96851. }
  96852. else {
  96853. this._emissiveTextureAndColor.texture = null;
  96854. }
  96855. }
  96856. if (this.customEmissiveColorSelector) {
  96857. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  96858. }
  96859. else {
  96860. if (material.emissiveColor) {
  96861. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  96862. }
  96863. else {
  96864. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96865. }
  96866. }
  96867. };
  96868. /**
  96869. * Returns true if the mesh should render, otherwise false.
  96870. * @param mesh The mesh to render
  96871. * @returns true if it should render otherwise false
  96872. */
  96873. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  96874. return this.hasMesh(mesh);
  96875. };
  96876. /**
  96877. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  96878. * @param mesh The mesh to exclude from the glow layer
  96879. */
  96880. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  96881. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  96882. this._excludedMeshes.push(mesh.uniqueId);
  96883. }
  96884. };
  96885. /**
  96886. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  96887. * @param mesh The mesh to remove
  96888. */
  96889. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  96890. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  96891. if (index !== -1) {
  96892. this._excludedMeshes.splice(index, 1);
  96893. }
  96894. };
  96895. /**
  96896. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  96897. * @param mesh The mesh to include in the glow layer
  96898. */
  96899. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  96900. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  96901. this._includedOnlyMeshes.push(mesh.uniqueId);
  96902. }
  96903. };
  96904. /**
  96905. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  96906. * @param mesh The mesh to remove
  96907. */
  96908. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  96909. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  96910. if (index !== -1) {
  96911. this._includedOnlyMeshes.splice(index, 1);
  96912. }
  96913. };
  96914. /**
  96915. * Determine if a given mesh will be used in the glow layer
  96916. * @param mesh The mesh to test
  96917. * @returns true if the mesh will be highlighted by the current glow layer
  96918. */
  96919. GlowLayer.prototype.hasMesh = function (mesh) {
  96920. // Included Mesh
  96921. if (this._includedOnlyMeshes.length) {
  96922. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  96923. }
  96924. ;
  96925. // Excluded Mesh
  96926. if (this._excludedMeshes.length) {
  96927. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  96928. }
  96929. ;
  96930. return true;
  96931. };
  96932. /**
  96933. * Free any resources and references associated to a mesh.
  96934. * Internal use
  96935. * @param mesh The mesh to free.
  96936. */
  96937. GlowLayer.prototype._disposeMesh = function (mesh) {
  96938. this.removeIncludedOnlyMesh(mesh);
  96939. this.removeExcludedMesh(mesh);
  96940. };
  96941. /**
  96942. * Gets the class name of the effect layer
  96943. * @returns the string with the class name of the effect layer
  96944. */
  96945. GlowLayer.prototype.getClassName = function () {
  96946. return "GlowLayer";
  96947. };
  96948. /**
  96949. * Serializes this glow layer
  96950. * @returns a serialized glow layer object
  96951. */
  96952. GlowLayer.prototype.serialize = function () {
  96953. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96954. serializationObject.customType = "BABYLON.GlowLayer";
  96955. var index;
  96956. // Included meshes
  96957. serializationObject.includedMeshes = [];
  96958. if (this._includedOnlyMeshes.length) {
  96959. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  96960. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  96961. if (mesh) {
  96962. serializationObject.includedMeshes.push(mesh.id);
  96963. }
  96964. }
  96965. }
  96966. // Excluded meshes
  96967. serializationObject.excludedMeshes = [];
  96968. if (this._excludedMeshes.length) {
  96969. for (index = 0; index < this._excludedMeshes.length; index++) {
  96970. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  96971. if (mesh) {
  96972. serializationObject.excludedMeshes.push(mesh.id);
  96973. }
  96974. }
  96975. }
  96976. return serializationObject;
  96977. };
  96978. /**
  96979. * Creates a Glow Layer from parsed glow layer data
  96980. * @param parsedGlowLayer defines glow layer data
  96981. * @param scene defines the current scene
  96982. * @param rootUrl defines the root URL containing the glow layer information
  96983. * @returns a parsed Glow Layer
  96984. */
  96985. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  96986. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  96987. var index;
  96988. // Excluded meshes
  96989. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  96990. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  96991. if (mesh) {
  96992. gl.addExcludedMesh(mesh);
  96993. }
  96994. }
  96995. // Included meshes
  96996. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  96997. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  96998. if (mesh) {
  96999. gl.addIncludedOnlyMesh(mesh);
  97000. }
  97001. }
  97002. return gl;
  97003. };
  97004. /**
  97005. * Effect Name of the layer.
  97006. */
  97007. GlowLayer.EffectName = "GlowLayer";
  97008. /**
  97009. * The default blur kernel size used for the glow.
  97010. */
  97011. GlowLayer.DefaultBlurKernelSize = 32;
  97012. /**
  97013. * The default texture size ratio used for the glow.
  97014. */
  97015. GlowLayer.DefaultTextureRatio = 0.5;
  97016. __decorate([
  97017. BABYLON.serialize()
  97018. ], GlowLayer.prototype, "blurKernelSize", null);
  97019. __decorate([
  97020. BABYLON.serialize()
  97021. ], GlowLayer.prototype, "intensity", null);
  97022. __decorate([
  97023. BABYLON.serialize("options")
  97024. ], GlowLayer.prototype, "_options", void 0);
  97025. return GlowLayer;
  97026. }(BABYLON.EffectLayer));
  97027. BABYLON.GlowLayer = GlowLayer;
  97028. })(BABYLON || (BABYLON = {}));
  97029. //# sourceMappingURL=babylon.glowLayer.js.map
  97030. var BABYLON;
  97031. (function (BABYLON) {
  97032. /**
  97033. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97034. */
  97035. var AssetTaskState;
  97036. (function (AssetTaskState) {
  97037. /**
  97038. * Initialization
  97039. */
  97040. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97041. /**
  97042. * Running
  97043. */
  97044. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97045. /**
  97046. * Done
  97047. */
  97048. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97049. /**
  97050. * Error
  97051. */
  97052. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97053. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97054. /**
  97055. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97056. */
  97057. var AbstractAssetTask = /** @class */ (function () {
  97058. /**
  97059. * Creates a new {BABYLON.AssetsManager}
  97060. * @param name defines the name of the task
  97061. */
  97062. function AbstractAssetTask(
  97063. /**
  97064. * Task name
  97065. */ name) {
  97066. this.name = name;
  97067. this._isCompleted = false;
  97068. this._taskState = AssetTaskState.INIT;
  97069. }
  97070. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97071. /**
  97072. * Get if the task is completed
  97073. */
  97074. get: function () {
  97075. return this._isCompleted;
  97076. },
  97077. enumerable: true,
  97078. configurable: true
  97079. });
  97080. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97081. /**
  97082. * Gets the current state of the task
  97083. */
  97084. get: function () {
  97085. return this._taskState;
  97086. },
  97087. enumerable: true,
  97088. configurable: true
  97089. });
  97090. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97091. /**
  97092. * Gets the current error object (if task is in error)
  97093. */
  97094. get: function () {
  97095. return this._errorObject;
  97096. },
  97097. enumerable: true,
  97098. configurable: true
  97099. });
  97100. /**
  97101. * Internal only
  97102. * @hidden
  97103. */
  97104. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97105. if (this._errorObject) {
  97106. return;
  97107. }
  97108. this._errorObject = {
  97109. message: message,
  97110. exception: exception
  97111. };
  97112. };
  97113. /**
  97114. * Execute the current task
  97115. * @param scene defines the scene where you want your assets to be loaded
  97116. * @param onSuccess is a callback called when the task is successfully executed
  97117. * @param onError is a callback called if an error occurs
  97118. */
  97119. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97120. var _this = this;
  97121. this._taskState = AssetTaskState.RUNNING;
  97122. this.runTask(scene, function () {
  97123. _this.onDoneCallback(onSuccess, onError);
  97124. }, function (msg, exception) {
  97125. _this.onErrorCallback(onError, msg, exception);
  97126. });
  97127. };
  97128. /**
  97129. * Execute the current task
  97130. * @param scene defines the scene where you want your assets to be loaded
  97131. * @param onSuccess is a callback called when the task is successfully executed
  97132. * @param onError is a callback called if an error occurs
  97133. */
  97134. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97135. throw new Error("runTask is not implemented");
  97136. };
  97137. /**
  97138. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  97139. * This can be used with failed tasks that have the reason for failure fixed.
  97140. */
  97141. AbstractAssetTask.prototype.reset = function () {
  97142. this._taskState = AssetTaskState.INIT;
  97143. };
  97144. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  97145. this._taskState = AssetTaskState.ERROR;
  97146. this._errorObject = {
  97147. message: message,
  97148. exception: exception
  97149. };
  97150. if (this.onError) {
  97151. this.onError(this, message, exception);
  97152. }
  97153. onError();
  97154. };
  97155. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  97156. try {
  97157. this._taskState = AssetTaskState.DONE;
  97158. this._isCompleted = true;
  97159. if (this.onSuccess) {
  97160. this.onSuccess(this);
  97161. }
  97162. onSuccess();
  97163. }
  97164. catch (e) {
  97165. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  97166. }
  97167. };
  97168. return AbstractAssetTask;
  97169. }());
  97170. BABYLON.AbstractAssetTask = AbstractAssetTask;
  97171. /**
  97172. * Class used to share progress information about assets loading
  97173. */
  97174. var AssetsProgressEvent = /** @class */ (function () {
  97175. /**
  97176. * Creates a {BABYLON.AssetsProgressEvent}
  97177. * @param remainingCount defines the number of remaining tasks to process
  97178. * @param totalCount defines the total number of tasks
  97179. * @param task defines the task that was just processed
  97180. */
  97181. function AssetsProgressEvent(remainingCount, totalCount, task) {
  97182. this.remainingCount = remainingCount;
  97183. this.totalCount = totalCount;
  97184. this.task = task;
  97185. }
  97186. return AssetsProgressEvent;
  97187. }());
  97188. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  97189. /**
  97190. * Define a task used by {BABYLON.AssetsManager} to load meshes
  97191. */
  97192. var MeshAssetTask = /** @class */ (function (_super) {
  97193. __extends(MeshAssetTask, _super);
  97194. /**
  97195. * Creates a new {BABYLON.MeshAssetTask}
  97196. * @param name defines the name of the task
  97197. * @param meshesNames defines the list of mesh's names you want to load
  97198. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  97199. * @param sceneFilename defines the filename of the scene to load from
  97200. */
  97201. function MeshAssetTask(
  97202. /**
  97203. * Defines the name of the task
  97204. */
  97205. name,
  97206. /**
  97207. * Defines the list of mesh's names you want to load
  97208. */
  97209. meshesNames,
  97210. /**
  97211. * Defines the root url to use as a base to load your meshes and associated resources
  97212. */
  97213. rootUrl,
  97214. /**
  97215. * Defines the filename of the scene to load from
  97216. */
  97217. sceneFilename) {
  97218. var _this = _super.call(this, name) || this;
  97219. _this.name = name;
  97220. _this.meshesNames = meshesNames;
  97221. _this.rootUrl = rootUrl;
  97222. _this.sceneFilename = sceneFilename;
  97223. return _this;
  97224. }
  97225. /**
  97226. * Execute the current task
  97227. * @param scene defines the scene where you want your assets to be loaded
  97228. * @param onSuccess is a callback called when the task is successfully executed
  97229. * @param onError is a callback called if an error occurs
  97230. */
  97231. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97232. var _this = this;
  97233. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  97234. _this.loadedMeshes = meshes;
  97235. _this.loadedParticleSystems = particleSystems;
  97236. _this.loadedSkeletons = skeletons;
  97237. onSuccess();
  97238. }, null, function (scene, message, exception) {
  97239. onError(message, exception);
  97240. });
  97241. };
  97242. return MeshAssetTask;
  97243. }(AbstractAssetTask));
  97244. BABYLON.MeshAssetTask = MeshAssetTask;
  97245. /**
  97246. * Define a task used by {BABYLON.AssetsManager} to load text content
  97247. */
  97248. var TextFileAssetTask = /** @class */ (function (_super) {
  97249. __extends(TextFileAssetTask, _super);
  97250. /**
  97251. * Creates a new TextFileAssetTask object
  97252. * @param name defines the name of the task
  97253. * @param url defines the location of the file to load
  97254. */
  97255. function TextFileAssetTask(
  97256. /**
  97257. * Defines the name of the task
  97258. */
  97259. name,
  97260. /**
  97261. * Defines the location of the file to load
  97262. */
  97263. url) {
  97264. var _this = _super.call(this, name) || this;
  97265. _this.name = name;
  97266. _this.url = url;
  97267. return _this;
  97268. }
  97269. /**
  97270. * Execute the current task
  97271. * @param scene defines the scene where you want your assets to be loaded
  97272. * @param onSuccess is a callback called when the task is successfully executed
  97273. * @param onError is a callback called if an error occurs
  97274. */
  97275. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97276. var _this = this;
  97277. scene._loadFile(this.url, function (data) {
  97278. _this.text = data;
  97279. onSuccess();
  97280. }, undefined, false, false, function (request, exception) {
  97281. if (request) {
  97282. onError(request.status + " " + request.statusText, exception);
  97283. }
  97284. });
  97285. };
  97286. return TextFileAssetTask;
  97287. }(AbstractAssetTask));
  97288. BABYLON.TextFileAssetTask = TextFileAssetTask;
  97289. /**
  97290. * Define a task used by {BABYLON.AssetsManager} to load binary data
  97291. */
  97292. var BinaryFileAssetTask = /** @class */ (function (_super) {
  97293. __extends(BinaryFileAssetTask, _super);
  97294. /**
  97295. * Creates a new BinaryFileAssetTask object
  97296. * @param name defines the name of the new task
  97297. * @param url defines the location of the file to load
  97298. */
  97299. function BinaryFileAssetTask(
  97300. /**
  97301. * Defines the name of the task
  97302. */
  97303. name,
  97304. /**
  97305. * Defines the location of the file to load
  97306. */
  97307. url) {
  97308. var _this = _super.call(this, name) || this;
  97309. _this.name = name;
  97310. _this.url = url;
  97311. return _this;
  97312. }
  97313. /**
  97314. * Execute the current task
  97315. * @param scene defines the scene where you want your assets to be loaded
  97316. * @param onSuccess is a callback called when the task is successfully executed
  97317. * @param onError is a callback called if an error occurs
  97318. */
  97319. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97320. var _this = this;
  97321. scene._loadFile(this.url, function (data) {
  97322. _this.data = data;
  97323. onSuccess();
  97324. }, undefined, true, true, function (request, exception) {
  97325. if (request) {
  97326. onError(request.status + " " + request.statusText, exception);
  97327. }
  97328. });
  97329. };
  97330. return BinaryFileAssetTask;
  97331. }(AbstractAssetTask));
  97332. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  97333. /**
  97334. * Define a task used by {BABYLON.AssetsManager} to load images
  97335. */
  97336. var ImageAssetTask = /** @class */ (function (_super) {
  97337. __extends(ImageAssetTask, _super);
  97338. /**
  97339. * Creates a new ImageAssetTask
  97340. * @param name defines the name of the task
  97341. * @param url defines the location of the image to load
  97342. */
  97343. function ImageAssetTask(
  97344. /**
  97345. * Defines the name of the task
  97346. */
  97347. name,
  97348. /**
  97349. * Defines the location of the image to load
  97350. */
  97351. url) {
  97352. var _this = _super.call(this, name) || this;
  97353. _this.name = name;
  97354. _this.url = url;
  97355. return _this;
  97356. }
  97357. /**
  97358. * Execute the current task
  97359. * @param scene defines the scene where you want your assets to be loaded
  97360. * @param onSuccess is a callback called when the task is successfully executed
  97361. * @param onError is a callback called if an error occurs
  97362. */
  97363. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97364. var _this = this;
  97365. var img = new Image();
  97366. BABYLON.Tools.SetCorsBehavior(this.url, img);
  97367. img.onload = function () {
  97368. _this.image = img;
  97369. onSuccess();
  97370. };
  97371. img.onerror = function (err) {
  97372. onError("Error loading image", err);
  97373. };
  97374. img.src = this.url;
  97375. };
  97376. return ImageAssetTask;
  97377. }(AbstractAssetTask));
  97378. BABYLON.ImageAssetTask = ImageAssetTask;
  97379. /**
  97380. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  97381. */
  97382. var TextureAssetTask = /** @class */ (function (_super) {
  97383. __extends(TextureAssetTask, _super);
  97384. /**
  97385. * Creates a new TextureAssetTask object
  97386. * @param name defines the name of the task
  97387. * @param url defines the location of the file to load
  97388. * @param noMipmap defines if mipmap should not be generated (default is false)
  97389. * @param invertY defines if texture must be inverted on Y axis (default is false)
  97390. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97391. */
  97392. function TextureAssetTask(
  97393. /**
  97394. * Defines the name of the task
  97395. */
  97396. name,
  97397. /**
  97398. * Defines the location of the file to load
  97399. */
  97400. url,
  97401. /**
  97402. * Defines if mipmap should not be generated (default is false)
  97403. */
  97404. noMipmap,
  97405. /**
  97406. * Defines if texture must be inverted on Y axis (default is false)
  97407. */
  97408. invertY,
  97409. /**
  97410. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97411. */
  97412. samplingMode) {
  97413. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97414. var _this = _super.call(this, name) || this;
  97415. _this.name = name;
  97416. _this.url = url;
  97417. _this.noMipmap = noMipmap;
  97418. _this.invertY = invertY;
  97419. _this.samplingMode = samplingMode;
  97420. return _this;
  97421. }
  97422. /**
  97423. * Execute the current task
  97424. * @param scene defines the scene where you want your assets to be loaded
  97425. * @param onSuccess is a callback called when the task is successfully executed
  97426. * @param onError is a callback called if an error occurs
  97427. */
  97428. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97429. var onload = function () {
  97430. onSuccess();
  97431. };
  97432. var onerror = function (message, exception) {
  97433. onError(message, exception);
  97434. };
  97435. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  97436. };
  97437. return TextureAssetTask;
  97438. }(AbstractAssetTask));
  97439. BABYLON.TextureAssetTask = TextureAssetTask;
  97440. /**
  97441. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  97442. */
  97443. var CubeTextureAssetTask = /** @class */ (function (_super) {
  97444. __extends(CubeTextureAssetTask, _super);
  97445. /**
  97446. * Creates a new CubeTextureAssetTask
  97447. * @param name defines the name of the task
  97448. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97449. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97450. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97451. * @param files defines the explicit list of files (undefined by default)
  97452. */
  97453. function CubeTextureAssetTask(
  97454. /**
  97455. * Defines the name of the task
  97456. */
  97457. name,
  97458. /**
  97459. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97460. */
  97461. url,
  97462. /**
  97463. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97464. */
  97465. extensions,
  97466. /**
  97467. * Defines if mipmaps should not be generated (default is false)
  97468. */
  97469. noMipmap,
  97470. /**
  97471. * Defines the explicit list of files (undefined by default)
  97472. */
  97473. files) {
  97474. var _this = _super.call(this, name) || this;
  97475. _this.name = name;
  97476. _this.url = url;
  97477. _this.extensions = extensions;
  97478. _this.noMipmap = noMipmap;
  97479. _this.files = files;
  97480. return _this;
  97481. }
  97482. /**
  97483. * Execute the current task
  97484. * @param scene defines the scene where you want your assets to be loaded
  97485. * @param onSuccess is a callback called when the task is successfully executed
  97486. * @param onError is a callback called if an error occurs
  97487. */
  97488. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97489. var onload = function () {
  97490. onSuccess();
  97491. };
  97492. var onerror = function (message, exception) {
  97493. onError(message, exception);
  97494. };
  97495. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  97496. };
  97497. return CubeTextureAssetTask;
  97498. }(AbstractAssetTask));
  97499. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  97500. /**
  97501. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  97502. */
  97503. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  97504. __extends(HDRCubeTextureAssetTask, _super);
  97505. /**
  97506. * Creates a new HDRCubeTextureAssetTask object
  97507. * @param name defines the name of the task
  97508. * @param url defines the location of the file to load
  97509. * @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.
  97510. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97511. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97512. * @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)
  97513. * @param reserved Internal use only
  97514. */
  97515. function HDRCubeTextureAssetTask(
  97516. /**
  97517. * Defines the name of the task
  97518. */
  97519. name,
  97520. /**
  97521. * Defines the location of the file to load
  97522. */
  97523. url,
  97524. /**
  97525. * Defines the desired size (the more it increases the longer the generation will be)
  97526. */
  97527. size,
  97528. /**
  97529. * Defines if mipmaps should not be generated (default is false)
  97530. */
  97531. noMipmap,
  97532. /**
  97533. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97534. */
  97535. generateHarmonics,
  97536. /**
  97537. * 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)
  97538. */
  97539. gammaSpace,
  97540. /**
  97541. * Internal Use Only
  97542. */
  97543. reserved) {
  97544. if (noMipmap === void 0) { noMipmap = false; }
  97545. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97546. if (gammaSpace === void 0) { gammaSpace = false; }
  97547. if (reserved === void 0) { reserved = false; }
  97548. var _this = _super.call(this, name) || this;
  97549. _this.name = name;
  97550. _this.url = url;
  97551. _this.size = size;
  97552. _this.noMipmap = noMipmap;
  97553. _this.generateHarmonics = generateHarmonics;
  97554. _this.gammaSpace = gammaSpace;
  97555. _this.reserved = reserved;
  97556. return _this;
  97557. }
  97558. /**
  97559. * Execute the current task
  97560. * @param scene defines the scene where you want your assets to be loaded
  97561. * @param onSuccess is a callback called when the task is successfully executed
  97562. * @param onError is a callback called if an error occurs
  97563. */
  97564. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97565. var onload = function () {
  97566. onSuccess();
  97567. };
  97568. var onerror = function (message, exception) {
  97569. onError(message, exception);
  97570. };
  97571. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  97572. };
  97573. return HDRCubeTextureAssetTask;
  97574. }(AbstractAssetTask));
  97575. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  97576. /**
  97577. * This class can be used to easily import assets into a scene
  97578. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  97579. */
  97580. var AssetsManager = /** @class */ (function () {
  97581. /**
  97582. * Creates a new AssetsManager
  97583. * @param scene defines the scene to work on
  97584. */
  97585. function AssetsManager(scene) {
  97586. this._isLoading = false;
  97587. this._tasks = new Array();
  97588. this._waitingTasksCount = 0;
  97589. this._totalTasksCount = 0;
  97590. /**
  97591. * Observable called when all tasks are processed
  97592. */
  97593. this.onTaskSuccessObservable = new BABYLON.Observable();
  97594. /**
  97595. * Observable called when a task had an error
  97596. */
  97597. this.onTaskErrorObservable = new BABYLON.Observable();
  97598. /**
  97599. * Observable called when a task is successful
  97600. */
  97601. this.onTasksDoneObservable = new BABYLON.Observable();
  97602. /**
  97603. * Observable called when a task is done (whatever the result is)
  97604. */
  97605. this.onProgressObservable = new BABYLON.Observable();
  97606. /**
  97607. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  97608. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  97609. */
  97610. this.useDefaultLoadingScreen = true;
  97611. this._scene = scene;
  97612. }
  97613. /**
  97614. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97615. * @param taskName defines the name of the new task
  97616. * @param meshesNames defines the name of meshes to load
  97617. * @param rootUrl defines the root url to use to locate files
  97618. * @param sceneFilename defines the filename of the scene file
  97619. * @returns a new {BABYLON.MeshAssetTask} object
  97620. */
  97621. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97622. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97623. this._tasks.push(task);
  97624. return task;
  97625. };
  97626. /**
  97627. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97628. * @param taskName defines the name of the new task
  97629. * @param url defines the url of the file to load
  97630. * @returns a new {BABYLON.TextFileAssetTask} object
  97631. */
  97632. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97633. var task = new TextFileAssetTask(taskName, url);
  97634. this._tasks.push(task);
  97635. return task;
  97636. };
  97637. /**
  97638. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97639. * @param taskName defines the name of the new task
  97640. * @param url defines the url of the file to load
  97641. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97642. */
  97643. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97644. var task = new BinaryFileAssetTask(taskName, url);
  97645. this._tasks.push(task);
  97646. return task;
  97647. };
  97648. /**
  97649. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97650. * @param taskName defines the name of the new task
  97651. * @param url defines the url of the file to load
  97652. * @returns a new {BABYLON.ImageAssetTask} object
  97653. */
  97654. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97655. var task = new ImageAssetTask(taskName, url);
  97656. this._tasks.push(task);
  97657. return task;
  97658. };
  97659. /**
  97660. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  97661. * @param taskName defines the name of the new task
  97662. * @param url defines the url of the file to load
  97663. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97664. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  97665. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  97666. * @returns a new {BABYLON.TextureAssetTask} object
  97667. */
  97668. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  97669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97670. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  97671. this._tasks.push(task);
  97672. return task;
  97673. };
  97674. /**
  97675. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  97676. * @param taskName defines the name of the new task
  97677. * @param url defines the url of the file to load
  97678. * @param extensions defines the extension to use to load the cube map (can be null)
  97679. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97680. * @param files defines the list of files to load (can be null)
  97681. * @returns a new {BABYLON.CubeTextureAssetTask} object
  97682. */
  97683. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  97684. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  97685. this._tasks.push(task);
  97686. return task;
  97687. };
  97688. /**
  97689. *
  97690. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  97691. * @param taskName defines the name of the new task
  97692. * @param url defines the url of the file to load
  97693. * @param size defines the size you want for the cubemap (can be null)
  97694. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97695. * @param generateHarmonics defines if you want to automatically generate (true by default)
  97696. * @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)
  97697. * @param reserved Internal use only
  97698. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  97699. */
  97700. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  97701. if (noMipmap === void 0) { noMipmap = false; }
  97702. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97703. if (gammaSpace === void 0) { gammaSpace = false; }
  97704. if (reserved === void 0) { reserved = false; }
  97705. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  97706. this._tasks.push(task);
  97707. return task;
  97708. };
  97709. /**
  97710. * Remove a task from the assets manager.
  97711. * @param task the task to remove
  97712. */
  97713. AssetsManager.prototype.removeTask = function (task) {
  97714. var index = this._tasks.indexOf(task);
  97715. if (index > -1) {
  97716. this._tasks.splice(index, 1);
  97717. }
  97718. };
  97719. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  97720. this._waitingTasksCount--;
  97721. try {
  97722. if (this.onProgress) {
  97723. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  97724. }
  97725. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  97726. }
  97727. catch (e) {
  97728. BABYLON.Tools.Error("Error running progress callbacks.");
  97729. console.log(e);
  97730. }
  97731. if (this._waitingTasksCount === 0) {
  97732. try {
  97733. if (this.onFinish) {
  97734. this.onFinish(this._tasks);
  97735. }
  97736. // Let's remove successfull tasks
  97737. var currentTasks = this._tasks.slice();
  97738. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  97739. var task = currentTasks_1[_i];
  97740. if (task.taskState === AssetTaskState.DONE) {
  97741. var index = this._tasks.indexOf(task);
  97742. if (index > -1) {
  97743. this._tasks.splice(index, 1);
  97744. }
  97745. }
  97746. }
  97747. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97748. }
  97749. catch (e) {
  97750. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  97751. console.log(e);
  97752. }
  97753. this._isLoading = false;
  97754. this._scene.getEngine().hideLoadingUI();
  97755. }
  97756. };
  97757. AssetsManager.prototype._runTask = function (task) {
  97758. var _this = this;
  97759. var done = function () {
  97760. try {
  97761. if (_this.onTaskSuccess) {
  97762. _this.onTaskSuccess(task);
  97763. }
  97764. _this.onTaskSuccessObservable.notifyObservers(task);
  97765. _this._decreaseWaitingTasksCount(task);
  97766. }
  97767. catch (e) {
  97768. error("Error executing task success callbacks", e);
  97769. }
  97770. };
  97771. var error = function (message, exception) {
  97772. task._setErrorObject(message, exception);
  97773. if (_this.onTaskError) {
  97774. _this.onTaskError(task);
  97775. }
  97776. _this.onTaskErrorObservable.notifyObservers(task);
  97777. _this._decreaseWaitingTasksCount(task);
  97778. };
  97779. task.run(this._scene, done, error);
  97780. };
  97781. /**
  97782. * Reset the {BABYLON.AssetsManager} and remove all tasks
  97783. * @return the current instance of the {BABYLON.AssetsManager}
  97784. */
  97785. AssetsManager.prototype.reset = function () {
  97786. this._isLoading = false;
  97787. this._tasks = new Array();
  97788. return this;
  97789. };
  97790. /**
  97791. * Start the loading process
  97792. * @return the current instance of the {BABYLON.AssetsManager}
  97793. */
  97794. AssetsManager.prototype.load = function () {
  97795. if (this._isLoading) {
  97796. return this;
  97797. }
  97798. this._isLoading = true;
  97799. this._waitingTasksCount = this._tasks.length;
  97800. this._totalTasksCount = this._tasks.length;
  97801. if (this._waitingTasksCount === 0) {
  97802. this._isLoading = false;
  97803. if (this.onFinish) {
  97804. this.onFinish(this._tasks);
  97805. }
  97806. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97807. return this;
  97808. }
  97809. if (this.useDefaultLoadingScreen) {
  97810. this._scene.getEngine().displayLoadingUI();
  97811. }
  97812. for (var index = 0; index < this._tasks.length; index++) {
  97813. var task = this._tasks[index];
  97814. if (task.taskState === AssetTaskState.INIT) {
  97815. this._runTask(task);
  97816. }
  97817. }
  97818. return this;
  97819. };
  97820. return AssetsManager;
  97821. }());
  97822. BABYLON.AssetsManager = AssetsManager;
  97823. })(BABYLON || (BABYLON = {}));
  97824. //# sourceMappingURL=babylon.assetsManager.js.map
  97825. var BABYLON;
  97826. (function (BABYLON) {
  97827. var serializedGeometries = [];
  97828. var serializeGeometry = function (geometry, serializationGeometries) {
  97829. if (serializedGeometries[geometry.id]) {
  97830. return;
  97831. }
  97832. if (geometry.doNotSerialize) {
  97833. return;
  97834. }
  97835. if (geometry instanceof BABYLON.BoxGeometry) {
  97836. serializationGeometries.boxes.push(geometry.serialize());
  97837. }
  97838. else if (geometry instanceof BABYLON.SphereGeometry) {
  97839. serializationGeometries.spheres.push(geometry.serialize());
  97840. }
  97841. else if (geometry instanceof BABYLON.CylinderGeometry) {
  97842. serializationGeometries.cylinders.push(geometry.serialize());
  97843. }
  97844. else if (geometry instanceof BABYLON.TorusGeometry) {
  97845. serializationGeometries.toruses.push(geometry.serialize());
  97846. }
  97847. else if (geometry instanceof BABYLON.GroundGeometry) {
  97848. serializationGeometries.grounds.push(geometry.serialize());
  97849. }
  97850. else if (geometry instanceof BABYLON.Plane) {
  97851. serializationGeometries.planes.push(geometry.serialize());
  97852. }
  97853. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  97854. serializationGeometries.torusKnots.push(geometry.serialize());
  97855. }
  97856. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  97857. throw new Error("Unknown primitive type");
  97858. }
  97859. else {
  97860. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  97861. }
  97862. serializedGeometries[geometry.id] = true;
  97863. };
  97864. var serializeMesh = function (mesh, serializationScene) {
  97865. var serializationObject = {};
  97866. // Geometry
  97867. var geometry = mesh._geometry;
  97868. if (geometry) {
  97869. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  97870. // 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
  97871. serializeGeometry(geometry, serializationScene.geometries);
  97872. }
  97873. }
  97874. // Custom
  97875. if (mesh.serialize) {
  97876. mesh.serialize(serializationObject);
  97877. }
  97878. return serializationObject;
  97879. };
  97880. var finalizeSingleMesh = function (mesh, serializationObject) {
  97881. //only works if the mesh is already loaded
  97882. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  97883. //serialize material
  97884. if (mesh.material) {
  97885. if (mesh.material instanceof BABYLON.MultiMaterial) {
  97886. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  97887. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97888. serializationObject.multiMaterials.push(mesh.material.serialize());
  97889. }
  97890. }
  97891. else {
  97892. serializationObject.materials = serializationObject.materials || [];
  97893. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  97894. serializationObject.materials.push(mesh.material.serialize());
  97895. }
  97896. }
  97897. }
  97898. //serialize geometry
  97899. var geometry = mesh._geometry;
  97900. if (geometry) {
  97901. if (!serializationObject.geometries) {
  97902. serializationObject.geometries = {};
  97903. serializationObject.geometries.boxes = [];
  97904. serializationObject.geometries.spheres = [];
  97905. serializationObject.geometries.cylinders = [];
  97906. serializationObject.geometries.toruses = [];
  97907. serializationObject.geometries.grounds = [];
  97908. serializationObject.geometries.planes = [];
  97909. serializationObject.geometries.torusKnots = [];
  97910. serializationObject.geometries.vertexData = [];
  97911. }
  97912. serializeGeometry(geometry, serializationObject.geometries);
  97913. }
  97914. // Skeletons
  97915. if (mesh.skeleton) {
  97916. serializationObject.skeletons = serializationObject.skeletons || [];
  97917. serializationObject.skeletons.push(mesh.skeleton.serialize());
  97918. }
  97919. //serialize the actual mesh
  97920. serializationObject.meshes = serializationObject.meshes || [];
  97921. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  97922. }
  97923. };
  97924. var SceneSerializer = /** @class */ (function () {
  97925. function SceneSerializer() {
  97926. }
  97927. SceneSerializer.ClearCache = function () {
  97928. serializedGeometries = [];
  97929. };
  97930. SceneSerializer.Serialize = function (scene) {
  97931. var serializationObject = {};
  97932. SceneSerializer.ClearCache();
  97933. // Scene
  97934. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  97935. serializationObject.autoClear = scene.autoClear;
  97936. serializationObject.clearColor = scene.clearColor.asArray();
  97937. serializationObject.ambientColor = scene.ambientColor.asArray();
  97938. serializationObject.gravity = scene.gravity.asArray();
  97939. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  97940. serializationObject.workerCollisions = scene.workerCollisions;
  97941. // Fog
  97942. if (scene.fogMode && scene.fogMode !== 0) {
  97943. serializationObject.fogMode = scene.fogMode;
  97944. serializationObject.fogColor = scene.fogColor.asArray();
  97945. serializationObject.fogStart = scene.fogStart;
  97946. serializationObject.fogEnd = scene.fogEnd;
  97947. serializationObject.fogDensity = scene.fogDensity;
  97948. }
  97949. //Physics
  97950. if (scene.isPhysicsEnabled()) {
  97951. var physicEngine = scene.getPhysicsEngine();
  97952. if (physicEngine) {
  97953. serializationObject.physicsEnabled = true;
  97954. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  97955. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  97956. }
  97957. }
  97958. // Metadata
  97959. if (scene.metadata) {
  97960. serializationObject.metadata = scene.metadata;
  97961. }
  97962. // Morph targets
  97963. serializationObject.morphTargetManagers = [];
  97964. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  97965. var abstractMesh = _a[_i];
  97966. var manager = abstractMesh.morphTargetManager;
  97967. if (manager) {
  97968. serializationObject.morphTargetManagers.push(manager.serialize());
  97969. }
  97970. }
  97971. // Lights
  97972. serializationObject.lights = [];
  97973. var index;
  97974. var light;
  97975. for (index = 0; index < scene.lights.length; index++) {
  97976. light = scene.lights[index];
  97977. if (!light.doNotSerialize) {
  97978. serializationObject.lights.push(light.serialize());
  97979. }
  97980. }
  97981. // Cameras
  97982. serializationObject.cameras = [];
  97983. for (index = 0; index < scene.cameras.length; index++) {
  97984. var camera = scene.cameras[index];
  97985. if (!camera.doNotSerialize) {
  97986. serializationObject.cameras.push(camera.serialize());
  97987. }
  97988. }
  97989. if (scene.activeCamera) {
  97990. serializationObject.activeCameraID = scene.activeCamera.id;
  97991. }
  97992. // Animations
  97993. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  97994. // Materials
  97995. serializationObject.materials = [];
  97996. serializationObject.multiMaterials = [];
  97997. var material;
  97998. for (index = 0; index < scene.materials.length; index++) {
  97999. material = scene.materials[index];
  98000. if (!material.doNotSerialize) {
  98001. serializationObject.materials.push(material.serialize());
  98002. }
  98003. }
  98004. // MultiMaterials
  98005. serializationObject.multiMaterials = [];
  98006. for (index = 0; index < scene.multiMaterials.length; index++) {
  98007. var multiMaterial = scene.multiMaterials[index];
  98008. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98009. }
  98010. // Environment texture
  98011. if (scene.environmentTexture) {
  98012. serializationObject.environmentTexture = scene.environmentTexture.name;
  98013. }
  98014. // Skeletons
  98015. serializationObject.skeletons = [];
  98016. for (index = 0; index < scene.skeletons.length; index++) {
  98017. var skeleton = scene.skeletons[index];
  98018. if (!skeleton.doNotSerialize) {
  98019. serializationObject.skeletons.push(skeleton.serialize());
  98020. }
  98021. }
  98022. // Transform nodes
  98023. serializationObject.transformNodes = [];
  98024. for (index = 0; index < scene.transformNodes.length; index++) {
  98025. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98026. }
  98027. // Geometries
  98028. serializationObject.geometries = {};
  98029. serializationObject.geometries.boxes = [];
  98030. serializationObject.geometries.spheres = [];
  98031. serializationObject.geometries.cylinders = [];
  98032. serializationObject.geometries.toruses = [];
  98033. serializationObject.geometries.grounds = [];
  98034. serializationObject.geometries.planes = [];
  98035. serializationObject.geometries.torusKnots = [];
  98036. serializationObject.geometries.vertexData = [];
  98037. serializedGeometries = [];
  98038. var geometries = scene.getGeometries();
  98039. for (index = 0; index < geometries.length; index++) {
  98040. var geometry = geometries[index];
  98041. if (geometry.isReady()) {
  98042. serializeGeometry(geometry, serializationObject.geometries);
  98043. }
  98044. }
  98045. // Meshes
  98046. serializationObject.meshes = [];
  98047. for (index = 0; index < scene.meshes.length; index++) {
  98048. var abstractMesh = scene.meshes[index];
  98049. if (abstractMesh instanceof BABYLON.Mesh) {
  98050. var mesh = abstractMesh;
  98051. if (!mesh.doNotSerialize) {
  98052. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98053. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98054. }
  98055. }
  98056. }
  98057. }
  98058. // Particles Systems
  98059. serializationObject.particleSystems = [];
  98060. for (index = 0; index < scene.particleSystems.length; index++) {
  98061. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98062. }
  98063. // Lens flares
  98064. serializationObject.lensFlareSystems = [];
  98065. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  98066. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  98067. }
  98068. // Shadows
  98069. serializationObject.shadowGenerators = [];
  98070. for (index = 0; index < scene.lights.length; index++) {
  98071. light = scene.lights[index];
  98072. var shadowGenerator = light.getShadowGenerator();
  98073. if (shadowGenerator) {
  98074. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98075. }
  98076. }
  98077. // Action Manager
  98078. if (scene.actionManager) {
  98079. serializationObject.actions = scene.actionManager.serialize("scene");
  98080. }
  98081. // Audio
  98082. serializationObject.sounds = [];
  98083. for (index = 0; index < scene.soundTracks.length; index++) {
  98084. var soundtrack = scene.soundTracks[index];
  98085. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98086. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98087. }
  98088. }
  98089. // Effect layers
  98090. serializationObject.effectLayers = [];
  98091. for (index = 0; index < scene.effectLayers.length; index++) {
  98092. var layer = scene.effectLayers[index];
  98093. if (layer.serialize) {
  98094. serializationObject.effectLayers.push(layer.serialize());
  98095. }
  98096. }
  98097. return serializationObject;
  98098. };
  98099. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98100. if (withParents === void 0) { withParents = false; }
  98101. if (withChildren === void 0) { withChildren = false; }
  98102. var serializationObject = {};
  98103. SceneSerializer.ClearCache();
  98104. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98105. if (withParents || withChildren) {
  98106. //deliberate for loop! not for each, appended should be processed as well.
  98107. for (var i = 0; i < toSerialize.length; ++i) {
  98108. if (withChildren) {
  98109. toSerialize[i].getDescendants().forEach(function (node) {
  98110. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98111. toSerialize.push(node);
  98112. }
  98113. });
  98114. }
  98115. //make sure the array doesn't contain the object already
  98116. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98117. toSerialize.push(toSerialize[i].parent);
  98118. }
  98119. }
  98120. }
  98121. toSerialize.forEach(function (mesh) {
  98122. finalizeSingleMesh(mesh, serializationObject);
  98123. });
  98124. return serializationObject;
  98125. };
  98126. return SceneSerializer;
  98127. }());
  98128. BABYLON.SceneSerializer = SceneSerializer;
  98129. })(BABYLON || (BABYLON = {}));
  98130. //# sourceMappingURL=babylon.sceneSerializer.js.map
  98131. var BABYLON;
  98132. (function (BABYLON) {
  98133. var ReflectionProbe = /** @class */ (function () {
  98134. function ReflectionProbe(name, size, scene, generateMipMaps) {
  98135. if (generateMipMaps === void 0) { generateMipMaps = true; }
  98136. var _this = this;
  98137. this.name = name;
  98138. this._viewMatrix = BABYLON.Matrix.Identity();
  98139. this._target = BABYLON.Vector3.Zero();
  98140. this._add = BABYLON.Vector3.Zero();
  98141. this._invertYAxis = false;
  98142. this.position = BABYLON.Vector3.Zero();
  98143. this._scene = scene;
  98144. this._scene.reflectionProbes.push(this);
  98145. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98146. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98147. switch (faceIndex) {
  98148. case 0:
  98149. _this._add.copyFromFloats(1, 0, 0);
  98150. break;
  98151. case 1:
  98152. _this._add.copyFromFloats(-1, 0, 0);
  98153. break;
  98154. case 2:
  98155. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  98156. break;
  98157. case 3:
  98158. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  98159. break;
  98160. case 4:
  98161. _this._add.copyFromFloats(0, 0, 1);
  98162. break;
  98163. case 5:
  98164. _this._add.copyFromFloats(0, 0, -1);
  98165. break;
  98166. }
  98167. if (_this._attachedMesh) {
  98168. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  98169. }
  98170. _this.position.addToRef(_this._add, _this._target);
  98171. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  98172. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  98173. scene._forcedViewPosition = _this.position;
  98174. });
  98175. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  98176. scene._forcedViewPosition = null;
  98177. scene.updateTransformMatrix(true);
  98178. });
  98179. if (scene.activeCamera) {
  98180. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  98181. }
  98182. }
  98183. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  98184. get: function () {
  98185. return this._renderTargetTexture.samples;
  98186. },
  98187. set: function (value) {
  98188. this._renderTargetTexture.samples = value;
  98189. },
  98190. enumerable: true,
  98191. configurable: true
  98192. });
  98193. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  98194. get: function () {
  98195. return this._renderTargetTexture.refreshRate;
  98196. },
  98197. set: function (value) {
  98198. this._renderTargetTexture.refreshRate = value;
  98199. },
  98200. enumerable: true,
  98201. configurable: true
  98202. });
  98203. ReflectionProbe.prototype.getScene = function () {
  98204. return this._scene;
  98205. };
  98206. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  98207. get: function () {
  98208. return this._renderTargetTexture;
  98209. },
  98210. enumerable: true,
  98211. configurable: true
  98212. });
  98213. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  98214. get: function () {
  98215. return this._renderTargetTexture.renderList;
  98216. },
  98217. enumerable: true,
  98218. configurable: true
  98219. });
  98220. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  98221. this._attachedMesh = mesh;
  98222. };
  98223. /**
  98224. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  98225. *
  98226. * @param renderingGroupId The rendering group id corresponding to its index
  98227. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  98228. */
  98229. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  98230. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  98231. };
  98232. ReflectionProbe.prototype.dispose = function () {
  98233. var index = this._scene.reflectionProbes.indexOf(this);
  98234. if (index !== -1) {
  98235. // Remove from the scene if found
  98236. this._scene.reflectionProbes.splice(index, 1);
  98237. }
  98238. if (this._renderTargetTexture) {
  98239. this._renderTargetTexture.dispose();
  98240. this._renderTargetTexture = null;
  98241. }
  98242. };
  98243. return ReflectionProbe;
  98244. }());
  98245. BABYLON.ReflectionProbe = ReflectionProbe;
  98246. })(BABYLON || (BABYLON = {}));
  98247. //# sourceMappingURL=babylon.reflectionProbe.js.map
  98248. var BABYLON;
  98249. (function (BABYLON) {
  98250. var Layer = /** @class */ (function () {
  98251. function Layer(name, imgUrl, scene, isBackground, color) {
  98252. this.name = name;
  98253. this.scale = new BABYLON.Vector2(1, 1);
  98254. this.offset = new BABYLON.Vector2(0, 0);
  98255. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  98256. this.layerMask = 0x0FFFFFFF;
  98257. this._vertexBuffers = {};
  98258. // Events
  98259. /**
  98260. * An event triggered when the layer is disposed.
  98261. */
  98262. this.onDisposeObservable = new BABYLON.Observable();
  98263. /**
  98264. * An event triggered before rendering the scene
  98265. */
  98266. this.onBeforeRenderObservable = new BABYLON.Observable();
  98267. /**
  98268. * An event triggered after rendering the scene
  98269. */
  98270. this.onAfterRenderObservable = new BABYLON.Observable();
  98271. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  98272. this.isBackground = isBackground === undefined ? true : isBackground;
  98273. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  98274. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  98275. this._scene.layers.push(this);
  98276. var engine = this._scene.getEngine();
  98277. // VBO
  98278. var vertices = [];
  98279. vertices.push(1, 1);
  98280. vertices.push(-1, 1);
  98281. vertices.push(-1, -1);
  98282. vertices.push(1, -1);
  98283. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98284. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98285. this._createIndexBuffer();
  98286. // Effects
  98287. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  98288. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  98289. }
  98290. Object.defineProperty(Layer.prototype, "onDispose", {
  98291. set: function (callback) {
  98292. if (this._onDisposeObserver) {
  98293. this.onDisposeObservable.remove(this._onDisposeObserver);
  98294. }
  98295. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  98296. },
  98297. enumerable: true,
  98298. configurable: true
  98299. });
  98300. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  98301. set: function (callback) {
  98302. if (this._onBeforeRenderObserver) {
  98303. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  98304. }
  98305. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  98306. },
  98307. enumerable: true,
  98308. configurable: true
  98309. });
  98310. Object.defineProperty(Layer.prototype, "onAfterRender", {
  98311. set: function (callback) {
  98312. if (this._onAfterRenderObserver) {
  98313. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98314. }
  98315. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  98316. },
  98317. enumerable: true,
  98318. configurable: true
  98319. });
  98320. Layer.prototype._createIndexBuffer = function () {
  98321. var engine = this._scene.getEngine();
  98322. // Indices
  98323. var indices = [];
  98324. indices.push(0);
  98325. indices.push(1);
  98326. indices.push(2);
  98327. indices.push(0);
  98328. indices.push(2);
  98329. indices.push(3);
  98330. this._indexBuffer = engine.createIndexBuffer(indices);
  98331. };
  98332. Layer.prototype._rebuild = function () {
  98333. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98334. if (vb) {
  98335. vb._rebuild();
  98336. }
  98337. this._createIndexBuffer();
  98338. };
  98339. Layer.prototype.render = function () {
  98340. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  98341. // Check
  98342. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  98343. return;
  98344. var engine = this._scene.getEngine();
  98345. this.onBeforeRenderObservable.notifyObservers(this);
  98346. // Render
  98347. engine.enableEffect(currentEffect);
  98348. engine.setState(false);
  98349. // Texture
  98350. currentEffect.setTexture("textureSampler", this.texture);
  98351. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  98352. // Color
  98353. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  98354. // Scale / offset
  98355. currentEffect.setVector2("offset", this.offset);
  98356. currentEffect.setVector2("scale", this.scale);
  98357. // VBOs
  98358. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98359. // Draw order
  98360. if (!this.alphaTest) {
  98361. engine.setAlphaMode(this.alphaBlendingMode);
  98362. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98363. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  98364. }
  98365. else {
  98366. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98367. }
  98368. this.onAfterRenderObservable.notifyObservers(this);
  98369. };
  98370. Layer.prototype.dispose = function () {
  98371. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98372. if (vertexBuffer) {
  98373. vertexBuffer.dispose();
  98374. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98375. }
  98376. if (this._indexBuffer) {
  98377. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98378. this._indexBuffer = null;
  98379. }
  98380. if (this.texture) {
  98381. this.texture.dispose();
  98382. this.texture = null;
  98383. }
  98384. // Remove from scene
  98385. var index = this._scene.layers.indexOf(this);
  98386. this._scene.layers.splice(index, 1);
  98387. // Callback
  98388. this.onDisposeObservable.notifyObservers(this);
  98389. this.onDisposeObservable.clear();
  98390. this.onAfterRenderObservable.clear();
  98391. this.onBeforeRenderObservable.clear();
  98392. };
  98393. return Layer;
  98394. }());
  98395. BABYLON.Layer = Layer;
  98396. })(BABYLON || (BABYLON = {}));
  98397. //# sourceMappingURL=babylon.layer.js.map
  98398. var BABYLON;
  98399. (function (BABYLON) {
  98400. var TextureTools = /** @class */ (function () {
  98401. function TextureTools() {
  98402. }
  98403. /**
  98404. * Uses the GPU to create a copy texture rescaled at a given size
  98405. * @param texture Texture to copy from
  98406. * @param width Desired width
  98407. * @param height Desired height
  98408. * @return Generated texture
  98409. */
  98410. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  98411. if (useBilinearMode === void 0) { useBilinearMode = true; }
  98412. var scene = texture.getScene();
  98413. var engine = scene.getEngine();
  98414. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  98415. rtt.wrapU = texture.wrapU;
  98416. rtt.wrapV = texture.wrapV;
  98417. rtt.uOffset = texture.uOffset;
  98418. rtt.vOffset = texture.vOffset;
  98419. rtt.uScale = texture.uScale;
  98420. rtt.vScale = texture.vScale;
  98421. rtt.uAng = texture.uAng;
  98422. rtt.vAng = texture.vAng;
  98423. rtt.wAng = texture.wAng;
  98424. rtt.coordinatesIndex = texture.coordinatesIndex;
  98425. rtt.level = texture.level;
  98426. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  98427. rtt._texture.isReady = false;
  98428. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98429. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98430. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98431. passPostProcess.getEffect().executeWhenCompiled(function () {
  98432. passPostProcess.onApply = function (effect) {
  98433. effect.setTexture("textureSampler", texture);
  98434. };
  98435. var internalTexture = rtt.getInternalTexture();
  98436. if (internalTexture) {
  98437. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  98438. engine.unBindFramebuffer(internalTexture);
  98439. rtt.disposeFramebufferObjects();
  98440. passPostProcess.dispose();
  98441. internalTexture.isReady = true;
  98442. }
  98443. });
  98444. return rtt;
  98445. };
  98446. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  98447. if (!scene._environmentBRDFTexture) {
  98448. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98449. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98450. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98451. scene._environmentBRDFTexture = texture;
  98452. }
  98453. return scene._environmentBRDFTexture;
  98454. };
  98455. 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=";
  98456. return TextureTools;
  98457. }());
  98458. BABYLON.TextureTools = TextureTools;
  98459. })(BABYLON || (BABYLON = {}));
  98460. //# sourceMappingURL=babylon.textureTools.js.map
  98461. var BABYLON;
  98462. (function (BABYLON) {
  98463. var FramingBehavior = /** @class */ (function () {
  98464. function FramingBehavior() {
  98465. this._mode = FramingBehavior.FitFrustumSidesMode;
  98466. this._radiusScale = 1.0;
  98467. this._positionScale = 0.5;
  98468. this._defaultElevation = 0.3;
  98469. this._elevationReturnTime = 1500;
  98470. this._elevationReturnWaitTime = 1000;
  98471. this._zoomStopsAnimation = false;
  98472. this._framingTime = 1500;
  98473. this._isPointerDown = false;
  98474. this._lastInteractionTime = -Infinity;
  98475. // Framing control
  98476. this._animatables = new Array();
  98477. this._betaIsAnimating = false;
  98478. }
  98479. Object.defineProperty(FramingBehavior.prototype, "name", {
  98480. get: function () {
  98481. return "Framing";
  98482. },
  98483. enumerable: true,
  98484. configurable: true
  98485. });
  98486. Object.defineProperty(FramingBehavior.prototype, "mode", {
  98487. /**
  98488. * Gets current mode used by the behavior.
  98489. */
  98490. get: function () {
  98491. return this._mode;
  98492. },
  98493. /**
  98494. * Sets the current mode used by the behavior
  98495. */
  98496. set: function (mode) {
  98497. this._mode = mode;
  98498. },
  98499. enumerable: true,
  98500. configurable: true
  98501. });
  98502. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  98503. /**
  98504. * Gets the scale applied to the radius
  98505. */
  98506. get: function () {
  98507. return this._radiusScale;
  98508. },
  98509. /**
  98510. * Sets the scale applied to the radius (1 by default)
  98511. */
  98512. set: function (radius) {
  98513. this._radiusScale = radius;
  98514. },
  98515. enumerable: true,
  98516. configurable: true
  98517. });
  98518. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  98519. /**
  98520. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98521. */
  98522. get: function () {
  98523. return this._positionScale;
  98524. },
  98525. /**
  98526. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98527. */
  98528. set: function (scale) {
  98529. this._positionScale = scale;
  98530. },
  98531. enumerable: true,
  98532. configurable: true
  98533. });
  98534. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  98535. /**
  98536. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98537. * behaviour is triggered, in radians.
  98538. */
  98539. get: function () {
  98540. return this._defaultElevation;
  98541. },
  98542. /**
  98543. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98544. * behaviour is triggered, in radians.
  98545. */
  98546. set: function (elevation) {
  98547. this._defaultElevation = elevation;
  98548. },
  98549. enumerable: true,
  98550. configurable: true
  98551. });
  98552. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  98553. /**
  98554. * Gets the time (in milliseconds) taken to return to the default beta position.
  98555. * Negative value indicates camera should not return to default.
  98556. */
  98557. get: function () {
  98558. return this._elevationReturnTime;
  98559. },
  98560. /**
  98561. * Sets the time (in milliseconds) taken to return to the default beta position.
  98562. * Negative value indicates camera should not return to default.
  98563. */
  98564. set: function (speed) {
  98565. this._elevationReturnTime = speed;
  98566. },
  98567. enumerable: true,
  98568. configurable: true
  98569. });
  98570. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  98571. /**
  98572. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98573. */
  98574. get: function () {
  98575. return this._elevationReturnWaitTime;
  98576. },
  98577. /**
  98578. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98579. */
  98580. set: function (time) {
  98581. this._elevationReturnWaitTime = time;
  98582. },
  98583. enumerable: true,
  98584. configurable: true
  98585. });
  98586. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  98587. /**
  98588. * Gets the flag that indicates if user zooming should stop animation.
  98589. */
  98590. get: function () {
  98591. return this._zoomStopsAnimation;
  98592. },
  98593. /**
  98594. * Sets the flag that indicates if user zooming should stop animation.
  98595. */
  98596. set: function (flag) {
  98597. this._zoomStopsAnimation = flag;
  98598. },
  98599. enumerable: true,
  98600. configurable: true
  98601. });
  98602. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  98603. /**
  98604. * Gets the transition time when framing the mesh, in milliseconds
  98605. */
  98606. get: function () {
  98607. return this._framingTime;
  98608. },
  98609. /**
  98610. * Sets the transition time when framing the mesh, in milliseconds
  98611. */
  98612. set: function (time) {
  98613. this._framingTime = time;
  98614. },
  98615. enumerable: true,
  98616. configurable: true
  98617. });
  98618. FramingBehavior.prototype.init = function () {
  98619. // Do notihng
  98620. };
  98621. FramingBehavior.prototype.attach = function (camera) {
  98622. var _this = this;
  98623. this._attachedCamera = camera;
  98624. var scene = this._attachedCamera.getScene();
  98625. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  98626. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98627. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98628. _this._isPointerDown = true;
  98629. return;
  98630. }
  98631. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98632. _this._isPointerDown = false;
  98633. }
  98634. });
  98635. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98636. if (mesh) {
  98637. _this.zoomOnMesh(mesh);
  98638. }
  98639. });
  98640. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98641. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98642. _this._applyUserInteraction();
  98643. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  98644. // back to the default position after a given timeout
  98645. _this._maintainCameraAboveGround();
  98646. });
  98647. };
  98648. FramingBehavior.prototype.detach = function () {
  98649. if (!this._attachedCamera) {
  98650. return;
  98651. }
  98652. var scene = this._attachedCamera.getScene();
  98653. if (this._onPrePointerObservableObserver) {
  98654. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98655. }
  98656. if (this._onAfterCheckInputsObserver) {
  98657. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98658. }
  98659. if (this._onMeshTargetChangedObserver) {
  98660. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98661. }
  98662. this._attachedCamera = null;
  98663. };
  98664. /**
  98665. * Targets the given mesh and updates zoom level accordingly.
  98666. * @param mesh The mesh to target.
  98667. * @param radius Optional. If a cached radius position already exists, overrides default.
  98668. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98669. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98670. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98671. */
  98672. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98673. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98674. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98675. mesh.computeWorldMatrix(true);
  98676. var boundingBox = mesh.getBoundingInfo().boundingBox;
  98677. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  98678. };
  98679. /**
  98680. * Targets the given mesh with its children and updates zoom level accordingly.
  98681. * @param mesh The mesh to target.
  98682. * @param radius Optional. If a cached radius position already exists, overrides default.
  98683. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98684. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98685. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98686. */
  98687. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98688. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98689. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98690. mesh.computeWorldMatrix(true);
  98691. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  98692. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  98693. };
  98694. /**
  98695. * Targets the given meshes with their children and updates zoom level accordingly.
  98696. * @param meshes The mesh to target.
  98697. * @param radius Optional. If a cached radius position already exists, overrides default.
  98698. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98699. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98700. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98701. */
  98702. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  98703. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98704. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98705. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  98706. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  98707. for (var i = 0; i < meshes.length; i++) {
  98708. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  98709. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  98710. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  98711. }
  98712. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  98713. };
  98714. /**
  98715. * Targets the given mesh and updates zoom level accordingly.
  98716. * @param mesh The mesh to target.
  98717. * @param radius Optional. If a cached radius position already exists, overrides default.
  98718. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98719. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98720. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98721. */
  98722. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  98723. var _this = this;
  98724. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98725. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98726. var zoomTarget;
  98727. if (!this._attachedCamera) {
  98728. return;
  98729. }
  98730. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  98731. var bottom = minimumWorld.y;
  98732. var top = maximumWorld.y;
  98733. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  98734. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  98735. if (focusOnOriginXZ) {
  98736. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  98737. }
  98738. else {
  98739. var centerWorld = minimumWorld.add(radiusWorld);
  98740. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  98741. }
  98742. if (!this._vectorTransition) {
  98743. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  98744. }
  98745. this._betaIsAnimating = true;
  98746. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  98747. if (animatable) {
  98748. this._animatables.push(animatable);
  98749. }
  98750. // sets the radius and lower radius bounds
  98751. // Small delta ensures camera is not always at lower zoom limit.
  98752. var radius = 0;
  98753. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  98754. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98755. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  98756. radius = position;
  98757. }
  98758. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98759. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98760. if (this._attachedCamera.lowerRadiusLimit === null) {
  98761. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  98762. }
  98763. }
  98764. // Set sensibilities
  98765. var extend = maximumWorld.subtract(minimumWorld).length();
  98766. this._attachedCamera.panningSensibility = 5000 / extend;
  98767. this._attachedCamera.wheelPrecision = 100 / radius;
  98768. // transition to new radius
  98769. if (!this._radiusTransition) {
  98770. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98771. }
  98772. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  98773. _this.stopAllAnimations();
  98774. if (onAnimationEnd) {
  98775. onAnimationEnd();
  98776. }
  98777. if (_this._attachedCamera) {
  98778. _this._attachedCamera.storeState();
  98779. }
  98780. });
  98781. if (animatable) {
  98782. this._animatables.push(animatable);
  98783. }
  98784. };
  98785. /**
  98786. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  98787. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  98788. * frustum width.
  98789. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  98790. * to fully enclose the mesh in the viewing frustum.
  98791. */
  98792. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  98793. var size = maximumWorld.subtract(minimumWorld);
  98794. var boxVectorGlobalDiagonal = size.length();
  98795. var frustumSlope = this._getFrustumSlope();
  98796. // Formula for setting distance
  98797. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  98798. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  98799. // Horizon distance
  98800. var radius = radiusWithoutFraming * this._radiusScale;
  98801. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  98802. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  98803. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  98804. var camera = this._attachedCamera;
  98805. if (!camera) {
  98806. return 0;
  98807. }
  98808. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98809. // Don't exceed the requested limit
  98810. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  98811. }
  98812. // Don't exceed the upper radius limit
  98813. if (camera.upperRadiusLimit) {
  98814. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  98815. }
  98816. return distance;
  98817. };
  98818. /**
  98819. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  98820. * is automatically returned to its default position (expected to be above ground plane).
  98821. */
  98822. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  98823. var _this = this;
  98824. if (this._elevationReturnTime < 0) {
  98825. return;
  98826. }
  98827. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  98828. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  98829. var limitBeta = Math.PI * 0.5;
  98830. // Bring the camera back up if below the ground plane
  98831. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  98832. this._betaIsAnimating = true;
  98833. //Transition to new position
  98834. this.stopAllAnimations();
  98835. if (!this._betaTransition) {
  98836. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98837. }
  98838. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  98839. _this._clearAnimationLocks();
  98840. _this.stopAllAnimations();
  98841. });
  98842. if (animatabe) {
  98843. this._animatables.push(animatabe);
  98844. }
  98845. }
  98846. };
  98847. /**
  98848. * Returns the frustum slope based on the canvas ratio and camera FOV
  98849. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  98850. */
  98851. FramingBehavior.prototype._getFrustumSlope = function () {
  98852. // Calculate the viewport ratio
  98853. // Aspect Ratio is Height/Width.
  98854. var camera = this._attachedCamera;
  98855. if (!camera) {
  98856. return BABYLON.Vector2.Zero();
  98857. }
  98858. var engine = camera.getScene().getEngine();
  98859. var aspectRatio = engine.getAspectRatio(camera);
  98860. // Camera FOV is the vertical field of view (top-bottom) in radians.
  98861. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  98862. var frustumSlopeY = Math.tan(camera.fov / 2);
  98863. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  98864. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  98865. // along the forward vector.
  98866. var frustumSlopeX = frustumSlopeY * aspectRatio;
  98867. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  98868. };
  98869. /**
  98870. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  98871. */
  98872. FramingBehavior.prototype._clearAnimationLocks = function () {
  98873. this._betaIsAnimating = false;
  98874. };
  98875. /**
  98876. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  98877. */
  98878. FramingBehavior.prototype._applyUserInteraction = function () {
  98879. if (this.isUserIsMoving) {
  98880. this._lastInteractionTime = BABYLON.Tools.Now;
  98881. this.stopAllAnimations();
  98882. this._clearAnimationLocks();
  98883. }
  98884. };
  98885. /**
  98886. * Stops and removes all animations that have been applied to the camera
  98887. */
  98888. FramingBehavior.prototype.stopAllAnimations = function () {
  98889. if (this._attachedCamera) {
  98890. this._attachedCamera.animations = [];
  98891. }
  98892. while (this._animatables.length) {
  98893. if (this._animatables[0]) {
  98894. this._animatables[0].onAnimationEnd = null;
  98895. this._animatables[0].stop();
  98896. }
  98897. this._animatables.shift();
  98898. }
  98899. };
  98900. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  98901. /**
  98902. * Gets a value indicating if the user is moving the camera
  98903. */
  98904. get: function () {
  98905. if (!this._attachedCamera) {
  98906. return false;
  98907. }
  98908. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  98909. this._attachedCamera.inertialBetaOffset !== 0 ||
  98910. this._attachedCamera.inertialRadiusOffset !== 0 ||
  98911. this._attachedCamera.inertialPanningX !== 0 ||
  98912. this._attachedCamera.inertialPanningY !== 0 ||
  98913. this._isPointerDown;
  98914. },
  98915. enumerable: true,
  98916. configurable: true
  98917. });
  98918. /**
  98919. * The easing function used by animations
  98920. */
  98921. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  98922. /**
  98923. * The easing mode used by animations
  98924. */
  98925. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  98926. // Statics
  98927. /**
  98928. * The camera can move all the way towards the mesh.
  98929. */
  98930. FramingBehavior.IgnoreBoundsSizeMode = 0;
  98931. /**
  98932. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  98933. */
  98934. FramingBehavior.FitFrustumSidesMode = 1;
  98935. return FramingBehavior;
  98936. }());
  98937. BABYLON.FramingBehavior = FramingBehavior;
  98938. })(BABYLON || (BABYLON = {}));
  98939. //# sourceMappingURL=babylon.framingBehavior.js.map
  98940. var BABYLON;
  98941. (function (BABYLON) {
  98942. /**
  98943. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  98944. */
  98945. var BouncingBehavior = /** @class */ (function () {
  98946. function BouncingBehavior() {
  98947. /**
  98948. * The duration of the animation, in milliseconds
  98949. */
  98950. this.transitionDuration = 450;
  98951. /**
  98952. * Length of the distance animated by the transition when lower radius is reached
  98953. */
  98954. this.lowerRadiusTransitionRange = 2;
  98955. /**
  98956. * Length of the distance animated by the transition when upper radius is reached
  98957. */
  98958. this.upperRadiusTransitionRange = -2;
  98959. this._autoTransitionRange = false;
  98960. // Animations
  98961. this._radiusIsAnimating = false;
  98962. this._radiusBounceTransition = null;
  98963. this._animatables = new Array();
  98964. }
  98965. Object.defineProperty(BouncingBehavior.prototype, "name", {
  98966. get: function () {
  98967. return "Bouncing";
  98968. },
  98969. enumerable: true,
  98970. configurable: true
  98971. });
  98972. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  98973. /**
  98974. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98975. */
  98976. get: function () {
  98977. return this._autoTransitionRange;
  98978. },
  98979. /**
  98980. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  98981. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  98982. */
  98983. set: function (value) {
  98984. var _this = this;
  98985. if (this._autoTransitionRange === value) {
  98986. return;
  98987. }
  98988. this._autoTransitionRange = value;
  98989. var camera = this._attachedCamera;
  98990. if (!camera) {
  98991. return;
  98992. }
  98993. if (value) {
  98994. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98995. if (!mesh) {
  98996. return;
  98997. }
  98998. mesh.computeWorldMatrix(true);
  98999. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99000. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99001. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99002. });
  99003. }
  99004. else if (this._onMeshTargetChangedObserver) {
  99005. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99006. }
  99007. },
  99008. enumerable: true,
  99009. configurable: true
  99010. });
  99011. BouncingBehavior.prototype.init = function () {
  99012. // Do notihng
  99013. };
  99014. BouncingBehavior.prototype.attach = function (camera) {
  99015. var _this = this;
  99016. this._attachedCamera = camera;
  99017. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99018. if (!_this._attachedCamera) {
  99019. return;
  99020. }
  99021. // Add the bounce animation to the lower radius limit
  99022. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99023. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99024. }
  99025. // Add the bounce animation to the upper radius limit
  99026. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99027. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99028. }
  99029. });
  99030. };
  99031. BouncingBehavior.prototype.detach = function () {
  99032. if (!this._attachedCamera) {
  99033. return;
  99034. }
  99035. if (this._onAfterCheckInputsObserver) {
  99036. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99037. }
  99038. if (this._onMeshTargetChangedObserver) {
  99039. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99040. }
  99041. this._attachedCamera = null;
  99042. };
  99043. /**
  99044. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  99045. * @param radiusLimit The limit to check against.
  99046. * @return Bool to indicate if at limit.
  99047. */
  99048. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  99049. if (!this._attachedCamera) {
  99050. return false;
  99051. }
  99052. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  99053. return true;
  99054. }
  99055. return false;
  99056. };
  99057. /**
  99058. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  99059. * @param radiusDelta The delta by which to animate to. Can be negative.
  99060. */
  99061. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  99062. var _this = this;
  99063. if (!this._attachedCamera) {
  99064. return;
  99065. }
  99066. if (!this._radiusBounceTransition) {
  99067. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  99068. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  99069. }
  99070. // Prevent zoom until bounce has completed
  99071. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  99072. this._attachedCamera.wheelPrecision = Infinity;
  99073. this._attachedCamera.inertialRadiusOffset = 0;
  99074. // Animate to the radius limit
  99075. this.stopAllAnimations();
  99076. this._radiusIsAnimating = true;
  99077. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  99078. if (animatable) {
  99079. this._animatables.push(animatable);
  99080. }
  99081. };
  99082. /**
  99083. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  99084. */
  99085. BouncingBehavior.prototype._clearAnimationLocks = function () {
  99086. this._radiusIsAnimating = false;
  99087. if (this._attachedCamera) {
  99088. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  99089. }
  99090. };
  99091. /**
  99092. * Stops and removes all animations that have been applied to the camera
  99093. */
  99094. BouncingBehavior.prototype.stopAllAnimations = function () {
  99095. if (this._attachedCamera) {
  99096. this._attachedCamera.animations = [];
  99097. }
  99098. while (this._animatables.length) {
  99099. this._animatables[0].onAnimationEnd = null;
  99100. this._animatables[0].stop();
  99101. this._animatables.shift();
  99102. }
  99103. };
  99104. /**
  99105. * The easing function used by animations
  99106. */
  99107. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  99108. /**
  99109. * The easing mode used by animations
  99110. */
  99111. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  99112. return BouncingBehavior;
  99113. }());
  99114. BABYLON.BouncingBehavior = BouncingBehavior;
  99115. })(BABYLON || (BABYLON = {}));
  99116. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  99117. var BABYLON;
  99118. (function (BABYLON) {
  99119. var AutoRotationBehavior = /** @class */ (function () {
  99120. function AutoRotationBehavior() {
  99121. this._zoomStopsAnimation = false;
  99122. this._idleRotationSpeed = 0.05;
  99123. this._idleRotationWaitTime = 2000;
  99124. this._idleRotationSpinupTime = 2000;
  99125. this._isPointerDown = false;
  99126. this._lastFrameTime = null;
  99127. this._lastInteractionTime = -Infinity;
  99128. this._cameraRotationSpeed = 0;
  99129. this._lastFrameRadius = 0;
  99130. }
  99131. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  99132. get: function () {
  99133. return "AutoRotation";
  99134. },
  99135. enumerable: true,
  99136. configurable: true
  99137. });
  99138. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  99139. /**
  99140. * Gets the flag that indicates if user zooming should stop animation.
  99141. */
  99142. get: function () {
  99143. return this._zoomStopsAnimation;
  99144. },
  99145. /**
  99146. * Sets the flag that indicates if user zooming should stop animation.
  99147. */
  99148. set: function (flag) {
  99149. this._zoomStopsAnimation = flag;
  99150. },
  99151. enumerable: true,
  99152. configurable: true
  99153. });
  99154. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  99155. /**
  99156. * Gets the default speed at which the camera rotates around the model.
  99157. */
  99158. get: function () {
  99159. return this._idleRotationSpeed;
  99160. },
  99161. /**
  99162. * Sets the default speed at which the camera rotates around the model.
  99163. */
  99164. set: function (speed) {
  99165. this._idleRotationSpeed = speed;
  99166. },
  99167. enumerable: true,
  99168. configurable: true
  99169. });
  99170. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  99171. /**
  99172. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  99173. */
  99174. get: function () {
  99175. return this._idleRotationWaitTime;
  99176. },
  99177. /**
  99178. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  99179. */
  99180. set: function (time) {
  99181. this._idleRotationWaitTime = time;
  99182. },
  99183. enumerable: true,
  99184. configurable: true
  99185. });
  99186. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  99187. /**
  99188. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99189. */
  99190. get: function () {
  99191. return this._idleRotationSpinupTime;
  99192. },
  99193. /**
  99194. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99195. */
  99196. set: function (time) {
  99197. this._idleRotationSpinupTime = time;
  99198. },
  99199. enumerable: true,
  99200. configurable: true
  99201. });
  99202. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  99203. /**
  99204. * Gets a value indicating if the camera is currently rotating because of this behavior
  99205. */
  99206. get: function () {
  99207. return Math.abs(this._cameraRotationSpeed) > 0;
  99208. },
  99209. enumerable: true,
  99210. configurable: true
  99211. });
  99212. AutoRotationBehavior.prototype.init = function () {
  99213. // Do notihng
  99214. };
  99215. AutoRotationBehavior.prototype.attach = function (camera) {
  99216. var _this = this;
  99217. this._attachedCamera = camera;
  99218. var scene = this._attachedCamera.getScene();
  99219. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99220. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99221. _this._isPointerDown = true;
  99222. return;
  99223. }
  99224. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99225. _this._isPointerDown = false;
  99226. }
  99227. });
  99228. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99229. var now = BABYLON.Tools.Now;
  99230. var dt = 0;
  99231. if (_this._lastFrameTime != null) {
  99232. dt = now - _this._lastFrameTime;
  99233. }
  99234. _this._lastFrameTime = now;
  99235. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99236. _this._applyUserInteraction();
  99237. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  99238. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  99239. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  99240. // Step camera rotation by rotation speed
  99241. if (_this._attachedCamera) {
  99242. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  99243. }
  99244. });
  99245. };
  99246. AutoRotationBehavior.prototype.detach = function () {
  99247. if (!this._attachedCamera) {
  99248. return;
  99249. }
  99250. var scene = this._attachedCamera.getScene();
  99251. if (this._onPrePointerObservableObserver) {
  99252. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99253. }
  99254. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99255. this._attachedCamera = null;
  99256. };
  99257. /**
  99258. * Returns true if user is scrolling.
  99259. * @return true if user is scrolling.
  99260. */
  99261. AutoRotationBehavior.prototype._userIsZooming = function () {
  99262. if (!this._attachedCamera) {
  99263. return false;
  99264. }
  99265. return this._attachedCamera.inertialRadiusOffset !== 0;
  99266. };
  99267. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  99268. if (!this._attachedCamera) {
  99269. return false;
  99270. }
  99271. var zoomHasHitLimit = false;
  99272. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  99273. zoomHasHitLimit = true;
  99274. }
  99275. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  99276. this._lastFrameRadius = this._attachedCamera.radius;
  99277. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  99278. };
  99279. /**
  99280. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99281. */
  99282. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  99283. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  99284. this._lastInteractionTime = BABYLON.Tools.Now;
  99285. }
  99286. };
  99287. // Tools
  99288. AutoRotationBehavior.prototype._userIsMoving = function () {
  99289. if (!this._attachedCamera) {
  99290. return false;
  99291. }
  99292. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99293. this._attachedCamera.inertialBetaOffset !== 0 ||
  99294. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99295. this._attachedCamera.inertialPanningX !== 0 ||
  99296. this._attachedCamera.inertialPanningY !== 0 ||
  99297. this._isPointerDown;
  99298. };
  99299. return AutoRotationBehavior;
  99300. }());
  99301. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  99302. })(BABYLON || (BABYLON = {}));
  99303. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  99304. var BABYLON;
  99305. (function (BABYLON) {
  99306. var NullEngineOptions = /** @class */ (function () {
  99307. function NullEngineOptions() {
  99308. this.renderWidth = 512;
  99309. this.renderHeight = 256;
  99310. this.textureSize = 512;
  99311. this.deterministicLockstep = false;
  99312. this.lockstepMaxSteps = 4;
  99313. }
  99314. return NullEngineOptions;
  99315. }());
  99316. BABYLON.NullEngineOptions = NullEngineOptions;
  99317. /**
  99318. * The null engine class provides support for headless version of babylon.js.
  99319. * This can be used in server side scenario or for testing purposes
  99320. */
  99321. var NullEngine = /** @class */ (function (_super) {
  99322. __extends(NullEngine, _super);
  99323. function NullEngine(options) {
  99324. if (options === void 0) { options = new NullEngineOptions(); }
  99325. var _this = _super.call(this, null) || this;
  99326. if (options.deterministicLockstep === undefined) {
  99327. options.deterministicLockstep = false;
  99328. }
  99329. if (options.lockstepMaxSteps === undefined) {
  99330. options.lockstepMaxSteps = 4;
  99331. }
  99332. _this._options = options;
  99333. // Init caps
  99334. // We consider we are on a webgl1 capable device
  99335. _this._caps = new BABYLON.EngineCapabilities();
  99336. _this._caps.maxTexturesImageUnits = 16;
  99337. _this._caps.maxVertexTextureImageUnits = 16;
  99338. _this._caps.maxTextureSize = 512;
  99339. _this._caps.maxCubemapTextureSize = 512;
  99340. _this._caps.maxRenderTextureSize = 512;
  99341. _this._caps.maxVertexAttribs = 16;
  99342. _this._caps.maxVaryingVectors = 16;
  99343. _this._caps.maxFragmentUniformVectors = 16;
  99344. _this._caps.maxVertexUniformVectors = 16;
  99345. // Extensions
  99346. _this._caps.standardDerivatives = false;
  99347. _this._caps.astc = null;
  99348. _this._caps.s3tc = null;
  99349. _this._caps.pvrtc = null;
  99350. _this._caps.etc1 = null;
  99351. _this._caps.etc2 = null;
  99352. _this._caps.textureAnisotropicFilterExtension = null;
  99353. _this._caps.maxAnisotropy = 0;
  99354. _this._caps.uintIndices = false;
  99355. _this._caps.fragmentDepthSupported = false;
  99356. _this._caps.highPrecisionShaderSupported = true;
  99357. _this._caps.colorBufferFloat = false;
  99358. _this._caps.textureFloat = false;
  99359. _this._caps.textureFloatLinearFiltering = false;
  99360. _this._caps.textureFloatRender = false;
  99361. _this._caps.textureHalfFloat = false;
  99362. _this._caps.textureHalfFloatLinearFiltering = false;
  99363. _this._caps.textureHalfFloatRender = false;
  99364. _this._caps.textureLOD = false;
  99365. _this._caps.drawBuffersExtension = false;
  99366. _this._caps.depthTextureExtension = false;
  99367. _this._caps.vertexArrayObject = false;
  99368. _this._caps.instancedArrays = false;
  99369. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  99370. // Wrappers
  99371. if (typeof URL === "undefined") {
  99372. URL = {
  99373. createObjectURL: function () { },
  99374. revokeObjectURL: function () { }
  99375. };
  99376. }
  99377. if (typeof Blob === "undefined") {
  99378. Blob = function () { };
  99379. }
  99380. return _this;
  99381. }
  99382. NullEngine.prototype.isDeterministicLockStep = function () {
  99383. return this._options.deterministicLockstep;
  99384. };
  99385. NullEngine.prototype.getLockstepMaxSteps = function () {
  99386. return this._options.lockstepMaxSteps;
  99387. };
  99388. NullEngine.prototype.getHardwareScalingLevel = function () {
  99389. return 1.0;
  99390. };
  99391. NullEngine.prototype.createVertexBuffer = function (vertices) {
  99392. return {
  99393. capacity: 0,
  99394. references: 1,
  99395. is32Bits: false
  99396. };
  99397. };
  99398. NullEngine.prototype.createIndexBuffer = function (indices) {
  99399. return {
  99400. capacity: 0,
  99401. references: 1,
  99402. is32Bits: false
  99403. };
  99404. };
  99405. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  99406. if (stencil === void 0) { stencil = false; }
  99407. };
  99408. NullEngine.prototype.getRenderWidth = function (useScreen) {
  99409. if (useScreen === void 0) { useScreen = false; }
  99410. if (!useScreen && this._currentRenderTarget) {
  99411. return this._currentRenderTarget.width;
  99412. }
  99413. return this._options.renderWidth;
  99414. };
  99415. NullEngine.prototype.getRenderHeight = function (useScreen) {
  99416. if (useScreen === void 0) { useScreen = false; }
  99417. if (!useScreen && this._currentRenderTarget) {
  99418. return this._currentRenderTarget.height;
  99419. }
  99420. return this._options.renderHeight;
  99421. };
  99422. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  99423. this._cachedViewport = viewport;
  99424. };
  99425. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  99426. return {
  99427. transformFeedback: null,
  99428. __SPECTOR_rebuildProgram: null
  99429. };
  99430. };
  99431. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  99432. return [];
  99433. };
  99434. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  99435. return [];
  99436. };
  99437. NullEngine.prototype.bindSamplers = function (effect) {
  99438. this._currentEffect = null;
  99439. };
  99440. NullEngine.prototype.enableEffect = function (effect) {
  99441. this._currentEffect = effect;
  99442. if (effect.onBind) {
  99443. effect.onBind(effect);
  99444. }
  99445. effect.onBindObservable.notifyObservers(effect);
  99446. };
  99447. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  99448. if (zOffset === void 0) { zOffset = 0; }
  99449. if (reverseSide === void 0) { reverseSide = false; }
  99450. };
  99451. NullEngine.prototype.setIntArray = function (uniform, array) {
  99452. };
  99453. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  99454. };
  99455. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  99456. };
  99457. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  99458. };
  99459. NullEngine.prototype.setFloatArray = function (uniform, array) {
  99460. };
  99461. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  99462. };
  99463. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  99464. };
  99465. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  99466. };
  99467. NullEngine.prototype.setArray = function (uniform, array) {
  99468. };
  99469. NullEngine.prototype.setArray2 = function (uniform, array) {
  99470. };
  99471. NullEngine.prototype.setArray3 = function (uniform, array) {
  99472. };
  99473. NullEngine.prototype.setArray4 = function (uniform, array) {
  99474. };
  99475. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  99476. };
  99477. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  99478. };
  99479. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  99480. };
  99481. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  99482. };
  99483. NullEngine.prototype.setFloat = function (uniform, value) {
  99484. };
  99485. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  99486. };
  99487. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  99488. };
  99489. NullEngine.prototype.setBool = function (uniform, bool) {
  99490. };
  99491. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  99492. };
  99493. NullEngine.prototype.setColor3 = function (uniform, color3) {
  99494. };
  99495. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  99496. };
  99497. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  99498. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  99499. if (this._alphaMode === mode) {
  99500. return;
  99501. }
  99502. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  99503. if (!noDepthWriteChange) {
  99504. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  99505. }
  99506. this._alphaMode = mode;
  99507. };
  99508. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  99509. };
  99510. NullEngine.prototype.wipeCaches = function (bruteForce) {
  99511. if (this.preventCacheWipeBetweenFrames) {
  99512. return;
  99513. }
  99514. this.resetTextureCache();
  99515. this._currentEffect = null;
  99516. if (bruteForce) {
  99517. this._currentProgram = null;
  99518. this._stencilState.reset();
  99519. this._depthCullingState.reset();
  99520. this._alphaState.reset();
  99521. }
  99522. this._cachedVertexBuffers = null;
  99523. this._cachedIndexBuffer = null;
  99524. this._cachedEffectForVertexBuffers = null;
  99525. };
  99526. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  99527. };
  99528. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  99529. };
  99530. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  99531. };
  99532. NullEngine.prototype._createTexture = function () {
  99533. return {};
  99534. };
  99535. NullEngine.prototype._releaseTexture = function (texture) {
  99536. };
  99537. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  99538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99539. if (onLoad === void 0) { onLoad = null; }
  99540. if (onError === void 0) { onError = null; }
  99541. if (buffer === void 0) { buffer = null; }
  99542. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  99543. var url = String(urlArg);
  99544. texture.url = url;
  99545. texture.generateMipMaps = !noMipmap;
  99546. texture.samplingMode = samplingMode;
  99547. texture.invertY = invertY;
  99548. texture.baseWidth = this._options.textureSize;
  99549. texture.baseHeight = this._options.textureSize;
  99550. texture.width = this._options.textureSize;
  99551. texture.height = this._options.textureSize;
  99552. if (format) {
  99553. texture.format = format;
  99554. }
  99555. texture.isReady = true;
  99556. if (onLoad) {
  99557. onLoad();
  99558. }
  99559. this._internalTexturesCache.push(texture);
  99560. return texture;
  99561. };
  99562. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  99563. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  99564. if (options !== undefined && typeof options === "object") {
  99565. fullOptions.generateMipMaps = options.generateMipMaps;
  99566. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  99567. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  99568. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  99569. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  99570. }
  99571. else {
  99572. fullOptions.generateMipMaps = options;
  99573. fullOptions.generateDepthBuffer = true;
  99574. fullOptions.generateStencilBuffer = false;
  99575. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99576. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  99577. }
  99578. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  99579. var width = size.width || size;
  99580. var height = size.height || size;
  99581. texture._depthStencilBuffer = {};
  99582. texture._framebuffer = {};
  99583. texture.baseWidth = width;
  99584. texture.baseHeight = height;
  99585. texture.width = width;
  99586. texture.height = height;
  99587. texture.isReady = true;
  99588. texture.samples = 1;
  99589. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  99590. texture.samplingMode = fullOptions.samplingMode;
  99591. texture.type = fullOptions.type;
  99592. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  99593. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  99594. this._internalTexturesCache.push(texture);
  99595. return texture;
  99596. };
  99597. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  99598. texture.samplingMode = samplingMode;
  99599. };
  99600. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  99601. if (this._currentRenderTarget) {
  99602. this.unBindFramebuffer(this._currentRenderTarget);
  99603. }
  99604. this._currentRenderTarget = texture;
  99605. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  99606. if (this._cachedViewport && !forceFullscreenViewport) {
  99607. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  99608. }
  99609. };
  99610. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  99611. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  99612. this._currentRenderTarget = null;
  99613. if (onBeforeUnbind) {
  99614. if (texture._MSAAFramebuffer) {
  99615. this._currentFramebuffer = texture._framebuffer;
  99616. }
  99617. onBeforeUnbind();
  99618. }
  99619. this._currentFramebuffer = null;
  99620. };
  99621. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  99622. var vbo = {
  99623. capacity: 1,
  99624. references: 1,
  99625. is32Bits: false
  99626. };
  99627. return vbo;
  99628. };
  99629. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  99630. if (premulAlpha === void 0) { premulAlpha = false; }
  99631. };
  99632. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  99633. if (offset === void 0) { offset = 0; }
  99634. };
  99635. /**
  99636. * Updates a dynamic vertex buffer.
  99637. * @param vertexBuffer the vertex buffer to update
  99638. * @param data the data used to update the vertex buffer
  99639. * @param byteOffset the byte offset of the data (optional)
  99640. * @param byteLength the byte length of the data (optional)
  99641. */
  99642. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  99643. };
  99644. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  99645. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  99646. this._boundTexturesCache[this._activeChannel] = texture;
  99647. return true;
  99648. }
  99649. return false;
  99650. };
  99651. NullEngine.prototype._bindTexture = function (channel, texture) {
  99652. if (channel < 0) {
  99653. return;
  99654. }
  99655. this._bindTextureDirectly(0, texture);
  99656. };
  99657. NullEngine.prototype._releaseBuffer = function (buffer) {
  99658. buffer.references--;
  99659. if (buffer.references === 0) {
  99660. return true;
  99661. }
  99662. return false;
  99663. };
  99664. NullEngine.prototype.releaseEffects = function () {
  99665. };
  99666. return NullEngine;
  99667. }(BABYLON.Engine));
  99668. BABYLON.NullEngine = NullEngine;
  99669. })(BABYLON || (BABYLON = {}));
  99670. //# sourceMappingURL=babylon.nullEngine.js.map
  99671. var BABYLON;
  99672. (function (BABYLON) {
  99673. /**
  99674. * This class can be used to get instrumentation data from a Babylon engine
  99675. */
  99676. var EngineInstrumentation = /** @class */ (function () {
  99677. function EngineInstrumentation(engine) {
  99678. this.engine = engine;
  99679. this._captureGPUFrameTime = false;
  99680. this._gpuFrameTime = new BABYLON.PerfCounter();
  99681. this._captureShaderCompilationTime = false;
  99682. this._shaderCompilationTime = new BABYLON.PerfCounter();
  99683. // Observers
  99684. this._onBeginFrameObserver = null;
  99685. this._onEndFrameObserver = null;
  99686. this._onBeforeShaderCompilationObserver = null;
  99687. this._onAfterShaderCompilationObserver = null;
  99688. }
  99689. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  99690. // Properties
  99691. /**
  99692. * Gets the perf counter used for GPU frame time
  99693. */
  99694. get: function () {
  99695. return this._gpuFrameTime;
  99696. },
  99697. enumerable: true,
  99698. configurable: true
  99699. });
  99700. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  99701. /**
  99702. * Gets the GPU frame time capture status
  99703. */
  99704. get: function () {
  99705. return this._captureGPUFrameTime;
  99706. },
  99707. /**
  99708. * Enable or disable the GPU frame time capture
  99709. */
  99710. set: function (value) {
  99711. var _this = this;
  99712. if (value === this._captureGPUFrameTime) {
  99713. return;
  99714. }
  99715. this._captureGPUFrameTime = value;
  99716. if (value) {
  99717. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  99718. if (!_this._gpuFrameTimeToken) {
  99719. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  99720. }
  99721. });
  99722. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  99723. if (!_this._gpuFrameTimeToken) {
  99724. return;
  99725. }
  99726. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  99727. if (time > -1) {
  99728. _this._gpuFrameTimeToken = null;
  99729. _this._gpuFrameTime.fetchNewFrame();
  99730. _this._gpuFrameTime.addCount(time, true);
  99731. }
  99732. });
  99733. }
  99734. else {
  99735. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99736. this._onBeginFrameObserver = null;
  99737. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99738. this._onEndFrameObserver = null;
  99739. }
  99740. },
  99741. enumerable: true,
  99742. configurable: true
  99743. });
  99744. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  99745. /**
  99746. * Gets the perf counter used for shader compilation time
  99747. */
  99748. get: function () {
  99749. return this._shaderCompilationTime;
  99750. },
  99751. enumerable: true,
  99752. configurable: true
  99753. });
  99754. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  99755. /**
  99756. * Gets the shader compilation time capture status
  99757. */
  99758. get: function () {
  99759. return this._captureShaderCompilationTime;
  99760. },
  99761. /**
  99762. * Enable or disable the shader compilation time capture
  99763. */
  99764. set: function (value) {
  99765. var _this = this;
  99766. if (value === this._captureShaderCompilationTime) {
  99767. return;
  99768. }
  99769. this._captureShaderCompilationTime = value;
  99770. if (value) {
  99771. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  99772. _this._shaderCompilationTime.fetchNewFrame();
  99773. _this._shaderCompilationTime.beginMonitoring();
  99774. });
  99775. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  99776. _this._shaderCompilationTime.endMonitoring();
  99777. });
  99778. }
  99779. else {
  99780. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99781. this._onBeforeShaderCompilationObserver = null;
  99782. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99783. this._onAfterShaderCompilationObserver = null;
  99784. }
  99785. },
  99786. enumerable: true,
  99787. configurable: true
  99788. });
  99789. EngineInstrumentation.prototype.dispose = function () {
  99790. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99791. this._onBeginFrameObserver = null;
  99792. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99793. this._onEndFrameObserver = null;
  99794. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99795. this._onBeforeShaderCompilationObserver = null;
  99796. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99797. this._onAfterShaderCompilationObserver = null;
  99798. this.engine = null;
  99799. };
  99800. return EngineInstrumentation;
  99801. }());
  99802. BABYLON.EngineInstrumentation = EngineInstrumentation;
  99803. })(BABYLON || (BABYLON = {}));
  99804. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  99805. var BABYLON;
  99806. (function (BABYLON) {
  99807. /**
  99808. * This class can be used to get instrumentation data from a Babylon engine
  99809. */
  99810. var SceneInstrumentation = /** @class */ (function () {
  99811. function SceneInstrumentation(scene) {
  99812. var _this = this;
  99813. this.scene = scene;
  99814. this._captureActiveMeshesEvaluationTime = false;
  99815. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  99816. this._captureRenderTargetsRenderTime = false;
  99817. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  99818. this._captureFrameTime = false;
  99819. this._frameTime = new BABYLON.PerfCounter();
  99820. this._captureRenderTime = false;
  99821. this._renderTime = new BABYLON.PerfCounter();
  99822. this._captureInterFrameTime = false;
  99823. this._interFrameTime = new BABYLON.PerfCounter();
  99824. this._captureParticlesRenderTime = false;
  99825. this._particlesRenderTime = new BABYLON.PerfCounter();
  99826. this._captureSpritesRenderTime = false;
  99827. this._spritesRenderTime = new BABYLON.PerfCounter();
  99828. this._capturePhysicsTime = false;
  99829. this._physicsTime = new BABYLON.PerfCounter();
  99830. this._captureAnimationsTime = false;
  99831. this._animationsTime = new BABYLON.PerfCounter();
  99832. this._captureCameraRenderTime = false;
  99833. this._cameraRenderTime = new BABYLON.PerfCounter();
  99834. // Observers
  99835. this._onBeforeActiveMeshesEvaluationObserver = null;
  99836. this._onAfterActiveMeshesEvaluationObserver = null;
  99837. this._onBeforeRenderTargetsRenderObserver = null;
  99838. this._onAfterRenderTargetsRenderObserver = null;
  99839. this._onAfterRenderObserver = null;
  99840. this._onBeforeDrawPhaseObserver = null;
  99841. this._onAfterDrawPhaseObserver = null;
  99842. this._onBeforeAnimationsObserver = null;
  99843. this._onBeforeParticlesRenderingObserver = null;
  99844. this._onAfterParticlesRenderingObserver = null;
  99845. this._onBeforeSpritesRenderingObserver = null;
  99846. this._onAfterSpritesRenderingObserver = null;
  99847. this._onBeforePhysicsObserver = null;
  99848. this._onAfterPhysicsObserver = null;
  99849. this._onAfterAnimationsObserver = null;
  99850. this._onBeforeCameraRenderObserver = null;
  99851. this._onAfterCameraRenderObserver = null;
  99852. // Before render
  99853. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  99854. if (_this._captureActiveMeshesEvaluationTime) {
  99855. _this._activeMeshesEvaluationTime.fetchNewFrame();
  99856. }
  99857. if (_this._captureRenderTargetsRenderTime) {
  99858. _this._renderTargetsRenderTime.fetchNewFrame();
  99859. }
  99860. if (_this._captureFrameTime) {
  99861. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  99862. _this._frameTime.beginMonitoring();
  99863. }
  99864. if (_this._captureInterFrameTime) {
  99865. _this._interFrameTime.endMonitoring();
  99866. }
  99867. if (_this._captureParticlesRenderTime) {
  99868. _this._particlesRenderTime.fetchNewFrame();
  99869. }
  99870. if (_this._captureSpritesRenderTime) {
  99871. _this._spritesRenderTime.fetchNewFrame();
  99872. }
  99873. if (_this._captureAnimationsTime) {
  99874. _this._animationsTime.beginMonitoring();
  99875. }
  99876. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  99877. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  99878. });
  99879. // After render
  99880. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  99881. if (_this._captureFrameTime) {
  99882. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  99883. _this._frameTime.endMonitoring();
  99884. }
  99885. if (_this._captureRenderTime) {
  99886. _this._renderTime.endMonitoring(false);
  99887. }
  99888. if (_this._captureInterFrameTime) {
  99889. _this._interFrameTime.beginMonitoring();
  99890. }
  99891. });
  99892. }
  99893. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  99894. // Properties
  99895. /**
  99896. * Gets the perf counter used for active meshes evaluation time
  99897. */
  99898. get: function () {
  99899. return this._activeMeshesEvaluationTime;
  99900. },
  99901. enumerable: true,
  99902. configurable: true
  99903. });
  99904. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  99905. /**
  99906. * Gets the active meshes evaluation time capture status
  99907. */
  99908. get: function () {
  99909. return this._captureActiveMeshesEvaluationTime;
  99910. },
  99911. /**
  99912. * Enable or disable the active meshes evaluation time capture
  99913. */
  99914. set: function (value) {
  99915. var _this = this;
  99916. if (value === this._captureActiveMeshesEvaluationTime) {
  99917. return;
  99918. }
  99919. this._captureActiveMeshesEvaluationTime = value;
  99920. if (value) {
  99921. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  99922. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  99923. _this._activeMeshesEvaluationTime.beginMonitoring();
  99924. });
  99925. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  99926. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  99927. _this._activeMeshesEvaluationTime.endMonitoring();
  99928. });
  99929. }
  99930. else {
  99931. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  99932. this._onBeforeActiveMeshesEvaluationObserver = null;
  99933. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  99934. this._onAfterActiveMeshesEvaluationObserver = null;
  99935. }
  99936. },
  99937. enumerable: true,
  99938. configurable: true
  99939. });
  99940. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  99941. /**
  99942. * Gets the perf counter used for render targets render time
  99943. */
  99944. get: function () {
  99945. return this._renderTargetsRenderTime;
  99946. },
  99947. enumerable: true,
  99948. configurable: true
  99949. });
  99950. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  99951. /**
  99952. * Gets the render targets render time capture status
  99953. */
  99954. get: function () {
  99955. return this._captureRenderTargetsRenderTime;
  99956. },
  99957. /**
  99958. * Enable or disable the render targets render time capture
  99959. */
  99960. set: function (value) {
  99961. var _this = this;
  99962. if (value === this._captureRenderTargetsRenderTime) {
  99963. return;
  99964. }
  99965. this._captureRenderTargetsRenderTime = value;
  99966. if (value) {
  99967. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  99968. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  99969. _this._renderTargetsRenderTime.beginMonitoring();
  99970. });
  99971. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  99972. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  99973. _this._renderTargetsRenderTime.endMonitoring(false);
  99974. });
  99975. }
  99976. else {
  99977. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  99978. this._onBeforeRenderTargetsRenderObserver = null;
  99979. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  99980. this._onAfterRenderTargetsRenderObserver = null;
  99981. }
  99982. },
  99983. enumerable: true,
  99984. configurable: true
  99985. });
  99986. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  99987. /**
  99988. * Gets the perf counter used for particles render time
  99989. */
  99990. get: function () {
  99991. return this._particlesRenderTime;
  99992. },
  99993. enumerable: true,
  99994. configurable: true
  99995. });
  99996. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  99997. /**
  99998. * Gets the particles render time capture status
  99999. */
  100000. get: function () {
  100001. return this._captureParticlesRenderTime;
  100002. },
  100003. /**
  100004. * Enable or disable the particles render time capture
  100005. */
  100006. set: function (value) {
  100007. var _this = this;
  100008. if (value === this._captureParticlesRenderTime) {
  100009. return;
  100010. }
  100011. this._captureParticlesRenderTime = value;
  100012. if (value) {
  100013. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  100014. BABYLON.Tools.StartPerformanceCounter("Particles");
  100015. _this._particlesRenderTime.beginMonitoring();
  100016. });
  100017. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  100018. BABYLON.Tools.EndPerformanceCounter("Particles");
  100019. _this._particlesRenderTime.endMonitoring(false);
  100020. });
  100021. }
  100022. else {
  100023. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100024. this._onBeforeParticlesRenderingObserver = null;
  100025. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100026. this._onAfterParticlesRenderingObserver = null;
  100027. }
  100028. },
  100029. enumerable: true,
  100030. configurable: true
  100031. });
  100032. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  100033. /**
  100034. * Gets the perf counter used for sprites render time
  100035. */
  100036. get: function () {
  100037. return this._spritesRenderTime;
  100038. },
  100039. enumerable: true,
  100040. configurable: true
  100041. });
  100042. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  100043. /**
  100044. * Gets the sprites render time capture status
  100045. */
  100046. get: function () {
  100047. return this._captureSpritesRenderTime;
  100048. },
  100049. /**
  100050. * Enable or disable the sprites render time capture
  100051. */
  100052. set: function (value) {
  100053. var _this = this;
  100054. if (value === this._captureSpritesRenderTime) {
  100055. return;
  100056. }
  100057. this._captureSpritesRenderTime = value;
  100058. if (value) {
  100059. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  100060. BABYLON.Tools.StartPerformanceCounter("Sprites");
  100061. _this._spritesRenderTime.beginMonitoring();
  100062. });
  100063. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  100064. BABYLON.Tools.EndPerformanceCounter("Sprites");
  100065. _this._spritesRenderTime.endMonitoring(false);
  100066. });
  100067. }
  100068. else {
  100069. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100070. this._onBeforeSpritesRenderingObserver = null;
  100071. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100072. this._onAfterSpritesRenderingObserver = null;
  100073. }
  100074. },
  100075. enumerable: true,
  100076. configurable: true
  100077. });
  100078. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  100079. /**
  100080. * Gets the perf counter used for physics time
  100081. */
  100082. get: function () {
  100083. return this._physicsTime;
  100084. },
  100085. enumerable: true,
  100086. configurable: true
  100087. });
  100088. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  100089. /**
  100090. * Gets the physics time capture status
  100091. */
  100092. get: function () {
  100093. return this._capturePhysicsTime;
  100094. },
  100095. /**
  100096. * Enable or disable the physics time capture
  100097. */
  100098. set: function (value) {
  100099. var _this = this;
  100100. if (value === this._capturePhysicsTime) {
  100101. return;
  100102. }
  100103. this._capturePhysicsTime = value;
  100104. if (value) {
  100105. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  100106. BABYLON.Tools.StartPerformanceCounter("Physics");
  100107. _this._physicsTime.beginMonitoring();
  100108. });
  100109. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  100110. BABYLON.Tools.EndPerformanceCounter("Physics");
  100111. _this._physicsTime.endMonitoring();
  100112. });
  100113. }
  100114. else {
  100115. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100116. this._onBeforePhysicsObserver = null;
  100117. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100118. this._onAfterPhysicsObserver = null;
  100119. }
  100120. },
  100121. enumerable: true,
  100122. configurable: true
  100123. });
  100124. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  100125. /**
  100126. * Gets the perf counter used for animations time
  100127. */
  100128. get: function () {
  100129. return this._animationsTime;
  100130. },
  100131. enumerable: true,
  100132. configurable: true
  100133. });
  100134. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  100135. /**
  100136. * Gets the animations time capture status
  100137. */
  100138. get: function () {
  100139. return this._captureAnimationsTime;
  100140. },
  100141. /**
  100142. * Enable or disable the animations time capture
  100143. */
  100144. set: function (value) {
  100145. var _this = this;
  100146. if (value === this._captureAnimationsTime) {
  100147. return;
  100148. }
  100149. this._captureAnimationsTime = value;
  100150. if (value) {
  100151. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  100152. _this._animationsTime.endMonitoring();
  100153. });
  100154. }
  100155. else {
  100156. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100157. this._onAfterAnimationsObserver = null;
  100158. }
  100159. },
  100160. enumerable: true,
  100161. configurable: true
  100162. });
  100163. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  100164. /**
  100165. * Gets the perf counter used for frame time capture
  100166. */
  100167. get: function () {
  100168. return this._frameTime;
  100169. },
  100170. enumerable: true,
  100171. configurable: true
  100172. });
  100173. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  100174. /**
  100175. * Gets the frame time capture status
  100176. */
  100177. get: function () {
  100178. return this._captureFrameTime;
  100179. },
  100180. /**
  100181. * Enable or disable the frame time capture
  100182. */
  100183. set: function (value) {
  100184. this._captureFrameTime = value;
  100185. },
  100186. enumerable: true,
  100187. configurable: true
  100188. });
  100189. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  100190. /**
  100191. * Gets the perf counter used for inter-frames time capture
  100192. */
  100193. get: function () {
  100194. return this._interFrameTime;
  100195. },
  100196. enumerable: true,
  100197. configurable: true
  100198. });
  100199. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  100200. /**
  100201. * Gets the inter-frames time capture status
  100202. */
  100203. get: function () {
  100204. return this._captureInterFrameTime;
  100205. },
  100206. /**
  100207. * Enable or disable the inter-frames time capture
  100208. */
  100209. set: function (value) {
  100210. this._captureInterFrameTime = value;
  100211. },
  100212. enumerable: true,
  100213. configurable: true
  100214. });
  100215. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  100216. /**
  100217. * Gets the perf counter used for render time capture
  100218. */
  100219. get: function () {
  100220. return this._renderTime;
  100221. },
  100222. enumerable: true,
  100223. configurable: true
  100224. });
  100225. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  100226. /**
  100227. * Gets the render time capture status
  100228. */
  100229. get: function () {
  100230. return this._captureRenderTime;
  100231. },
  100232. /**
  100233. * Enable or disable the render time capture
  100234. */
  100235. set: function (value) {
  100236. var _this = this;
  100237. if (value === this._captureRenderTime) {
  100238. return;
  100239. }
  100240. this._captureRenderTime = value;
  100241. if (value) {
  100242. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  100243. _this._renderTime.beginMonitoring();
  100244. BABYLON.Tools.StartPerformanceCounter("Main render");
  100245. });
  100246. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  100247. _this._renderTime.endMonitoring(false);
  100248. BABYLON.Tools.EndPerformanceCounter("Main render");
  100249. });
  100250. }
  100251. else {
  100252. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100253. this._onBeforeDrawPhaseObserver = null;
  100254. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100255. this._onAfterDrawPhaseObserver = null;
  100256. }
  100257. },
  100258. enumerable: true,
  100259. configurable: true
  100260. });
  100261. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  100262. /**
  100263. * Gets the perf counter used for camera render time capture
  100264. */
  100265. get: function () {
  100266. return this._cameraRenderTime;
  100267. },
  100268. enumerable: true,
  100269. configurable: true
  100270. });
  100271. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  100272. /**
  100273. * Gets the camera render time capture status
  100274. */
  100275. get: function () {
  100276. return this._captureCameraRenderTime;
  100277. },
  100278. /**
  100279. * Enable or disable the camera render time capture
  100280. */
  100281. set: function (value) {
  100282. var _this = this;
  100283. if (value === this._captureCameraRenderTime) {
  100284. return;
  100285. }
  100286. this._captureCameraRenderTime = value;
  100287. if (value) {
  100288. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  100289. _this._cameraRenderTime.beginMonitoring();
  100290. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  100291. });
  100292. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  100293. _this._cameraRenderTime.endMonitoring(false);
  100294. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  100295. });
  100296. }
  100297. else {
  100298. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100299. this._onBeforeCameraRenderObserver = null;
  100300. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100301. this._onAfterCameraRenderObserver = null;
  100302. }
  100303. },
  100304. enumerable: true,
  100305. configurable: true
  100306. });
  100307. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  100308. /**
  100309. * Gets the perf counter used for draw calls
  100310. */
  100311. get: function () {
  100312. return this.scene.getEngine()._drawCalls;
  100313. },
  100314. enumerable: true,
  100315. configurable: true
  100316. });
  100317. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  100318. /**
  100319. * Gets the perf counter used for texture collisions
  100320. */
  100321. get: function () {
  100322. return this.scene.getEngine()._textureCollisions;
  100323. },
  100324. enumerable: true,
  100325. configurable: true
  100326. });
  100327. SceneInstrumentation.prototype.dispose = function () {
  100328. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100329. this._onAfterRenderObserver = null;
  100330. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100331. this._onBeforeActiveMeshesEvaluationObserver = null;
  100332. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100333. this._onAfterActiveMeshesEvaluationObserver = null;
  100334. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100335. this._onBeforeRenderTargetsRenderObserver = null;
  100336. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100337. this._onAfterRenderTargetsRenderObserver = null;
  100338. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  100339. this._onBeforeAnimationsObserver = null;
  100340. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100341. this._onBeforeParticlesRenderingObserver = null;
  100342. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100343. this._onAfterParticlesRenderingObserver = null;
  100344. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100345. this._onBeforeSpritesRenderingObserver = null;
  100346. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100347. this._onAfterSpritesRenderingObserver = null;
  100348. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100349. this._onBeforeDrawPhaseObserver = null;
  100350. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100351. this._onAfterDrawPhaseObserver = null;
  100352. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100353. this._onBeforePhysicsObserver = null;
  100354. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100355. this._onAfterPhysicsObserver = null;
  100356. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100357. this._onAfterAnimationsObserver = null;
  100358. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100359. this._onBeforeCameraRenderObserver = null;
  100360. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100361. this._onAfterCameraRenderObserver = null;
  100362. this.scene = null;
  100363. };
  100364. return SceneInstrumentation;
  100365. }());
  100366. BABYLON.SceneInstrumentation = SceneInstrumentation;
  100367. })(BABYLON || (BABYLON = {}));
  100368. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  100369. var BABYLON;
  100370. (function (BABYLON) {
  100371. /**
  100372. * @hidden
  100373. **/
  100374. var _TimeToken = /** @class */ (function () {
  100375. function _TimeToken() {
  100376. this._timeElapsedQueryEnded = false;
  100377. }
  100378. return _TimeToken;
  100379. }());
  100380. BABYLON._TimeToken = _TimeToken;
  100381. })(BABYLON || (BABYLON = {}));
  100382. //# sourceMappingURL=babylon.timeToken.js.map
  100383. var BABYLON;
  100384. (function (BABYLON) {
  100385. /**
  100386. * Background material defines definition.
  100387. * @hidden Mainly internal Use
  100388. */
  100389. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  100390. __extends(BackgroundMaterialDefines, _super);
  100391. /**
  100392. * Constructor of the defines.
  100393. */
  100394. function BackgroundMaterialDefines() {
  100395. var _this = _super.call(this) || this;
  100396. /**
  100397. * True if the diffuse texture is in use.
  100398. */
  100399. _this.DIFFUSE = false;
  100400. /**
  100401. * The direct UV channel to use.
  100402. */
  100403. _this.DIFFUSEDIRECTUV = 0;
  100404. /**
  100405. * True if the diffuse texture is in gamma space.
  100406. */
  100407. _this.GAMMADIFFUSE = false;
  100408. /**
  100409. * True if the diffuse texture has opacity in the alpha channel.
  100410. */
  100411. _this.DIFFUSEHASALPHA = false;
  100412. /**
  100413. * True if you want the material to fade to transparent at grazing angle.
  100414. */
  100415. _this.OPACITYFRESNEL = false;
  100416. /**
  100417. * True if an extra blur needs to be added in the reflection.
  100418. */
  100419. _this.REFLECTIONBLUR = false;
  100420. /**
  100421. * True if you want the material to fade to reflection at grazing angle.
  100422. */
  100423. _this.REFLECTIONFRESNEL = false;
  100424. /**
  100425. * True if you want the material to falloff as far as you move away from the scene center.
  100426. */
  100427. _this.REFLECTIONFALLOFF = false;
  100428. /**
  100429. * False if the current Webgl implementation does not support the texture lod extension.
  100430. */
  100431. _this.TEXTURELODSUPPORT = false;
  100432. /**
  100433. * True to ensure the data are premultiplied.
  100434. */
  100435. _this.PREMULTIPLYALPHA = false;
  100436. /**
  100437. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  100438. */
  100439. _this.USERGBCOLOR = false;
  100440. /**
  100441. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  100442. * stays aligned with the desired configuration.
  100443. */
  100444. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  100445. /**
  100446. * True to add noise in order to reduce the banding effect.
  100447. */
  100448. _this.NOISE = false;
  100449. /**
  100450. * is the reflection texture in BGR color scheme?
  100451. * Mainly used to solve a bug in ios10 video tag
  100452. */
  100453. _this.REFLECTIONBGR = false;
  100454. _this.IMAGEPROCESSING = false;
  100455. _this.VIGNETTE = false;
  100456. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  100457. _this.VIGNETTEBLENDMODEOPAQUE = false;
  100458. _this.TONEMAPPING = false;
  100459. _this.CONTRAST = false;
  100460. _this.COLORCURVES = false;
  100461. _this.COLORGRADING = false;
  100462. _this.COLORGRADING3D = false;
  100463. _this.SAMPLER3DGREENDEPTH = false;
  100464. _this.SAMPLER3DBGRMAP = false;
  100465. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  100466. _this.EXPOSURE = false;
  100467. // Reflection.
  100468. _this.REFLECTION = false;
  100469. _this.REFLECTIONMAP_3D = false;
  100470. _this.REFLECTIONMAP_SPHERICAL = false;
  100471. _this.REFLECTIONMAP_PLANAR = false;
  100472. _this.REFLECTIONMAP_CUBIC = false;
  100473. _this.REFLECTIONMAP_PROJECTION = false;
  100474. _this.REFLECTIONMAP_SKYBOX = false;
  100475. _this.REFLECTIONMAP_EXPLICIT = false;
  100476. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100477. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100478. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100479. _this.INVERTCUBICMAP = false;
  100480. _this.REFLECTIONMAP_OPPOSITEZ = false;
  100481. _this.LODINREFLECTIONALPHA = false;
  100482. _this.GAMMAREFLECTION = false;
  100483. _this.RGBDREFLECTION = false;
  100484. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  100485. // Default BJS.
  100486. _this.MAINUV1 = false;
  100487. _this.MAINUV2 = false;
  100488. _this.UV1 = false;
  100489. _this.UV2 = false;
  100490. _this.CLIPPLANE = false;
  100491. _this.POINTSIZE = false;
  100492. _this.FOG = false;
  100493. _this.NORMAL = false;
  100494. _this.NUM_BONE_INFLUENCERS = 0;
  100495. _this.BonesPerMesh = 0;
  100496. _this.INSTANCES = false;
  100497. _this.SHADOWFLOAT = false;
  100498. _this.rebuild();
  100499. return _this;
  100500. }
  100501. return BackgroundMaterialDefines;
  100502. }(BABYLON.MaterialDefines));
  100503. /**
  100504. * Background material used to create an efficient environement around your scene.
  100505. */
  100506. var BackgroundMaterial = /** @class */ (function (_super) {
  100507. __extends(BackgroundMaterial, _super);
  100508. /**
  100509. * Instantiates a Background Material in the given scene
  100510. * @param name The friendly name of the material
  100511. * @param scene The scene to add the material to
  100512. */
  100513. function BackgroundMaterial(name, scene) {
  100514. var _this = _super.call(this, name, scene) || this;
  100515. /**
  100516. * Key light Color (multiply against the environement texture)
  100517. */
  100518. _this.primaryColor = BABYLON.Color3.White();
  100519. _this._primaryColorShadowLevel = 0;
  100520. _this._primaryColorHighlightLevel = 0;
  100521. /**
  100522. * Reflection Texture used in the material.
  100523. * Should be author in a specific way for the best result (refer to the documentation).
  100524. */
  100525. _this.reflectionTexture = null;
  100526. /**
  100527. * Reflection Texture level of blur.
  100528. *
  100529. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  100530. * texture twice.
  100531. */
  100532. _this.reflectionBlur = 0;
  100533. /**
  100534. * Diffuse Texture used in the material.
  100535. * Should be author in a specific way for the best result (refer to the documentation).
  100536. */
  100537. _this.diffuseTexture = null;
  100538. _this._shadowLights = null;
  100539. /**
  100540. * Specify the list of lights casting shadow on the material.
  100541. * All scene shadow lights will be included if null.
  100542. */
  100543. _this.shadowLights = null;
  100544. /**
  100545. * Helps adjusting the shadow to a softer level if required.
  100546. * 0 means black shadows and 1 means no shadows.
  100547. */
  100548. _this.shadowLevel = 0;
  100549. /**
  100550. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  100551. * It is usually zero but might be interesting to modify according to your setup.
  100552. */
  100553. _this.sceneCenter = BABYLON.Vector3.Zero();
  100554. /**
  100555. * This helps specifying that the material is falling off to the sky box at grazing angle.
  100556. * This helps ensuring a nice transition when the camera goes under the ground.
  100557. */
  100558. _this.opacityFresnel = true;
  100559. /**
  100560. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  100561. * This helps adding a mirror texture on the ground.
  100562. */
  100563. _this.reflectionFresnel = false;
  100564. /**
  100565. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  100566. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  100567. */
  100568. _this.reflectionFalloffDistance = 0.0;
  100569. /**
  100570. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  100571. */
  100572. _this.reflectionAmount = 1.0;
  100573. /**
  100574. * This specifies the weight of the reflection at grazing angle.
  100575. */
  100576. _this.reflectionReflectance0 = 0.05;
  100577. /**
  100578. * This specifies the weight of the reflection at a perpendicular point of view.
  100579. */
  100580. _this.reflectionReflectance90 = 0.5;
  100581. /**
  100582. * Helps to directly use the maps channels instead of their level.
  100583. */
  100584. _this.useRGBColor = true;
  100585. /**
  100586. * This helps reducing the banding effect that could occur on the background.
  100587. */
  100588. _this.enableNoise = false;
  100589. _this._fovMultiplier = 1.0;
  100590. /**
  100591. * Enable the FOV adjustment feature controlled by fovMultiplier.
  100592. */
  100593. _this.useEquirectangularFOV = false;
  100594. _this._maxSimultaneousLights = 4;
  100595. /**
  100596. * Number of Simultaneous lights allowed on the material.
  100597. */
  100598. _this.maxSimultaneousLights = 4;
  100599. /**
  100600. * Keep track of the image processing observer to allow dispose and replace.
  100601. */
  100602. _this._imageProcessingObserver = null;
  100603. /**
  100604. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  100605. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  100606. */
  100607. _this.switchToBGR = false;
  100608. // Temp values kept as cache in the material.
  100609. _this._renderTargets = new BABYLON.SmartArray(16);
  100610. _this._reflectionControls = BABYLON.Vector4.Zero();
  100611. _this._white = BABYLON.Color3.White();
  100612. _this._primaryShadowColor = BABYLON.Color3.Black();
  100613. _this._primaryHighlightColor = BABYLON.Color3.Black();
  100614. // Setup the default processing configuration to the scene.
  100615. _this._attachImageProcessingConfiguration(null);
  100616. _this.getRenderTargetTextures = function () {
  100617. _this._renderTargets.reset();
  100618. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  100619. _this._renderTargets.push(_this._diffuseTexture);
  100620. }
  100621. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  100622. _this._renderTargets.push(_this._reflectionTexture);
  100623. }
  100624. return _this._renderTargets;
  100625. };
  100626. return _this;
  100627. }
  100628. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  100629. /**
  100630. * Experimental Internal Use Only.
  100631. *
  100632. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  100633. * This acts as a helper to set the primary color to a more "human friendly" value.
  100634. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  100635. * output color as close as possible from the chosen value.
  100636. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  100637. * part of lighting setup.)
  100638. */
  100639. get: function () {
  100640. return this.__perceptualColor;
  100641. },
  100642. set: function (value) {
  100643. this.__perceptualColor = value;
  100644. this._computePrimaryColorFromPerceptualColor();
  100645. this._markAllSubMeshesAsLightsDirty();
  100646. },
  100647. enumerable: true,
  100648. configurable: true
  100649. });
  100650. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  100651. /**
  100652. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  100653. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  100654. */
  100655. get: function () {
  100656. return this._primaryColorShadowLevel;
  100657. },
  100658. set: function (value) {
  100659. this._primaryColorShadowLevel = value;
  100660. this._computePrimaryColors();
  100661. this._markAllSubMeshesAsLightsDirty();
  100662. },
  100663. enumerable: true,
  100664. configurable: true
  100665. });
  100666. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  100667. /**
  100668. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  100669. * The primary color is used at the level chosen to define what the white area would look.
  100670. */
  100671. get: function () {
  100672. return this._primaryColorHighlightLevel;
  100673. },
  100674. set: function (value) {
  100675. this._primaryColorHighlightLevel = value;
  100676. this._computePrimaryColors();
  100677. this._markAllSubMeshesAsLightsDirty();
  100678. },
  100679. enumerable: true,
  100680. configurable: true
  100681. });
  100682. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  100683. /**
  100684. * Sets the reflection reflectance fresnel values according to the default standard
  100685. * empirically know to work well :-)
  100686. */
  100687. set: function (value) {
  100688. var reflectionWeight = value;
  100689. if (reflectionWeight < 0.5) {
  100690. reflectionWeight = reflectionWeight * 2.0;
  100691. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  100692. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  100693. }
  100694. else {
  100695. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  100696. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  100697. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  100698. }
  100699. },
  100700. enumerable: true,
  100701. configurable: true
  100702. });
  100703. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  100704. /**
  100705. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100706. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  100707. * Recommended to be keep at 1.0 except for special cases.
  100708. */
  100709. get: function () {
  100710. return this._fovMultiplier;
  100711. },
  100712. set: function (value) {
  100713. if (isNaN(value)) {
  100714. value = 1.0;
  100715. }
  100716. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  100717. },
  100718. enumerable: true,
  100719. configurable: true
  100720. });
  100721. /**
  100722. * Attaches a new image processing configuration to the PBR Material.
  100723. * @param configuration (if null the scene configuration will be use)
  100724. */
  100725. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  100726. var _this = this;
  100727. if (configuration === this._imageProcessingConfiguration) {
  100728. return;
  100729. }
  100730. // Detaches observer.
  100731. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100732. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100733. }
  100734. // Pick the scene configuration if needed.
  100735. if (!configuration) {
  100736. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  100737. }
  100738. else {
  100739. this._imageProcessingConfiguration = configuration;
  100740. }
  100741. // Attaches observer.
  100742. if (this._imageProcessingConfiguration) {
  100743. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  100744. _this._computePrimaryColorFromPerceptualColor();
  100745. _this._markAllSubMeshesAsImageProcessingDirty();
  100746. });
  100747. }
  100748. };
  100749. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  100750. /**
  100751. * Gets the image processing configuration used either in this material.
  100752. */
  100753. get: function () {
  100754. return this._imageProcessingConfiguration;
  100755. },
  100756. /**
  100757. * Sets the Default image processing configuration used either in the this material.
  100758. *
  100759. * If sets to null, the scene one is in use.
  100760. */
  100761. set: function (value) {
  100762. this._attachImageProcessingConfiguration(value);
  100763. // Ensure the effect will be rebuilt.
  100764. this._markAllSubMeshesAsTexturesDirty();
  100765. },
  100766. enumerable: true,
  100767. configurable: true
  100768. });
  100769. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  100770. /**
  100771. * Gets wether the color curves effect is enabled.
  100772. */
  100773. get: function () {
  100774. return this.imageProcessingConfiguration.colorCurvesEnabled;
  100775. },
  100776. /**
  100777. * Sets wether the color curves effect is enabled.
  100778. */
  100779. set: function (value) {
  100780. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  100781. },
  100782. enumerable: true,
  100783. configurable: true
  100784. });
  100785. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  100786. /**
  100787. * Gets wether the color grading effect is enabled.
  100788. */
  100789. get: function () {
  100790. return this.imageProcessingConfiguration.colorGradingEnabled;
  100791. },
  100792. /**
  100793. * Gets wether the color grading effect is enabled.
  100794. */
  100795. set: function (value) {
  100796. this.imageProcessingConfiguration.colorGradingEnabled = value;
  100797. },
  100798. enumerable: true,
  100799. configurable: true
  100800. });
  100801. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  100802. /**
  100803. * Gets wether tonemapping is enabled or not.
  100804. */
  100805. get: function () {
  100806. return this._imageProcessingConfiguration.toneMappingEnabled;
  100807. },
  100808. /**
  100809. * Sets wether tonemapping is enabled or not
  100810. */
  100811. set: function (value) {
  100812. this._imageProcessingConfiguration.toneMappingEnabled = value;
  100813. },
  100814. enumerable: true,
  100815. configurable: true
  100816. });
  100817. ;
  100818. ;
  100819. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  100820. /**
  100821. * The camera exposure used on this material.
  100822. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100823. * This corresponds to a photographic exposure.
  100824. */
  100825. get: function () {
  100826. return this._imageProcessingConfiguration.exposure;
  100827. },
  100828. /**
  100829. * The camera exposure used on this material.
  100830. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100831. * This corresponds to a photographic exposure.
  100832. */
  100833. set: function (value) {
  100834. this._imageProcessingConfiguration.exposure = value;
  100835. },
  100836. enumerable: true,
  100837. configurable: true
  100838. });
  100839. ;
  100840. ;
  100841. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  100842. /**
  100843. * Gets The camera contrast used on this material.
  100844. */
  100845. get: function () {
  100846. return this._imageProcessingConfiguration.contrast;
  100847. },
  100848. /**
  100849. * Sets The camera contrast used on this material.
  100850. */
  100851. set: function (value) {
  100852. this._imageProcessingConfiguration.contrast = value;
  100853. },
  100854. enumerable: true,
  100855. configurable: true
  100856. });
  100857. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  100858. /**
  100859. * Gets the Color Grading 2D Lookup Texture.
  100860. */
  100861. get: function () {
  100862. return this._imageProcessingConfiguration.colorGradingTexture;
  100863. },
  100864. /**
  100865. * Sets the Color Grading 2D Lookup Texture.
  100866. */
  100867. set: function (value) {
  100868. this.imageProcessingConfiguration.colorGradingTexture = value;
  100869. },
  100870. enumerable: true,
  100871. configurable: true
  100872. });
  100873. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  100874. /**
  100875. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100876. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100877. * 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;
  100878. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100879. */
  100880. get: function () {
  100881. return this.imageProcessingConfiguration.colorCurves;
  100882. },
  100883. /**
  100884. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  100885. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  100886. * 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;
  100887. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  100888. */
  100889. set: function (value) {
  100890. this.imageProcessingConfiguration.colorCurves = value;
  100891. },
  100892. enumerable: true,
  100893. configurable: true
  100894. });
  100895. /**
  100896. * The entire material has been created in order to prevent overdraw.
  100897. * @returns false
  100898. */
  100899. BackgroundMaterial.prototype.needAlphaTesting = function () {
  100900. return true;
  100901. };
  100902. /**
  100903. * The entire material has been created in order to prevent overdraw.
  100904. * @returns true if blending is enable
  100905. */
  100906. BackgroundMaterial.prototype.needAlphaBlending = function () {
  100907. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  100908. };
  100909. /**
  100910. * Checks wether the material is ready to be rendered for a given mesh.
  100911. * @param mesh The mesh to render
  100912. * @param subMesh The submesh to check against
  100913. * @param useInstances Specify wether or not the material is used with instances
  100914. * @returns true if all the dependencies are ready (Textures, Effects...)
  100915. */
  100916. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  100917. var _this = this;
  100918. if (useInstances === void 0) { useInstances = false; }
  100919. if (subMesh.effect && this.isFrozen) {
  100920. if (this._wasPreviouslyReady) {
  100921. return true;
  100922. }
  100923. }
  100924. if (!subMesh._materialDefines) {
  100925. subMesh._materialDefines = new BackgroundMaterialDefines();
  100926. }
  100927. var scene = this.getScene();
  100928. var defines = subMesh._materialDefines;
  100929. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  100930. if (defines._renderId === scene.getRenderId()) {
  100931. return true;
  100932. }
  100933. }
  100934. var engine = scene.getEngine();
  100935. // Lights
  100936. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  100937. defines._needNormals = true;
  100938. // Textures
  100939. if (defines._areTexturesDirty) {
  100940. defines._needUVs = false;
  100941. if (scene.texturesEnabled) {
  100942. if (scene.getEngine().getCaps().textureLOD) {
  100943. defines.TEXTURELODSUPPORT = true;
  100944. }
  100945. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  100946. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  100947. return false;
  100948. }
  100949. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  100950. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  100951. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  100952. defines.OPACITYFRESNEL = this._opacityFresnel;
  100953. }
  100954. else {
  100955. defines.DIFFUSE = false;
  100956. defines.DIFFUSEHASALPHA = false;
  100957. defines.GAMMADIFFUSE = false;
  100958. defines.OPACITYFRESNEL = false;
  100959. }
  100960. var reflectionTexture = this._reflectionTexture;
  100961. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  100962. if (!reflectionTexture.isReadyOrNotBlocking()) {
  100963. return false;
  100964. }
  100965. defines.REFLECTION = true;
  100966. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  100967. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  100968. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  100969. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  100970. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  100971. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  100972. defines.REFLECTIONBGR = this.switchToBGR;
  100973. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  100974. defines.INVERTCUBICMAP = true;
  100975. }
  100976. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  100977. switch (reflectionTexture.coordinatesMode) {
  100978. case BABYLON.Texture.EXPLICIT_MODE:
  100979. defines.REFLECTIONMAP_EXPLICIT = true;
  100980. break;
  100981. case BABYLON.Texture.PLANAR_MODE:
  100982. defines.REFLECTIONMAP_PLANAR = true;
  100983. break;
  100984. case BABYLON.Texture.PROJECTION_MODE:
  100985. defines.REFLECTIONMAP_PROJECTION = true;
  100986. break;
  100987. case BABYLON.Texture.SKYBOX_MODE:
  100988. defines.REFLECTIONMAP_SKYBOX = true;
  100989. break;
  100990. case BABYLON.Texture.SPHERICAL_MODE:
  100991. defines.REFLECTIONMAP_SPHERICAL = true;
  100992. break;
  100993. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  100994. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  100995. break;
  100996. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  100997. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  100998. break;
  100999. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101000. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101001. break;
  101002. case BABYLON.Texture.CUBIC_MODE:
  101003. case BABYLON.Texture.INVCUBIC_MODE:
  101004. default:
  101005. defines.REFLECTIONMAP_CUBIC = true;
  101006. break;
  101007. }
  101008. if (this.reflectionFresnel) {
  101009. defines.REFLECTIONFRESNEL = true;
  101010. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  101011. this._reflectionControls.x = this.reflectionAmount;
  101012. this._reflectionControls.y = this.reflectionReflectance0;
  101013. this._reflectionControls.z = this.reflectionReflectance90;
  101014. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  101015. }
  101016. else {
  101017. defines.REFLECTIONFRESNEL = false;
  101018. defines.REFLECTIONFALLOFF = false;
  101019. }
  101020. }
  101021. else {
  101022. defines.REFLECTION = false;
  101023. defines.REFLECTIONFRESNEL = false;
  101024. defines.REFLECTIONFALLOFF = false;
  101025. defines.REFLECTIONBLUR = false;
  101026. defines.REFLECTIONMAP_3D = false;
  101027. defines.REFLECTIONMAP_SPHERICAL = false;
  101028. defines.REFLECTIONMAP_PLANAR = false;
  101029. defines.REFLECTIONMAP_CUBIC = false;
  101030. defines.REFLECTIONMAP_PROJECTION = false;
  101031. defines.REFLECTIONMAP_SKYBOX = false;
  101032. defines.REFLECTIONMAP_EXPLICIT = false;
  101033. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101034. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101035. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101036. defines.INVERTCUBICMAP = false;
  101037. defines.REFLECTIONMAP_OPPOSITEZ = false;
  101038. defines.LODINREFLECTIONALPHA = false;
  101039. defines.GAMMAREFLECTION = false;
  101040. defines.RGBDREFLECTION = false;
  101041. }
  101042. }
  101043. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  101044. defines.USERGBCOLOR = this._useRGBColor;
  101045. defines.NOISE = this._enableNoise;
  101046. }
  101047. if (defines._areLightsDirty) {
  101048. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  101049. }
  101050. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  101051. if (!this._imageProcessingConfiguration.isReady()) {
  101052. return false;
  101053. }
  101054. this._imageProcessingConfiguration.prepareDefines(defines);
  101055. }
  101056. // Misc.
  101057. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  101058. // Values that need to be evaluated on every frame
  101059. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  101060. // Attribs
  101061. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  101062. if (mesh) {
  101063. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101064. mesh.createNormals(true);
  101065. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  101066. }
  101067. }
  101068. }
  101069. // Get correct effect
  101070. if (defines.isDirty) {
  101071. defines.markAsProcessed();
  101072. scene.resetCachedMaterial();
  101073. // Fallbacks
  101074. var fallbacks = new BABYLON.EffectFallbacks();
  101075. if (defines.FOG) {
  101076. fallbacks.addFallback(0, "FOG");
  101077. }
  101078. if (defines.POINTSIZE) {
  101079. fallbacks.addFallback(1, "POINTSIZE");
  101080. }
  101081. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  101082. if (defines.NUM_BONE_INFLUENCERS > 0) {
  101083. fallbacks.addCPUSkinningFallback(0, mesh);
  101084. }
  101085. //Attributes
  101086. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101087. if (defines.NORMAL) {
  101088. attribs.push(BABYLON.VertexBuffer.NormalKind);
  101089. }
  101090. if (defines.UV1) {
  101091. attribs.push(BABYLON.VertexBuffer.UVKind);
  101092. }
  101093. if (defines.UV2) {
  101094. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101095. }
  101096. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  101097. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  101098. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  101099. "vFogInfos", "vFogColor", "pointSize",
  101100. "vClipPlane", "mBones",
  101101. "vPrimaryColor", "vPrimaryColorShadow",
  101102. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  101103. "shadowLevel", "alpha",
  101104. "vBackgroundCenter", "vReflectionControl",
  101105. "vDiffuseInfos", "diffuseMatrix",
  101106. ];
  101107. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  101108. var uniformBuffers = ["Material", "Scene"];
  101109. if (BABYLON.ImageProcessingConfiguration) {
  101110. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  101111. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  101112. }
  101113. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  101114. uniformsNames: uniforms,
  101115. uniformBuffersNames: uniformBuffers,
  101116. samplers: samplers,
  101117. defines: defines,
  101118. maxSimultaneousLights: this._maxSimultaneousLights
  101119. });
  101120. var onCompiled = function (effect) {
  101121. if (_this.onCompiled) {
  101122. _this.onCompiled(effect);
  101123. }
  101124. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  101125. };
  101126. var join = defines.toString();
  101127. subMesh.setEffect(scene.getEngine().createEffect("background", {
  101128. attributes: attribs,
  101129. uniformsNames: uniforms,
  101130. uniformBuffersNames: uniformBuffers,
  101131. samplers: samplers,
  101132. defines: join,
  101133. fallbacks: fallbacks,
  101134. onCompiled: onCompiled,
  101135. onError: this.onError,
  101136. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  101137. }, engine), defines);
  101138. this.buildUniformLayout();
  101139. }
  101140. if (!subMesh.effect || !subMesh.effect.isReady()) {
  101141. return false;
  101142. }
  101143. defines._renderId = scene.getRenderId();
  101144. this._wasPreviouslyReady = true;
  101145. return true;
  101146. };
  101147. /**
  101148. * Compute the primary color according to the chosen perceptual color.
  101149. */
  101150. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  101151. if (!this.__perceptualColor) {
  101152. return;
  101153. }
  101154. this._primaryColor.copyFrom(this.__perceptualColor);
  101155. // Revert gamma space.
  101156. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  101157. // Revert image processing configuration.
  101158. if (this._imageProcessingConfiguration) {
  101159. // Revert Exposure.
  101160. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  101161. }
  101162. this._computePrimaryColors();
  101163. };
  101164. /**
  101165. * Compute the highlights and shadow colors according to their chosen levels.
  101166. */
  101167. BackgroundMaterial.prototype._computePrimaryColors = function () {
  101168. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  101169. return;
  101170. }
  101171. // Find the highlight color based on the configuration.
  101172. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  101173. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  101174. // Find the shadow color based on the configuration.
  101175. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  101176. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  101177. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  101178. };
  101179. /**
  101180. * Build the uniform buffer used in the material.
  101181. */
  101182. BackgroundMaterial.prototype.buildUniformLayout = function () {
  101183. // Order is important !
  101184. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  101185. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  101186. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  101187. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  101188. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  101189. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  101190. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  101191. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  101192. this._uniformBuffer.addUniform("pointSize", 1);
  101193. this._uniformBuffer.addUniform("shadowLevel", 1);
  101194. this._uniformBuffer.addUniform("alpha", 1);
  101195. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  101196. this._uniformBuffer.addUniform("vReflectionControl", 4);
  101197. this._uniformBuffer.create();
  101198. };
  101199. /**
  101200. * Unbind the material.
  101201. */
  101202. BackgroundMaterial.prototype.unbind = function () {
  101203. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  101204. this._uniformBuffer.setTexture("diffuseSampler", null);
  101205. }
  101206. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  101207. this._uniformBuffer.setTexture("reflectionSampler", null);
  101208. }
  101209. _super.prototype.unbind.call(this);
  101210. };
  101211. /**
  101212. * Bind only the world matrix to the material.
  101213. * @param world The world matrix to bind.
  101214. */
  101215. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  101216. this._activeEffect.setMatrix("world", world);
  101217. };
  101218. /**
  101219. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  101220. * @param world The world matrix to bind.
  101221. * @param subMesh The submesh to bind for.
  101222. */
  101223. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  101224. var scene = this.getScene();
  101225. var defines = subMesh._materialDefines;
  101226. if (!defines) {
  101227. return;
  101228. }
  101229. var effect = subMesh.effect;
  101230. if (!effect) {
  101231. return;
  101232. }
  101233. this._activeEffect = effect;
  101234. // Matrices
  101235. this.bindOnlyWorldMatrix(world);
  101236. // Bones
  101237. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  101238. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  101239. if (mustRebind) {
  101240. this._uniformBuffer.bindToEffect(effect, "Material");
  101241. this.bindViewProjection(effect);
  101242. var reflectionTexture = this._reflectionTexture;
  101243. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  101244. // Texture uniforms
  101245. if (scene.texturesEnabled) {
  101246. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101247. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  101248. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  101249. }
  101250. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101251. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  101252. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  101253. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  101254. }
  101255. }
  101256. if (this.shadowLevel > 0) {
  101257. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  101258. }
  101259. this._uniformBuffer.updateFloat("alpha", this.alpha);
  101260. // Point size
  101261. if (this.pointsCloud) {
  101262. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  101263. }
  101264. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  101265. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  101266. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  101267. }
  101268. else {
  101269. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  101270. }
  101271. }
  101272. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  101273. // Textures
  101274. if (scene.texturesEnabled) {
  101275. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101276. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  101277. }
  101278. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101279. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  101280. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101281. }
  101282. else if (!defines.REFLECTIONBLUR) {
  101283. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101284. }
  101285. else {
  101286. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  101287. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  101288. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  101289. }
  101290. if (defines.REFLECTIONFRESNEL) {
  101291. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  101292. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  101293. }
  101294. }
  101295. }
  101296. // Clip plane
  101297. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  101298. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  101299. }
  101300. if (mustRebind || !this.isFrozen) {
  101301. if (scene.lightsEnabled) {
  101302. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  101303. }
  101304. // View
  101305. this.bindView(effect);
  101306. // Fog
  101307. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  101308. // image processing
  101309. if (this._imageProcessingConfiguration) {
  101310. this._imageProcessingConfiguration.bind(this._activeEffect);
  101311. }
  101312. }
  101313. this._uniformBuffer.update();
  101314. this._afterBind(mesh, this._activeEffect);
  101315. };
  101316. /**
  101317. * Dispose the material.
  101318. * @param forceDisposeEffect Force disposal of the associated effect.
  101319. * @param forceDisposeTextures Force disposal of the associated textures.
  101320. */
  101321. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  101322. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  101323. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  101324. if (forceDisposeTextures) {
  101325. if (this.diffuseTexture) {
  101326. this.diffuseTexture.dispose();
  101327. }
  101328. if (this.reflectionTexture) {
  101329. this.reflectionTexture.dispose();
  101330. }
  101331. }
  101332. this._renderTargets.dispose();
  101333. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101334. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101335. }
  101336. _super.prototype.dispose.call(this, forceDisposeEffect);
  101337. };
  101338. /**
  101339. * Clones the material.
  101340. * @param name The cloned name.
  101341. * @returns The cloned material.
  101342. */
  101343. BackgroundMaterial.prototype.clone = function (name) {
  101344. var _this = this;
  101345. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  101346. };
  101347. /**
  101348. * Serializes the current material to its JSON representation.
  101349. * @returns The JSON representation.
  101350. */
  101351. BackgroundMaterial.prototype.serialize = function () {
  101352. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101353. serializationObject.customType = "BABYLON.BackgroundMaterial";
  101354. return serializationObject;
  101355. };
  101356. /**
  101357. * Gets the class name of the material
  101358. * @returns "BackgroundMaterial"
  101359. */
  101360. BackgroundMaterial.prototype.getClassName = function () {
  101361. return "BackgroundMaterial";
  101362. };
  101363. /**
  101364. * Parse a JSON input to create back a background material.
  101365. * @param source The JSON data to parse
  101366. * @param scene The scene to create the parsed material in
  101367. * @param rootUrl The root url of the assets the material depends upon
  101368. * @returns the instantiated BackgroundMaterial.
  101369. */
  101370. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  101371. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  101372. };
  101373. /**
  101374. * Standard reflectance value at parallel view angle.
  101375. */
  101376. BackgroundMaterial.StandardReflectance0 = 0.05;
  101377. /**
  101378. * Standard reflectance value at grazing angle.
  101379. */
  101380. BackgroundMaterial.StandardReflectance90 = 0.5;
  101381. __decorate([
  101382. BABYLON.serializeAsColor3()
  101383. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  101384. __decorate([
  101385. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101386. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  101387. __decorate([
  101388. BABYLON.serializeAsColor3()
  101389. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  101390. __decorate([
  101391. BABYLON.serialize()
  101392. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  101393. __decorate([
  101394. BABYLON.serialize()
  101395. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  101396. __decorate([
  101397. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101398. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  101399. __decorate([
  101400. BABYLON.serializeAsTexture()
  101401. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  101402. __decorate([
  101403. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101404. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  101405. __decorate([
  101406. BABYLON.serialize()
  101407. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  101408. __decorate([
  101409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101410. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  101411. __decorate([
  101412. BABYLON.serializeAsTexture()
  101413. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  101414. __decorate([
  101415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101416. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  101417. __decorate([
  101418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101419. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  101420. __decorate([
  101421. BABYLON.serialize()
  101422. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  101423. __decorate([
  101424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101425. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  101426. __decorate([
  101427. BABYLON.serializeAsVector3()
  101428. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  101429. __decorate([
  101430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101431. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  101432. __decorate([
  101433. BABYLON.serialize()
  101434. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  101435. __decorate([
  101436. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101437. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  101438. __decorate([
  101439. BABYLON.serialize()
  101440. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  101441. __decorate([
  101442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101443. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  101444. __decorate([
  101445. BABYLON.serialize()
  101446. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  101447. __decorate([
  101448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101449. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  101450. __decorate([
  101451. BABYLON.serialize()
  101452. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  101453. __decorate([
  101454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101455. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  101456. __decorate([
  101457. BABYLON.serialize()
  101458. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  101459. __decorate([
  101460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101461. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  101462. __decorate([
  101463. BABYLON.serialize()
  101464. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  101465. __decorate([
  101466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101467. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  101468. __decorate([
  101469. BABYLON.serialize()
  101470. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  101471. __decorate([
  101472. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101473. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  101474. __decorate([
  101475. BABYLON.serialize()
  101476. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  101477. __decorate([
  101478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101479. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  101480. __decorate([
  101481. BABYLON.serialize()
  101482. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  101483. __decorate([
  101484. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101485. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  101486. __decorate([
  101487. BABYLON.serializeAsImageProcessingConfiguration()
  101488. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  101489. return BackgroundMaterial;
  101490. }(BABYLON.PushMaterial));
  101491. BABYLON.BackgroundMaterial = BackgroundMaterial;
  101492. })(BABYLON || (BABYLON = {}));
  101493. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  101494. var __assign = (this && this.__assign) || Object.assign || function(t) {
  101495. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101496. s = arguments[i];
  101497. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101498. t[p] = s[p];
  101499. }
  101500. return t;
  101501. };
  101502. var BABYLON;
  101503. (function (BABYLON) {
  101504. /**
  101505. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  101506. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  101507. * It also helps with the default setup of your imageProcessing configuration.
  101508. */
  101509. var EnvironmentHelper = /** @class */ (function () {
  101510. /**
  101511. * constructor
  101512. * @param options
  101513. * @param scene The scene to add the material to
  101514. */
  101515. function EnvironmentHelper(options, scene) {
  101516. var _this = this;
  101517. this._errorHandler = function (message, exception) {
  101518. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  101519. };
  101520. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  101521. this._scene = scene;
  101522. this.onErrorObservable = new BABYLON.Observable();
  101523. this._setupBackground();
  101524. this._setupImageProcessing();
  101525. }
  101526. /**
  101527. * Creates the default options for the helper.
  101528. */
  101529. EnvironmentHelper._getDefaultOptions = function () {
  101530. return {
  101531. createGround: true,
  101532. groundSize: 15,
  101533. groundTexture: this._groundTextureCDNUrl,
  101534. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101535. groundOpacity: 0.9,
  101536. enableGroundShadow: true,
  101537. groundShadowLevel: 0.5,
  101538. enableGroundMirror: false,
  101539. groundMirrorSizeRatio: 0.3,
  101540. groundMirrorBlurKernel: 64,
  101541. groundMirrorAmount: 1,
  101542. groundMirrorFresnelWeight: 1,
  101543. groundMirrorFallOffDistance: 0,
  101544. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  101545. groundYBias: 0.00001,
  101546. createSkybox: true,
  101547. skyboxSize: 20,
  101548. skyboxTexture: this._skyboxTextureCDNUrl,
  101549. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101550. backgroundYRotation: 0,
  101551. sizeAuto: true,
  101552. rootPosition: BABYLON.Vector3.Zero(),
  101553. setupImageProcessing: true,
  101554. environmentTexture: this._environmentTextureCDNUrl,
  101555. cameraExposure: 0.8,
  101556. cameraContrast: 1.2,
  101557. toneMappingEnabled: true,
  101558. };
  101559. };
  101560. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  101561. /**
  101562. * Gets the root mesh created by the helper.
  101563. */
  101564. get: function () {
  101565. return this._rootMesh;
  101566. },
  101567. enumerable: true,
  101568. configurable: true
  101569. });
  101570. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  101571. /**
  101572. * Gets the skybox created by the helper.
  101573. */
  101574. get: function () {
  101575. return this._skybox;
  101576. },
  101577. enumerable: true,
  101578. configurable: true
  101579. });
  101580. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  101581. /**
  101582. * Gets the skybox texture created by the helper.
  101583. */
  101584. get: function () {
  101585. return this._skyboxTexture;
  101586. },
  101587. enumerable: true,
  101588. configurable: true
  101589. });
  101590. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  101591. /**
  101592. * Gets the skybox material created by the helper.
  101593. */
  101594. get: function () {
  101595. return this._skyboxMaterial;
  101596. },
  101597. enumerable: true,
  101598. configurable: true
  101599. });
  101600. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  101601. /**
  101602. * Gets the ground mesh created by the helper.
  101603. */
  101604. get: function () {
  101605. return this._ground;
  101606. },
  101607. enumerable: true,
  101608. configurable: true
  101609. });
  101610. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  101611. /**
  101612. * Gets the ground texture created by the helper.
  101613. */
  101614. get: function () {
  101615. return this._groundTexture;
  101616. },
  101617. enumerable: true,
  101618. configurable: true
  101619. });
  101620. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  101621. /**
  101622. * Gets the ground mirror created by the helper.
  101623. */
  101624. get: function () {
  101625. return this._groundMirror;
  101626. },
  101627. enumerable: true,
  101628. configurable: true
  101629. });
  101630. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  101631. /**
  101632. * Gets the ground mirror render list to helps pushing the meshes
  101633. * you wish in the ground reflection.
  101634. */
  101635. get: function () {
  101636. if (this._groundMirror) {
  101637. return this._groundMirror.renderList;
  101638. }
  101639. return null;
  101640. },
  101641. enumerable: true,
  101642. configurable: true
  101643. });
  101644. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  101645. /**
  101646. * Gets the ground material created by the helper.
  101647. */
  101648. get: function () {
  101649. return this._groundMaterial;
  101650. },
  101651. enumerable: true,
  101652. configurable: true
  101653. });
  101654. /**
  101655. * Updates the background according to the new options
  101656. * @param options
  101657. */
  101658. EnvironmentHelper.prototype.updateOptions = function (options) {
  101659. var newOptions = __assign({}, this._options, options);
  101660. if (this._ground && !newOptions.createGround) {
  101661. this._ground.dispose();
  101662. this._ground = null;
  101663. }
  101664. if (this._groundMaterial && !newOptions.createGround) {
  101665. this._groundMaterial.dispose();
  101666. this._groundMaterial = null;
  101667. }
  101668. if (this._groundTexture) {
  101669. if (this._options.groundTexture != newOptions.groundTexture) {
  101670. this._groundTexture.dispose();
  101671. this._groundTexture = null;
  101672. }
  101673. }
  101674. if (this._skybox && !newOptions.createSkybox) {
  101675. this._skybox.dispose();
  101676. this._skybox = null;
  101677. }
  101678. if (this._skyboxMaterial && !newOptions.createSkybox) {
  101679. this._skyboxMaterial.dispose();
  101680. this._skyboxMaterial = null;
  101681. }
  101682. if (this._skyboxTexture) {
  101683. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  101684. this._skyboxTexture.dispose();
  101685. this._skyboxTexture = null;
  101686. }
  101687. }
  101688. if (this._groundMirror && !newOptions.enableGroundMirror) {
  101689. this._groundMirror.dispose();
  101690. this._groundMirror = null;
  101691. }
  101692. if (this._scene.environmentTexture) {
  101693. if (this._options.environmentTexture != newOptions.environmentTexture) {
  101694. this._scene.environmentTexture.dispose();
  101695. }
  101696. }
  101697. this._options = newOptions;
  101698. this._setupBackground();
  101699. this._setupImageProcessing();
  101700. };
  101701. /**
  101702. * Sets the primary color of all the available elements.
  101703. * @param color the main color to affect to the ground and the background
  101704. */
  101705. EnvironmentHelper.prototype.setMainColor = function (color) {
  101706. if (this.groundMaterial) {
  101707. this.groundMaterial.primaryColor = color;
  101708. }
  101709. if (this.skyboxMaterial) {
  101710. this.skyboxMaterial.primaryColor = color;
  101711. }
  101712. if (this.groundMirror) {
  101713. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  101714. }
  101715. };
  101716. /**
  101717. * Setup the image processing according to the specified options.
  101718. */
  101719. EnvironmentHelper.prototype._setupImageProcessing = function () {
  101720. if (this._options.setupImageProcessing) {
  101721. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  101722. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  101723. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  101724. this._setupEnvironmentTexture();
  101725. }
  101726. };
  101727. /**
  101728. * Setup the environment texture according to the specified options.
  101729. */
  101730. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  101731. if (this._scene.environmentTexture) {
  101732. return;
  101733. }
  101734. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  101735. this._scene.environmentTexture = this._options.environmentTexture;
  101736. return;
  101737. }
  101738. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  101739. this._scene.environmentTexture = environmentTexture;
  101740. };
  101741. /**
  101742. * Setup the background according to the specified options.
  101743. */
  101744. EnvironmentHelper.prototype._setupBackground = function () {
  101745. if (!this._rootMesh) {
  101746. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  101747. }
  101748. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  101749. var sceneSize = this._getSceneSize();
  101750. if (this._options.createGround) {
  101751. this._setupGround(sceneSize);
  101752. this._setupGroundMaterial();
  101753. this._setupGroundDiffuseTexture();
  101754. if (this._options.enableGroundMirror) {
  101755. this._setupGroundMirrorTexture(sceneSize);
  101756. }
  101757. this._setupMirrorInGroundMaterial();
  101758. }
  101759. if (this._options.createSkybox) {
  101760. this._setupSkybox(sceneSize);
  101761. this._setupSkyboxMaterial();
  101762. this._setupSkyboxReflectionTexture();
  101763. }
  101764. this._rootMesh.position.x = sceneSize.rootPosition.x;
  101765. this._rootMesh.position.z = sceneSize.rootPosition.z;
  101766. this._rootMesh.position.y = sceneSize.rootPosition.y;
  101767. };
  101768. /**
  101769. * Get the scene sizes according to the setup.
  101770. */
  101771. EnvironmentHelper.prototype._getSceneSize = function () {
  101772. var _this = this;
  101773. var groundSize = this._options.groundSize;
  101774. var skyboxSize = this._options.skyboxSize;
  101775. var rootPosition = this._options.rootPosition;
  101776. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  101777. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101778. }
  101779. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  101780. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  101781. });
  101782. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  101783. if (this._options.sizeAuto) {
  101784. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  101785. this._scene.activeCamera.upperRadiusLimit) {
  101786. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  101787. skyboxSize = groundSize;
  101788. }
  101789. var sceneDiagonalLenght = sceneDiagonal.length();
  101790. if (sceneDiagonalLenght > groundSize) {
  101791. groundSize = sceneDiagonalLenght * 2;
  101792. skyboxSize = groundSize;
  101793. }
  101794. // 10 % bigger.
  101795. groundSize *= 1.1;
  101796. skyboxSize *= 1.5;
  101797. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  101798. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  101799. }
  101800. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101801. };
  101802. /**
  101803. * Setup the ground according to the specified options.
  101804. */
  101805. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  101806. var _this = this;
  101807. if (!this._ground || this._ground.isDisposed()) {
  101808. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  101809. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  101810. this._ground.parent = this._rootMesh;
  101811. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  101812. }
  101813. this._ground.receiveShadows = this._options.enableGroundShadow;
  101814. };
  101815. /**
  101816. * Setup the ground material according to the specified options.
  101817. */
  101818. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  101819. if (!this._groundMaterial) {
  101820. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  101821. }
  101822. this._groundMaterial.alpha = this._options.groundOpacity;
  101823. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  101824. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  101825. this._groundMaterial.primaryColor = this._options.groundColor;
  101826. this._groundMaterial.useRGBColor = false;
  101827. this._groundMaterial.enableNoise = true;
  101828. if (this._ground) {
  101829. this._ground.material = this._groundMaterial;
  101830. }
  101831. };
  101832. /**
  101833. * Setup the ground diffuse texture according to the specified options.
  101834. */
  101835. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  101836. if (!this._groundMaterial) {
  101837. return;
  101838. }
  101839. if (this._groundTexture) {
  101840. return;
  101841. }
  101842. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  101843. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  101844. return;
  101845. }
  101846. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101847. diffuseTexture.gammaSpace = false;
  101848. diffuseTexture.hasAlpha = true;
  101849. this._groundMaterial.diffuseTexture = diffuseTexture;
  101850. };
  101851. /**
  101852. * Setup the ground mirror texture according to the specified options.
  101853. */
  101854. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  101855. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  101856. if (!this._groundMirror) {
  101857. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  101858. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  101859. this._groundMirror.anisotropicFilteringLevel = 1;
  101860. this._groundMirror.wrapU = wrapping;
  101861. this._groundMirror.wrapV = wrapping;
  101862. this._groundMirror.gammaSpace = false;
  101863. if (this._groundMirror.renderList) {
  101864. for (var i = 0; i < this._scene.meshes.length; i++) {
  101865. var mesh = this._scene.meshes[i];
  101866. if (mesh !== this._ground &&
  101867. mesh !== this._skybox &&
  101868. mesh !== this._rootMesh) {
  101869. this._groundMirror.renderList.push(mesh);
  101870. }
  101871. }
  101872. }
  101873. }
  101874. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  101875. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  101876. };
  101877. /**
  101878. * Setup the ground to receive the mirror texture.
  101879. */
  101880. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  101881. if (this._groundMaterial) {
  101882. this._groundMaterial.reflectionTexture = this._groundMirror;
  101883. this._groundMaterial.reflectionFresnel = true;
  101884. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  101885. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  101886. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  101887. }
  101888. };
  101889. /**
  101890. * Setup the skybox according to the specified options.
  101891. */
  101892. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  101893. var _this = this;
  101894. if (!this._skybox || this._skybox.isDisposed()) {
  101895. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  101896. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  101897. }
  101898. this._skybox.parent = this._rootMesh;
  101899. };
  101900. /**
  101901. * Setup the skybox material according to the specified options.
  101902. */
  101903. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  101904. if (!this._skybox) {
  101905. return;
  101906. }
  101907. if (!this._skyboxMaterial) {
  101908. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  101909. }
  101910. this._skyboxMaterial.useRGBColor = false;
  101911. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  101912. this._skyboxMaterial.enableNoise = true;
  101913. this._skybox.material = this._skyboxMaterial;
  101914. };
  101915. /**
  101916. * Setup the skybox reflection texture according to the specified options.
  101917. */
  101918. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  101919. if (!this._skyboxMaterial) {
  101920. return;
  101921. }
  101922. if (this._skyboxTexture) {
  101923. return;
  101924. }
  101925. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  101926. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  101927. return;
  101928. }
  101929. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  101930. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  101931. this._skyboxTexture.gammaSpace = false;
  101932. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  101933. };
  101934. /**
  101935. * Dispose all the elements created by the Helper.
  101936. */
  101937. EnvironmentHelper.prototype.dispose = function () {
  101938. if (this._groundMaterial) {
  101939. this._groundMaterial.dispose(true, true);
  101940. }
  101941. if (this._skyboxMaterial) {
  101942. this._skyboxMaterial.dispose(true, true);
  101943. }
  101944. this._rootMesh.dispose(false);
  101945. };
  101946. /**
  101947. * Default ground texture URL.
  101948. */
  101949. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  101950. /**
  101951. * Default skybox texture URL.
  101952. */
  101953. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  101954. /**
  101955. * Default environment texture URL.
  101956. */
  101957. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  101958. return EnvironmentHelper;
  101959. }());
  101960. BABYLON.EnvironmentHelper = EnvironmentHelper;
  101961. })(BABYLON || (BABYLON = {}));
  101962. //# sourceMappingURL=babylon.environmentHelper.js.map
  101963. var BABYLON;
  101964. (function (BABYLON) {
  101965. /** Internal class used to store shapes for emitters */
  101966. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  101967. function ParticleSystemSetEmitterCreationOptions() {
  101968. }
  101969. return ParticleSystemSetEmitterCreationOptions;
  101970. }());
  101971. /**
  101972. * Represents a set of particle systems working together to create a specific effect
  101973. */
  101974. var ParticleSystemSet = /** @class */ (function () {
  101975. function ParticleSystemSet() {
  101976. /**
  101977. * Gets the particle system list
  101978. */
  101979. this.systems = new Array();
  101980. }
  101981. Object.defineProperty(ParticleSystemSet.prototype, "emitterMesh", {
  101982. /**
  101983. * Gets the emitter mesh used with this set
  101984. */
  101985. get: function () {
  101986. return this._emitterMesh;
  101987. },
  101988. enumerable: true,
  101989. configurable: true
  101990. });
  101991. /**
  101992. * Creates a new emitter mesh as a sphere
  101993. * @param options defines the options used to create the sphere
  101994. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  101995. * @param scene defines the hosting scene
  101996. */
  101997. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  101998. if (this._emitterMesh) {
  101999. this._emitterMesh.dispose();
  102000. }
  102001. this._emitterCreationOptions = {
  102002. kind: "Sphere",
  102003. options: options,
  102004. renderingGroupId: renderingGroupId
  102005. };
  102006. this._emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  102007. this._emitterMesh.renderingGroupId = renderingGroupId;
  102008. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  102009. material.emissiveColor = options.color;
  102010. this._emitterMesh.material = material;
  102011. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102012. var system = _a[_i];
  102013. system.emitter = this._emitterMesh;
  102014. }
  102015. };
  102016. /**
  102017. * Starts all particle systems of the set
  102018. * @param emitter defines an optional mesh to use as emitter for the particle systems
  102019. */
  102020. ParticleSystemSet.prototype.start = function (emitter) {
  102021. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102022. var system = _a[_i];
  102023. if (emitter) {
  102024. system.emitter = emitter;
  102025. }
  102026. system.start();
  102027. }
  102028. };
  102029. /**
  102030. * Release all associated resources
  102031. */
  102032. ParticleSystemSet.prototype.dispose = function () {
  102033. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102034. var system = _a[_i];
  102035. system.dispose();
  102036. }
  102037. this.systems = [];
  102038. if (this._emitterMesh) {
  102039. this._emitterMesh.dispose();
  102040. this._emitterMesh = null;
  102041. }
  102042. };
  102043. /**
  102044. * Serialize the set into a JSON compatible object
  102045. * @returns a JSON compatible representation of the set
  102046. */
  102047. ParticleSystemSet.prototype.serialize = function () {
  102048. var result = {};
  102049. result.systems = [];
  102050. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102051. var system = _a[_i];
  102052. result.systems.push(system.serialize());
  102053. }
  102054. if (this._emitterMesh) {
  102055. result.emitter = this._emitterCreationOptions;
  102056. }
  102057. return result;
  102058. };
  102059. /**
  102060. * Parse a new ParticleSystemSet from a serialized source
  102061. * @param data defines a JSON compatible representation of the set
  102062. * @param scene defines the hosting scene
  102063. * @param gpu defines if we want GPU particles or CPU particles
  102064. * @returns a new ParticleSystemSet
  102065. */
  102066. ParticleSystemSet.Parse = function (data, scene, gpu) {
  102067. if (gpu === void 0) { gpu = false; }
  102068. var result = new ParticleSystemSet();
  102069. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  102070. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  102071. var system = _a[_i];
  102072. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  102073. }
  102074. if (data.emitter) {
  102075. var options = data.emitter.options;
  102076. switch (data.emitter.kind) {
  102077. case "Sphere":
  102078. result.setEmitterAsSphere({
  102079. diameter: options.diameter,
  102080. segments: options.segments,
  102081. color: BABYLON.Color3.FromArray(options.color)
  102082. }, data.emitter.renderingGroupId, scene);
  102083. break;
  102084. }
  102085. }
  102086. return result;
  102087. };
  102088. return ParticleSystemSet;
  102089. }());
  102090. BABYLON.ParticleSystemSet = ParticleSystemSet;
  102091. })(BABYLON || (BABYLON = {}));
  102092. //# sourceMappingURL=babylon.particleSystemSet.js.map
  102093. var BABYLON;
  102094. (function (BABYLON) {
  102095. /**
  102096. * This class is made for on one-liner static method to help creating particle system set.
  102097. */
  102098. var ParticleHelper = /** @class */ (function () {
  102099. function ParticleHelper() {
  102100. }
  102101. /**
  102102. * This is the main static method (one-liner) of this helper to create different particle systems
  102103. * @param type This string represents the type to the particle system to create
  102104. * @param scene The scene where the particle system should live
  102105. * @param gpu If the system will use gpu
  102106. * @returns the ParticleSystemSet created
  102107. */
  102108. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  102109. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  102110. if (gpu === void 0) { gpu = false; }
  102111. return new Promise(function (resolve, reject) {
  102112. if (!scene) {
  102113. scene = BABYLON.Engine.LastCreatedScene;
  102114. ;
  102115. }
  102116. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  102117. return reject("Particle system with GPU is not supported.");
  102118. }
  102119. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  102120. var newData = JSON.parse(data.toString());
  102121. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  102122. }, undefined, undefined, undefined, function (req, exception) {
  102123. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  102124. });
  102125. });
  102126. };
  102127. /**
  102128. * Static function used to export a particle system to a ParticleSystemSet variable.
  102129. * Please note that the emitter shape is not exported
  102130. * @param system defines the particle systems to export
  102131. */
  102132. ParticleHelper.ExportSet = function (systems) {
  102133. var set = new BABYLON.ParticleSystemSet();
  102134. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  102135. var system = systems_1[_i];
  102136. set.systems.push(system);
  102137. }
  102138. return set;
  102139. };
  102140. /**
  102141. * Gets or sets base Assets URL
  102142. */
  102143. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  102144. return ParticleHelper;
  102145. }());
  102146. BABYLON.ParticleHelper = ParticleHelper;
  102147. })(BABYLON || (BABYLON = {}));
  102148. //# sourceMappingURL=babylon.particleHelper.js.map
  102149. var BABYLON;
  102150. (function (BABYLON) {
  102151. /**
  102152. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  102153. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  102154. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  102155. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102156. */
  102157. var VideoDome = /** @class */ (function (_super) {
  102158. __extends(VideoDome, _super);
  102159. /**
  102160. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  102161. * @param name Element's name, child elements will append suffixes for their own names.
  102162. * @param urlsOrVideo defines the url(s) or the video element to use
  102163. * @param options An object containing optional or exposed sub element properties
  102164. */
  102165. function VideoDome(name, urlsOrVideo, options, scene) {
  102166. var _this = _super.call(this, name, scene) || this;
  102167. _this._useDirectMapping = false;
  102168. // set defaults and manage values
  102169. name = name || "videoDome";
  102170. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102171. options.clickToPlay = Boolean(options.clickToPlay);
  102172. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  102173. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  102174. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102175. if (options.useDirectMapping === undefined) {
  102176. _this._useDirectMapping = true;
  102177. }
  102178. else {
  102179. _this._useDirectMapping = options.useDirectMapping;
  102180. }
  102181. // create
  102182. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  102183. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102184. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  102185. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102186. // configure material
  102187. material.useEquirectangularFOV = true;
  102188. material.fovMultiplier = 1.0;
  102189. material.opacityFresnel = false;
  102190. if (_this._useDirectMapping) {
  102191. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102192. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102193. material.diffuseTexture = texture;
  102194. }
  102195. else {
  102196. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102197. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102198. material.reflectionTexture = texture;
  102199. }
  102200. // configure mesh
  102201. _this._mesh.material = material;
  102202. _this._mesh.parent = _this;
  102203. // optional configuration
  102204. if (options.clickToPlay) {
  102205. scene.onPointerUp = function () {
  102206. _this._videoTexture.video.play();
  102207. };
  102208. }
  102209. return _this;
  102210. }
  102211. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  102212. /**
  102213. * Gets the video texture being displayed on the sphere
  102214. */
  102215. get: function () {
  102216. return this._videoTexture;
  102217. },
  102218. enumerable: true,
  102219. configurable: true
  102220. });
  102221. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  102222. /**
  102223. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102224. * Also see the options.resolution property.
  102225. */
  102226. get: function () {
  102227. return this._material.fovMultiplier;
  102228. },
  102229. set: function (value) {
  102230. this._material.fovMultiplier = value;
  102231. },
  102232. enumerable: true,
  102233. configurable: true
  102234. });
  102235. /**
  102236. * Releases resources associated with this node.
  102237. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102238. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102239. */
  102240. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102241. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102242. this._videoTexture.dispose();
  102243. this._mesh.dispose();
  102244. this._material.dispose();
  102245. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102246. };
  102247. return VideoDome;
  102248. }(BABYLON.Node));
  102249. BABYLON.VideoDome = VideoDome;
  102250. })(BABYLON || (BABYLON = {}));
  102251. //# sourceMappingURL=babylon.videoDome.js.map
  102252. var BABYLON;
  102253. (function (BABYLON) {
  102254. /**
  102255. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  102256. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  102257. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  102258. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102259. */
  102260. var PhotoDome = /** @class */ (function (_super) {
  102261. __extends(PhotoDome, _super);
  102262. /**
  102263. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  102264. * @param name Element's name, child elements will append suffixes for their own names.
  102265. * @param urlsOfPhoto define the url of the photo to display
  102266. * @param options An object containing optional or exposed sub element properties
  102267. */
  102268. function PhotoDome(name, urlOfPhoto, options, scene) {
  102269. var _this = _super.call(this, name, scene) || this;
  102270. _this._useDirectMapping = false;
  102271. // set defaults and manage values
  102272. name = name || "photoDome";
  102273. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102274. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102275. if (options.useDirectMapping === undefined) {
  102276. _this._useDirectMapping = true;
  102277. }
  102278. else {
  102279. _this._useDirectMapping = options.useDirectMapping;
  102280. }
  102281. // create
  102282. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102283. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102284. // configure material
  102285. material.opacityFresnel = false;
  102286. material.useEquirectangularFOV = true;
  102287. material.fovMultiplier = 1.0;
  102288. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  102289. // configure mesh
  102290. _this._mesh.material = material;
  102291. _this._mesh.parent = _this;
  102292. return _this;
  102293. }
  102294. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  102295. /**
  102296. * Gets or sets the texture being displayed on the sphere
  102297. */
  102298. get: function () {
  102299. return this._photoTexture;
  102300. },
  102301. set: function (value) {
  102302. if (this._photoTexture === value) {
  102303. return;
  102304. }
  102305. this._photoTexture = value;
  102306. if (this._useDirectMapping) {
  102307. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102308. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102309. this._material.diffuseTexture = this._photoTexture;
  102310. }
  102311. else {
  102312. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102313. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102314. this._material.reflectionTexture = this._photoTexture;
  102315. }
  102316. },
  102317. enumerable: true,
  102318. configurable: true
  102319. });
  102320. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  102321. /**
  102322. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102323. * Also see the options.resolution property.
  102324. */
  102325. get: function () {
  102326. return this._material.fovMultiplier;
  102327. },
  102328. set: function (value) {
  102329. this._material.fovMultiplier = value;
  102330. },
  102331. enumerable: true,
  102332. configurable: true
  102333. });
  102334. /**
  102335. * Releases resources associated with this node.
  102336. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102337. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102338. */
  102339. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102340. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102341. this._photoTexture.dispose();
  102342. this._mesh.dispose();
  102343. this._material.dispose();
  102344. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102345. };
  102346. return PhotoDome;
  102347. }(BABYLON.Node));
  102348. BABYLON.PhotoDome = PhotoDome;
  102349. })(BABYLON || (BABYLON = {}));
  102350. //# sourceMappingURL=babylon.photoDome.js.map
  102351. 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;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\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\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=offset*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#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\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;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\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=texture(sizeGradientSampler,vec2(0,0)).r;\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\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#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\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\noutSize.x=texture(sizeGradientSampler,vec2(age/life,0)).r;\noutSize.yz=size.yz;\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#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(((outAge*cellInfos.z)/life),life),0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","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"};
  102352. 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};"};