babylon.no-module.max.js 4.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709
  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. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "key", {
  240. /**
  241. * Unique key for this effect
  242. */
  243. get: function () {
  244. return this._key;
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. /**
  250. * If the effect has been compiled and prepared.
  251. * @returns if the effect is compiled and prepared.
  252. */
  253. Effect.prototype.isReady = function () {
  254. return this._isReady;
  255. };
  256. /**
  257. * The engine the effect was initialized with.
  258. * @returns the engine.
  259. */
  260. Effect.prototype.getEngine = function () {
  261. return this._engine;
  262. };
  263. /**
  264. * The compiled webGL program for the effect
  265. * @returns the webGL program.
  266. */
  267. Effect.prototype.getProgram = function () {
  268. return this._program;
  269. };
  270. /**
  271. * The set of names of attribute variables for the shader.
  272. * @returns An array of attribute names.
  273. */
  274. Effect.prototype.getAttributesNames = function () {
  275. return this._attributesNames;
  276. };
  277. /**
  278. * Returns the attribute at the given index.
  279. * @param index The index of the attribute.
  280. * @returns The location of the attribute.
  281. */
  282. Effect.prototype.getAttributeLocation = function (index) {
  283. return this._attributes[index];
  284. };
  285. /**
  286. * Returns the attribute based on the name of the variable.
  287. * @param name of the attribute to look up.
  288. * @returns the attribute location.
  289. */
  290. Effect.prototype.getAttributeLocationByName = function (name) {
  291. var index = this._attributesNames.indexOf(name);
  292. return this._attributes[index];
  293. };
  294. /**
  295. * The number of attributes.
  296. * @returns the numnber of attributes.
  297. */
  298. Effect.prototype.getAttributesCount = function () {
  299. return this._attributes.length;
  300. };
  301. /**
  302. * Gets the index of a uniform variable.
  303. * @param uniformName of the uniform to look up.
  304. * @returns the index.
  305. */
  306. Effect.prototype.getUniformIndex = function (uniformName) {
  307. return this._uniformsNames.indexOf(uniformName);
  308. };
  309. /**
  310. * Returns the attribute based on the name of the variable.
  311. * @param uniformName of the uniform to look up.
  312. * @returns the location of the uniform.
  313. */
  314. Effect.prototype.getUniform = function (uniformName) {
  315. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  316. };
  317. /**
  318. * Returns an array of sampler variable names
  319. * @returns The array of sampler variable neames.
  320. */
  321. Effect.prototype.getSamplers = function () {
  322. return this._samplers;
  323. };
  324. /**
  325. * The error from the last compilation.
  326. * @returns the error string.
  327. */
  328. Effect.prototype.getCompilationError = function () {
  329. return this._compilationError;
  330. };
  331. /**
  332. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  333. * @param func The callback to be used.
  334. */
  335. Effect.prototype.executeWhenCompiled = function (func) {
  336. if (this.isReady()) {
  337. func(this);
  338. return;
  339. }
  340. this.onCompileObservable.add(function (effect) {
  341. func(effect);
  342. });
  343. };
  344. /** @ignore */
  345. Effect.prototype._loadVertexShader = function (vertex, callback) {
  346. if (BABYLON.Tools.IsWindowObjectExist()) {
  347. // DOM element ?
  348. if (vertex instanceof HTMLElement) {
  349. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  350. callback(vertexCode);
  351. return;
  352. }
  353. }
  354. // Base64 encoded ?
  355. if (vertex.substr(0, 7) === "base64:") {
  356. var vertexBinary = window.atob(vertex.substr(7));
  357. callback(vertexBinary);
  358. return;
  359. }
  360. // Is in local store ?
  361. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  362. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  363. return;
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  374. };
  375. /** @ignore */
  376. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. callback(fragmentCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (fragment.substr(0, 7) === "base64:") {
  387. var fragmentBinary = window.atob(fragment.substr(7));
  388. callback(fragmentBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  393. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  394. return;
  395. }
  396. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  397. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  398. return;
  399. }
  400. var fragmentShaderUrl;
  401. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  402. fragmentShaderUrl = fragment;
  403. }
  404. else {
  405. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  406. }
  407. // Fragment shader
  408. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  409. };
  410. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  411. // Rebuild shaders source code
  412. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  413. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  414. vertexCode = prefix + vertexCode;
  415. fragmentCode = prefix + fragmentCode;
  416. // Number lines of shaders source code
  417. var i = 2;
  418. var regex = /\n/gm;
  419. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  420. i = 2;
  421. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  422. // Dump shaders name and formatted source code
  423. if (this.name.vertexElement) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  426. }
  427. else if (this.name.vertex) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  430. }
  431. else {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  434. }
  435. };
  436. ;
  437. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  438. var preparedSourceCode = this._processPrecision(sourceCode);
  439. if (this._engine.webGLVersion == 1) {
  440. callback(preparedSourceCode);
  441. return;
  442. }
  443. // Already converted
  444. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  445. callback(preparedSourceCode.replace("#version 300 es", ""));
  446. return;
  447. }
  448. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  449. // Remove extensions
  450. // #extension GL_OES_standard_derivatives : enable
  451. // #extension GL_EXT_shader_texture_lod : enable
  452. // #extension GL_EXT_frag_depth : enable
  453. // #extension GL_EXT_draw_buffers : require
  454. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  455. var result = preparedSourceCode.replace(regex, "");
  456. // Migrate to GLSL v300
  457. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  458. result = result.replace(/attribute[ \t]/g, "in ");
  459. result = result.replace(/[ \t]attribute/g, " in");
  460. if (isFragment) {
  461. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  462. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/texture2D\s*\(/g, "texture(");
  464. result = result.replace(/textureCube\s*\(/g, "texture(");
  465. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  466. result = result.replace(/gl_FragColor/g, "glFragColor");
  467. result = result.replace(/gl_FragData/g, "glFragData");
  468. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  469. }
  470. callback(result);
  471. };
  472. Effect.prototype._processIncludes = function (sourceCode, callback) {
  473. var _this = this;
  474. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  475. var match = regex.exec(sourceCode);
  476. var returnValue = new String(sourceCode);
  477. while (match != null) {
  478. var includeFile = match[1];
  479. // Uniform declaration
  480. if (includeFile.indexOf("__decl__") !== -1) {
  481. includeFile = includeFile.replace(/__decl__/, "");
  482. if (this._engine.supportsUniformBuffers) {
  483. includeFile = includeFile.replace(/Vertex/, "Ubo");
  484. includeFile = includeFile.replace(/Fragment/, "Ubo");
  485. }
  486. includeFile = includeFile + "Declaration";
  487. }
  488. if (Effect.IncludesShadersStore[includeFile]) {
  489. // Substitution
  490. var includeContent = Effect.IncludesShadersStore[includeFile];
  491. if (match[2]) {
  492. var splits = match[3].split(",");
  493. for (var index = 0; index < splits.length; index += 2) {
  494. var source = new RegExp(splits[index], "g");
  495. var dest = splits[index + 1];
  496. includeContent = includeContent.replace(source, dest);
  497. }
  498. }
  499. if (match[4]) {
  500. var indexString = match[5];
  501. if (indexString.indexOf("..") !== -1) {
  502. var indexSplits = indexString.split("..");
  503. var minIndex = parseInt(indexSplits[0]);
  504. var maxIndex = parseInt(indexSplits[1]);
  505. var sourceIncludeContent = includeContent.slice(0);
  506. includeContent = "";
  507. if (isNaN(maxIndex)) {
  508. maxIndex = this._indexParameters[indexSplits[1]];
  509. }
  510. for (var i = minIndex; i < maxIndex; i++) {
  511. if (!this._engine.supportsUniformBuffers) {
  512. // Ubo replacement
  513. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  514. return p1 + "{X}";
  515. });
  516. }
  517. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  518. }
  519. }
  520. else {
  521. if (!this._engine.supportsUniformBuffers) {
  522. // Ubo replacement
  523. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  524. return p1 + "{X}";
  525. });
  526. }
  527. includeContent = includeContent.replace(/\{X\}/g, indexString);
  528. }
  529. }
  530. // Replace
  531. returnValue = returnValue.replace(match[0], includeContent);
  532. }
  533. else {
  534. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  535. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  536. Effect.IncludesShadersStore[includeFile] = fileContent;
  537. _this._processIncludes(returnValue, callback);
  538. });
  539. return;
  540. }
  541. match = regex.exec(sourceCode);
  542. }
  543. callback(returnValue);
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else { // Sorry we did everything we can
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  714. * @param channel Name of the sampler variable.
  715. * @param texture Texture to set.
  716. */
  717. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  718. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  719. };
  720. /**
  721. * Sets an array of textures on the engine to be used in the shader.
  722. * @param channel Name of the variable.
  723. * @param textures Textures to set.
  724. */
  725. Effect.prototype.setTextureArray = function (channel, textures) {
  726. if (this._samplers.indexOf(channel + "Ex") === -1) {
  727. var initialPos = this._samplers.indexOf(channel);
  728. for (var index = 1; index < textures.length; index++) {
  729. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  730. }
  731. }
  732. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  733. };
  734. /**
  735. * 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)
  736. * @param channel Name of the sampler variable.
  737. * @param postProcess Post process to get the input texture from.
  738. */
  739. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  740. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  741. };
  742. /**
  743. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  744. * 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)
  745. * @param channel Name of the sampler variable.
  746. * @param postProcess Post process to get the output texture from.
  747. */
  748. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  749. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  750. };
  751. /** @ignore */
  752. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  753. var cache = this._valueCache[uniformName];
  754. var flag = matrix.updateFlag;
  755. if (cache !== undefined && cache === flag) {
  756. return false;
  757. }
  758. this._valueCache[uniformName] = flag;
  759. return true;
  760. };
  761. /** @ignore */
  762. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  763. var cache = this._valueCache[uniformName];
  764. if (!cache) {
  765. cache = [x, y];
  766. this._valueCache[uniformName] = cache;
  767. return true;
  768. }
  769. var changed = false;
  770. if (cache[0] !== x) {
  771. cache[0] = x;
  772. changed = true;
  773. }
  774. if (cache[1] !== y) {
  775. cache[1] = y;
  776. changed = true;
  777. }
  778. return changed;
  779. };
  780. /** @ignore */
  781. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  782. var cache = this._valueCache[uniformName];
  783. if (!cache) {
  784. cache = [x, y, z];
  785. this._valueCache[uniformName] = cache;
  786. return true;
  787. }
  788. var changed = false;
  789. if (cache[0] !== x) {
  790. cache[0] = x;
  791. changed = true;
  792. }
  793. if (cache[1] !== y) {
  794. cache[1] = y;
  795. changed = true;
  796. }
  797. if (cache[2] !== z) {
  798. cache[2] = z;
  799. changed = true;
  800. }
  801. return changed;
  802. };
  803. /** @ignore */
  804. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y, z, w];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. if (cache[2] !== z) {
  821. cache[2] = z;
  822. changed = true;
  823. }
  824. if (cache[3] !== w) {
  825. cache[3] = w;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /**
  831. * Binds a buffer to a uniform.
  832. * @param buffer Buffer to bind.
  833. * @param name Name of the uniform variable to bind to.
  834. */
  835. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  836. var bufferName = this._uniformBuffersNames[name];
  837. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  838. return;
  839. }
  840. Effect._baseCache[bufferName] = buffer;
  841. this._engine.bindUniformBufferBase(buffer, bufferName);
  842. };
  843. /**
  844. * Binds block to a uniform.
  845. * @param blockName Name of the block to bind.
  846. * @param index Index to bind.
  847. */
  848. Effect.prototype.bindUniformBlock = function (blockName, index) {
  849. this._engine.bindUniformBlock(this._program, blockName, index);
  850. };
  851. /**
  852. * Sets an interger value on a uniform variable.
  853. * @param uniformName Name of the variable.
  854. * @param value Value to be set.
  855. * @returns this effect.
  856. */
  857. Effect.prototype.setInt = function (uniformName, value) {
  858. var cache = this._valueCache[uniformName];
  859. if (cache !== undefined && cache === value)
  860. return this;
  861. this._valueCache[uniformName] = value;
  862. this._engine.setInt(this.getUniform(uniformName), value);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array on a uniform variable.
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * 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)
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setIntArray2 = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setIntArray2(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * 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)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setIntArray3 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setIntArray3(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * 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)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setIntArray4 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setIntArray4(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array on a uniform variable.
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * 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)
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * 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)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * 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)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array on a uniform variable.
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * 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)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setArray2 = function (uniformName, array) {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setArray2(this.getUniform(uniformName), array);
  973. return this;
  974. };
  975. /**
  976. * 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)
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setArray3 = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setArray3(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * 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)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setArray4 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setArray4(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * Sets matrices on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param matrices matrices to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1004. if (!matrices) {
  1005. return this;
  1006. }
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets matrix on a uniform variable.
  1013. * @param uniformName Name of the variable.
  1014. * @param matrix matrix to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1018. if (this._cacheMatrix(uniformName, matrix)) {
  1019. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1020. }
  1021. return this;
  1022. };
  1023. /**
  1024. * 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)
  1025. * @param uniformName Name of the variable.
  1026. * @param matrix matrix to be set.
  1027. * @returns this effect.
  1028. */
  1029. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1030. this._valueCache[uniformName] = null;
  1031. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1032. return this;
  1033. };
  1034. /**
  1035. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1036. * @param uniformName Name of the variable.
  1037. * @param matrix matrix to be set.
  1038. * @returns this effect.
  1039. */
  1040. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1041. this._valueCache[uniformName] = null;
  1042. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1043. return this;
  1044. };
  1045. /**
  1046. * Sets a float on a uniform variable.
  1047. * @param uniformName Name of the variable.
  1048. * @param value value to be set.
  1049. * @returns this effect.
  1050. */
  1051. Effect.prototype.setFloat = function (uniformName, value) {
  1052. var cache = this._valueCache[uniformName];
  1053. if (cache !== undefined && cache === value)
  1054. return this;
  1055. this._valueCache[uniformName] = value;
  1056. this._engine.setFloat(this.getUniform(uniformName), value);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a boolean on a uniform variable.
  1061. * @param uniformName Name of the variable.
  1062. * @param bool value to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setBool = function (uniformName, bool) {
  1066. var cache = this._valueCache[uniformName];
  1067. if (cache !== undefined && cache === bool)
  1068. return this;
  1069. this._valueCache[uniformName] = bool;
  1070. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a Vector2 on a uniform variable.
  1075. * @param uniformName Name of the variable.
  1076. * @param vector2 vector2 to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1080. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1081. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1082. }
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float2 on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param x First float in float2.
  1089. * @param y Second float in float2.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1093. if (this._cacheFloat2(uniformName, x, y)) {
  1094. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1095. }
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector3 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector3 Value to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1105. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1106. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float3 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float3.
  1114. * @param y Second float in float3.
  1115. * @param z Third float in float3.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1119. if (this._cacheFloat3(uniformName, x, y, z)) {
  1120. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1121. }
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets a Vector4 on a uniform variable.
  1126. * @param uniformName Name of the variable.
  1127. * @param vector4 Value to be set.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1131. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1132. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1133. }
  1134. return this;
  1135. };
  1136. /**
  1137. * Sets a float4 on a uniform variable.
  1138. * @param uniformName Name of the variable.
  1139. * @param x First float in float4.
  1140. * @param y Second float in float4.
  1141. * @param z Third float in float4.
  1142. * @param w Fourth float in float4.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1146. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Color3 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param color3 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setColor3 = function (uniformName, color3) {
  1158. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1159. this._engine.setColor3(this.getUniform(uniformName), color3);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Color4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param color3 Value to be set.
  1167. * @param alpha Alpha value to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1171. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1172. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color4 on a uniform variable
  1178. * @param uniformName defines the name of the variable
  1179. * @param color4 defines the value to be set
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1183. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1184. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Resets the cache of effects.
  1190. */
  1191. Effect.ResetCache = function () {
  1192. Effect._baseCache = {};
  1193. };
  1194. Effect._uniqueIdSeed = 0;
  1195. Effect._baseCache = {};
  1196. /**
  1197. * Store of each shader (The can be looked up using effect.key)
  1198. */
  1199. Effect.ShadersStore = {};
  1200. /**
  1201. * Store of each included file for a shader (The can be looked up using effect.key)
  1202. */
  1203. Effect.IncludesShadersStore = {};
  1204. return Effect;
  1205. }());
  1206. BABYLON.Effect = Effect;
  1207. })(BABYLON || (BABYLON = {}));
  1208. //# sourceMappingURL=babylon.effect.js.map
  1209. //# sourceMappingURL=babylon.types.js.map
  1210. var BABYLON;
  1211. (function (BABYLON) {
  1212. var KeyboardEventTypes = /** @class */ (function () {
  1213. function KeyboardEventTypes() {
  1214. }
  1215. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1216. get: function () {
  1217. return KeyboardEventTypes._KEYDOWN;
  1218. },
  1219. enumerable: true,
  1220. configurable: true
  1221. });
  1222. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1223. get: function () {
  1224. return KeyboardEventTypes._KEYUP;
  1225. },
  1226. enumerable: true,
  1227. configurable: true
  1228. });
  1229. KeyboardEventTypes._KEYDOWN = 0x01;
  1230. KeyboardEventTypes._KEYUP = 0x02;
  1231. return KeyboardEventTypes;
  1232. }());
  1233. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1234. var KeyboardInfo = /** @class */ (function () {
  1235. function KeyboardInfo(type, event) {
  1236. this.type = type;
  1237. this.event = event;
  1238. }
  1239. return KeyboardInfo;
  1240. }());
  1241. BABYLON.KeyboardInfo = KeyboardInfo;
  1242. /**
  1243. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1244. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1245. */
  1246. var KeyboardInfoPre = /** @class */ (function (_super) {
  1247. __extends(KeyboardInfoPre, _super);
  1248. function KeyboardInfoPre(type, event) {
  1249. var _this = _super.call(this, type, event) || this;
  1250. _this.skipOnPointerObservable = false;
  1251. return _this;
  1252. }
  1253. return KeyboardInfoPre;
  1254. }(KeyboardInfo));
  1255. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1256. })(BABYLON || (BABYLON = {}));
  1257. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1258. var BABYLON;
  1259. (function (BABYLON) {
  1260. var PointerEventTypes = /** @class */ (function () {
  1261. function PointerEventTypes() {
  1262. }
  1263. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1264. get: function () {
  1265. return PointerEventTypes._POINTERDOWN;
  1266. },
  1267. enumerable: true,
  1268. configurable: true
  1269. });
  1270. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1271. get: function () {
  1272. return PointerEventTypes._POINTERUP;
  1273. },
  1274. enumerable: true,
  1275. configurable: true
  1276. });
  1277. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1278. get: function () {
  1279. return PointerEventTypes._POINTERMOVE;
  1280. },
  1281. enumerable: true,
  1282. configurable: true
  1283. });
  1284. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1285. get: function () {
  1286. return PointerEventTypes._POINTERWHEEL;
  1287. },
  1288. enumerable: true,
  1289. configurable: true
  1290. });
  1291. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1292. get: function () {
  1293. return PointerEventTypes._POINTERPICK;
  1294. },
  1295. enumerable: true,
  1296. configurable: true
  1297. });
  1298. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1299. get: function () {
  1300. return PointerEventTypes._POINTERTAP;
  1301. },
  1302. enumerable: true,
  1303. configurable: true
  1304. });
  1305. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1306. get: function () {
  1307. return PointerEventTypes._POINTERDOUBLETAP;
  1308. },
  1309. enumerable: true,
  1310. configurable: true
  1311. });
  1312. PointerEventTypes._POINTERDOWN = 0x01;
  1313. PointerEventTypes._POINTERUP = 0x02;
  1314. PointerEventTypes._POINTERMOVE = 0x04;
  1315. PointerEventTypes._POINTERWHEEL = 0x08;
  1316. PointerEventTypes._POINTERPICK = 0x10;
  1317. PointerEventTypes._POINTERTAP = 0x20;
  1318. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1319. return PointerEventTypes;
  1320. }());
  1321. BABYLON.PointerEventTypes = PointerEventTypes;
  1322. var PointerInfoBase = /** @class */ (function () {
  1323. function PointerInfoBase(type, event) {
  1324. this.type = type;
  1325. this.event = event;
  1326. }
  1327. return PointerInfoBase;
  1328. }());
  1329. BABYLON.PointerInfoBase = PointerInfoBase;
  1330. /**
  1331. * This class is used to store pointer related info for the onPrePointerObservable event.
  1332. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1333. */
  1334. var PointerInfoPre = /** @class */ (function (_super) {
  1335. __extends(PointerInfoPre, _super);
  1336. function PointerInfoPre(type, event, localX, localY) {
  1337. var _this = _super.call(this, type, event) || this;
  1338. _this.skipOnPointerObservable = false;
  1339. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1340. return _this;
  1341. }
  1342. return PointerInfoPre;
  1343. }(PointerInfoBase));
  1344. BABYLON.PointerInfoPre = PointerInfoPre;
  1345. /**
  1346. * This type contains all the data related to a pointer event in Babylon.js.
  1347. * 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.
  1348. */
  1349. var PointerInfo = /** @class */ (function (_super) {
  1350. __extends(PointerInfo, _super);
  1351. function PointerInfo(type, event, pickInfo) {
  1352. var _this = _super.call(this, type, event) || this;
  1353. _this.pickInfo = pickInfo;
  1354. return _this;
  1355. }
  1356. return PointerInfo;
  1357. }(PointerInfoBase));
  1358. BABYLON.PointerInfo = PointerInfo;
  1359. })(BABYLON || (BABYLON = {}));
  1360. //# sourceMappingURL=babylon.pointerEvents.js.map
  1361. var BABYLON;
  1362. (function (BABYLON) {
  1363. BABYLON.ToGammaSpace = 1 / 2.2;
  1364. BABYLON.ToLinearSpace = 2.2;
  1365. BABYLON.Epsilon = 0.001;
  1366. /**
  1367. * Class used to hold a RBG color
  1368. */
  1369. var Color3 = /** @class */ (function () {
  1370. /**
  1371. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1372. * @param r defines the red component (between 0 and 1, default is 0)
  1373. * @param g defines the green component (between 0 and 1, default is 0)
  1374. * @param b defines the blue component (between 0 and 1, default is 0)
  1375. */
  1376. function Color3(
  1377. /**
  1378. * Defines the red component (between 0 and 1, default is 0)
  1379. */
  1380. r,
  1381. /**
  1382. * Defines the green component (between 0 and 1, default is 0)
  1383. */
  1384. g,
  1385. /**
  1386. * Defines the blue component (between 0 and 1, default is 0)
  1387. */
  1388. b) {
  1389. if (r === void 0) { r = 0; }
  1390. if (g === void 0) { g = 0; }
  1391. if (b === void 0) { b = 0; }
  1392. this.r = r;
  1393. this.g = g;
  1394. this.b = b;
  1395. }
  1396. /**
  1397. * Creates a string with the Color3 current values
  1398. * @returns the string representation of the Color3 object
  1399. */
  1400. Color3.prototype.toString = function () {
  1401. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1402. };
  1403. /**
  1404. * Returns the string "Color3"
  1405. * @returns "Color3"
  1406. */
  1407. Color3.prototype.getClassName = function () {
  1408. return "Color3";
  1409. };
  1410. /**
  1411. * Compute the Color3 hash code
  1412. * @returns an unique number that can be used to hash Color3 objects
  1413. */
  1414. Color3.prototype.getHashCode = function () {
  1415. var hash = this.r || 0;
  1416. hash = (hash * 397) ^ (this.g || 0);
  1417. hash = (hash * 397) ^ (this.b || 0);
  1418. return hash;
  1419. };
  1420. // Operators
  1421. /**
  1422. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1423. * @param array defines the array where to store the r,g,b components
  1424. * @param index defines an optional index in the target array to define where to start storing values
  1425. * @returns the current Color3 object
  1426. */
  1427. Color3.prototype.toArray = function (array, index) {
  1428. if (index === undefined) {
  1429. index = 0;
  1430. }
  1431. array[index] = this.r;
  1432. array[index + 1] = this.g;
  1433. array[index + 2] = this.b;
  1434. return this;
  1435. };
  1436. /**
  1437. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1438. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1439. * @returns a new {BABYLON.Color4} object
  1440. */
  1441. Color3.prototype.toColor4 = function (alpha) {
  1442. if (alpha === void 0) { alpha = 1; }
  1443. return new Color4(this.r, this.g, this.b, alpha);
  1444. };
  1445. /**
  1446. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1447. * @returns the new array
  1448. */
  1449. Color3.prototype.asArray = function () {
  1450. var result = new Array();
  1451. this.toArray(result, 0);
  1452. return result;
  1453. };
  1454. /**
  1455. * Returns the luminance value
  1456. * @returns a float value
  1457. */
  1458. Color3.prototype.toLuminance = function () {
  1459. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1460. };
  1461. /**
  1462. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1463. * @param otherColor defines the second operand
  1464. * @returns the new Color3 object
  1465. */
  1466. Color3.prototype.multiply = function (otherColor) {
  1467. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1468. };
  1469. /**
  1470. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1471. * @param otherColor defines the second operand
  1472. * @param result defines the Color3 object where to store the result
  1473. * @returns the current Color3
  1474. */
  1475. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1476. result.r = this.r * otherColor.r;
  1477. result.g = this.g * otherColor.g;
  1478. result.b = this.b * otherColor.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Determines equality between Color3 objects
  1483. * @param otherColor defines the second operand
  1484. * @returns true if the rgb values are equal to the given ones
  1485. */
  1486. Color3.prototype.equals = function (otherColor) {
  1487. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1488. };
  1489. /**
  1490. * Determines equality between the current Color3 object and a set of r,b,g values
  1491. * @param r defines the red component to check
  1492. * @param g defines the green component to check
  1493. * @param b defines the blue component to check
  1494. * @returns true if the rgb values are equal to the given ones
  1495. */
  1496. Color3.prototype.equalsFloats = function (r, g, b) {
  1497. return this.r === r && this.g === g && this.b === b;
  1498. };
  1499. /**
  1500. * Multiplies in place each rgb value by scale
  1501. * @param scale defines the scaling factor
  1502. * @returns the updated Color3
  1503. */
  1504. Color3.prototype.scale = function (scale) {
  1505. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1506. };
  1507. /**
  1508. * Multiplies the rgb values by scale and stores the result into "result"
  1509. * @param scale defines the scaling factor
  1510. * @param result defines the Color3 object where to store the result
  1511. * @returns the unmodified current Color3
  1512. */
  1513. Color3.prototype.scaleToRef = function (scale, result) {
  1514. result.r = this.r * scale;
  1515. result.g = this.g * scale;
  1516. result.b = this.b * scale;
  1517. return this;
  1518. };
  1519. /**
  1520. * Scale the current Color3 values by a factor and add the result to a given Color3
  1521. * @param scale defines the scale factor
  1522. * @param result defines color to store the result into
  1523. * @returns the unmodified current Color3
  1524. */
  1525. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1526. result.r += this.r * scale;
  1527. result.g += this.g * scale;
  1528. result.b += this.b * scale;
  1529. return this;
  1530. };
  1531. /**
  1532. * Clamps the rgb values by the min and max values and stores the result into "result"
  1533. * @param min defines minimum clamping value (default is 0)
  1534. * @param max defines maximum clamping value (default is 1)
  1535. * @param result defines color to store the result into
  1536. * @returns the original Color3
  1537. */
  1538. Color3.prototype.clampToRef = function (min, max, result) {
  1539. if (min === void 0) { min = 0; }
  1540. if (max === void 0) { max = 1; }
  1541. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1542. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1543. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1544. return this;
  1545. };
  1546. /**
  1547. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1548. * @param otherColor defines the second operand
  1549. * @returns the new Color3
  1550. */
  1551. Color3.prototype.add = function (otherColor) {
  1552. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1553. };
  1554. /**
  1555. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1556. * @param otherColor defines the second operand
  1557. * @param result defines Color3 object to store the result into
  1558. * @returns the unmodified current Color3
  1559. */
  1560. Color3.prototype.addToRef = function (otherColor, result) {
  1561. result.r = this.r + otherColor.r;
  1562. result.g = this.g + otherColor.g;
  1563. result.b = this.b + otherColor.b;
  1564. return this;
  1565. };
  1566. /**
  1567. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1568. * @param otherColor defines the second operand
  1569. * @returns the new Color3
  1570. */
  1571. Color3.prototype.subtract = function (otherColor) {
  1572. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1573. };
  1574. /**
  1575. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1576. * @param otherColor defines the second operand
  1577. * @param result defines Color3 object to store the result into
  1578. * @returns the unmodified current Color3
  1579. */
  1580. Color3.prototype.subtractToRef = function (otherColor, result) {
  1581. result.r = this.r - otherColor.r;
  1582. result.g = this.g - otherColor.g;
  1583. result.b = this.b - otherColor.b;
  1584. return this;
  1585. };
  1586. /**
  1587. * Copy the current object
  1588. * @returns a new Color3 copied the current one
  1589. */
  1590. Color3.prototype.clone = function () {
  1591. return new Color3(this.r, this.g, this.b);
  1592. };
  1593. /**
  1594. * Copies the rgb values from the source in the current Color3
  1595. * @param source defines the source Color3 object
  1596. * @returns the updated Color3 object
  1597. */
  1598. Color3.prototype.copyFrom = function (source) {
  1599. this.r = source.r;
  1600. this.g = source.g;
  1601. this.b = source.b;
  1602. return this;
  1603. };
  1604. /**
  1605. * Updates the Color3 rgb values from the given floats
  1606. * @param r defines the red component to read from
  1607. * @param g defines the green component to read from
  1608. * @param b defines the blue component to read from
  1609. * @returns the current Color3 object
  1610. */
  1611. Color3.prototype.copyFromFloats = function (r, g, b) {
  1612. this.r = r;
  1613. this.g = g;
  1614. this.b = b;
  1615. return this;
  1616. };
  1617. /**
  1618. * Updates the Color3 rgb values from the given floats
  1619. * @param r defines the red component to read from
  1620. * @param g defines the green component to read from
  1621. * @param b defines the blue component to read from
  1622. * @returns the current Color3 object
  1623. */
  1624. Color3.prototype.set = function (r, g, b) {
  1625. return this.copyFromFloats(r, g, b);
  1626. };
  1627. /**
  1628. * Compute the Color3 hexadecimal code as a string
  1629. * @returns a string containing the hexadecimal representation of the Color3 object
  1630. */
  1631. Color3.prototype.toHexString = function () {
  1632. var intR = (this.r * 255) | 0;
  1633. var intG = (this.g * 255) | 0;
  1634. var intB = (this.b * 255) | 0;
  1635. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1636. };
  1637. /**
  1638. * Computes a new Color3 converted from the current one to linear space
  1639. * @returns a new Color3 object
  1640. */
  1641. Color3.prototype.toLinearSpace = function () {
  1642. var convertedColor = new Color3();
  1643. this.toLinearSpaceToRef(convertedColor);
  1644. return convertedColor;
  1645. };
  1646. /**
  1647. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1648. * @param convertedColor defines the Color3 object where to store the linear space version
  1649. * @returns the unmodified Color3
  1650. */
  1651. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1652. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1653. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1654. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1655. return this;
  1656. };
  1657. /**
  1658. * Computes a new Color3 converted from the current one to gamma space
  1659. * @returns a new Color3 object
  1660. */
  1661. Color3.prototype.toGammaSpace = function () {
  1662. var convertedColor = new Color3();
  1663. this.toGammaSpaceToRef(convertedColor);
  1664. return convertedColor;
  1665. };
  1666. /**
  1667. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1668. * @param convertedColor defines the Color3 object where to store the gamma space version
  1669. * @returns the unmodified Color3
  1670. */
  1671. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1672. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1673. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1674. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1675. return this;
  1676. };
  1677. // Statics
  1678. /**
  1679. * Creates a new Color3 from the string containing valid hexadecimal values
  1680. * @param hex defines a string containing valid hexadecimal values
  1681. * @returns a new Color3 object
  1682. */
  1683. Color3.FromHexString = function (hex) {
  1684. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1685. return new Color3(0, 0, 0);
  1686. }
  1687. var r = parseInt(hex.substring(1, 3), 16);
  1688. var g = parseInt(hex.substring(3, 5), 16);
  1689. var b = parseInt(hex.substring(5, 7), 16);
  1690. return Color3.FromInts(r, g, b);
  1691. };
  1692. /**
  1693. * Creates a new Vector3 from the starting index of the given array
  1694. * @param array defines the source array
  1695. * @param offset defines an offset in the source array
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromArray = function (array, offset) {
  1699. if (offset === void 0) { offset = 0; }
  1700. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1701. };
  1702. /**
  1703. * Creates a new Color3 from integer values (< 256)
  1704. * @param r defines the red component to read from (value between 0 and 255)
  1705. * @param g defines the green component to read from (value between 0 and 255)
  1706. * @param b defines the blue component to read from (value between 0 and 255)
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.FromInts = function (r, g, b) {
  1710. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1711. };
  1712. /**
  1713. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1714. * @param start defines the start Color3 value
  1715. * @param end defines the end Color3 value
  1716. * @param amount defines the gradient value between start and end
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Lerp = function (start, end, amount) {
  1720. var r = start.r + ((end.r - start.r) * amount);
  1721. var g = start.g + ((end.g - start.g) * amount);
  1722. var b = start.b + ((end.b - start.b) * amount);
  1723. return new Color3(r, g, b);
  1724. };
  1725. /**
  1726. * Returns a Color3 value containing a red color
  1727. * @returns a new Color3 object
  1728. */
  1729. Color3.Red = function () { return new Color3(1, 0, 0); };
  1730. /**
  1731. * Returns a Color3 value containing a green color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Green = function () { return new Color3(0, 1, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a blue color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1740. /**
  1741. * Returns a Color3 value containing a black color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Black = function () { return new Color3(0, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a white color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.White = function () { return new Color3(1, 1, 1); };
  1750. /**
  1751. * Returns a Color3 value containing a purple color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1755. /**
  1756. * Returns a Color3 value containing a magenta color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1760. /**
  1761. * Returns a Color3 value containing a yellow color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a gray color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a teal color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1775. /**
  1776. * Returns a Color3 value containing a random color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1780. return Color3;
  1781. }());
  1782. BABYLON.Color3 = Color3;
  1783. /**
  1784. * Class used to hold a RBGA color
  1785. */
  1786. var Color4 = /** @class */ (function () {
  1787. /**
  1788. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1789. * @param r defines the red component (between 0 and 1, default is 0)
  1790. * @param g defines the green component (between 0 and 1, default is 0)
  1791. * @param b defines the blue component (between 0 and 1, default is 0)
  1792. * @param a defines the alpha component (between 0 and 1, default is 1)
  1793. */
  1794. function Color4(
  1795. /**
  1796. * Defines the red component (between 0 and 1, default is 0)
  1797. */
  1798. r,
  1799. /**
  1800. * Defines the green component (between 0 and 1, default is 0)
  1801. */
  1802. g,
  1803. /**
  1804. * Defines the blue component (between 0 and 1, default is 0)
  1805. */
  1806. b,
  1807. /**
  1808. * Defines the alpha component (between 0 and 1, default is 1)
  1809. */
  1810. a) {
  1811. if (r === void 0) { r = 0; }
  1812. if (g === void 0) { g = 0; }
  1813. if (b === void 0) { b = 0; }
  1814. if (a === void 0) { a = 1; }
  1815. this.r = r;
  1816. this.g = g;
  1817. this.b = b;
  1818. this.a = a;
  1819. }
  1820. // Operators
  1821. /**
  1822. * Adds in place the given Color4 values to the current Color4 object
  1823. * @param right defines the second operand
  1824. * @returns the current updated Color4 object
  1825. */
  1826. Color4.prototype.addInPlace = function (right) {
  1827. this.r += right.r;
  1828. this.g += right.g;
  1829. this.b += right.b;
  1830. this.a += right.a;
  1831. return this;
  1832. };
  1833. /**
  1834. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1835. * @returns the new array
  1836. */
  1837. Color4.prototype.asArray = function () {
  1838. var result = new Array();
  1839. this.toArray(result, 0);
  1840. return result;
  1841. };
  1842. /**
  1843. * Stores from the starting index in the given array the Color4 successive values
  1844. * @param array defines the array where to store the r,g,b components
  1845. * @param index defines an optional index in the target array to define where to start storing values
  1846. * @returns the current Color4 object
  1847. */
  1848. Color4.prototype.toArray = function (array, index) {
  1849. if (index === undefined) {
  1850. index = 0;
  1851. }
  1852. array[index] = this.r;
  1853. array[index + 1] = this.g;
  1854. array[index + 2] = this.b;
  1855. array[index + 3] = this.a;
  1856. return this;
  1857. };
  1858. /**
  1859. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1860. * @param right defines the second operand
  1861. * @returns a new Color4 object
  1862. */
  1863. Color4.prototype.add = function (right) {
  1864. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1865. };
  1866. /**
  1867. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1868. * @param right defines the second operand
  1869. * @returns a new Color4 object
  1870. */
  1871. Color4.prototype.subtract = function (right) {
  1872. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1873. };
  1874. /**
  1875. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1876. * @param right defines the second operand
  1877. * @param result defines the Color4 object where to store the result
  1878. * @returns the current Color4 object
  1879. */
  1880. Color4.prototype.subtractToRef = function (right, result) {
  1881. result.r = this.r - right.r;
  1882. result.g = this.g - right.g;
  1883. result.b = this.b - right.b;
  1884. result.a = this.a - right.a;
  1885. return this;
  1886. };
  1887. /**
  1888. * Creates a new Color4 with the current Color4 values multiplied by scale
  1889. * @param scale defines the scaling factor to apply
  1890. * @returns a new Color4 object
  1891. */
  1892. Color4.prototype.scale = function (scale) {
  1893. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1894. };
  1895. /**
  1896. * Multiplies the current Color4 values by scale and stores the result in "result"
  1897. * @param scale defines the scaling factor to apply
  1898. * @param result defines the Color4 object where to store the result
  1899. * @returns the current unmodified Color4
  1900. */
  1901. Color4.prototype.scaleToRef = function (scale, result) {
  1902. result.r = this.r * scale;
  1903. result.g = this.g * scale;
  1904. result.b = this.b * scale;
  1905. result.a = this.a * scale;
  1906. return this;
  1907. };
  1908. /**
  1909. * Scale the current Color4 values by a factor and add the result to a given Color4
  1910. * @param scale defines the scale factor
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the unmodified current Color4
  1913. */
  1914. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1915. result.r += this.r * scale;
  1916. result.g += this.g * scale;
  1917. result.b += this.b * scale;
  1918. result.a += this.a * scale;
  1919. return this;
  1920. };
  1921. /**
  1922. * Clamps the rgb values by the min and max values and stores the result into "result"
  1923. * @param min defines minimum clamping value (default is 0)
  1924. * @param max defines maximum clamping value (default is 1)
  1925. * @param result defines color to store the result into.
  1926. * @returns the cuurent Color4
  1927. */
  1928. Color4.prototype.clampToRef = function (min, max, result) {
  1929. if (min === void 0) { min = 0; }
  1930. if (max === void 0) { max = 1; }
  1931. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1932. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1933. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1934. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1935. return this;
  1936. };
  1937. /**
  1938. * Multipy an Color4 value by another and return a new Color4 object
  1939. * @param color defines the Color4 value to multiply by
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.multiply = function (color) {
  1943. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1944. };
  1945. /**
  1946. * Multipy a Color4 value by another and push the result in a reference value
  1947. * @param color defines the Color4 value to multiply by
  1948. * @param result defines the Color4 to fill the result in
  1949. * @returns the result Color4
  1950. */
  1951. Color4.prototype.multiplyToRef = function (color, result) {
  1952. result.r = this.r * color.r;
  1953. result.g = this.g * color.g;
  1954. result.b = this.b * color.b;
  1955. result.a = this.a * color.a;
  1956. return result;
  1957. };
  1958. /**
  1959. * Creates a string with the Color4 current values
  1960. * @returns the string representation of the Color4 object
  1961. */
  1962. Color4.prototype.toString = function () {
  1963. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1964. };
  1965. /**
  1966. * Returns the string "Color4"
  1967. * @returns "Color4"
  1968. */
  1969. Color4.prototype.getClassName = function () {
  1970. return "Color4";
  1971. };
  1972. /**
  1973. * Compute the Color4 hash code
  1974. * @returns an unique number that can be used to hash Color4 objects
  1975. */
  1976. Color4.prototype.getHashCode = function () {
  1977. var hash = this.r || 0;
  1978. hash = (hash * 397) ^ (this.g || 0);
  1979. hash = (hash * 397) ^ (this.b || 0);
  1980. hash = (hash * 397) ^ (this.a || 0);
  1981. return hash;
  1982. };
  1983. /**
  1984. * Creates a new Color4 copied from the current one
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.clone = function () {
  1988. return new Color4(this.r, this.g, this.b, this.a);
  1989. };
  1990. /**
  1991. * Copies the given Color4 values into the current one
  1992. * @param source defines the source Color4 object
  1993. * @returns the current updated Color4 object
  1994. */
  1995. Color4.prototype.copyFrom = function (source) {
  1996. this.r = source.r;
  1997. this.g = source.g;
  1998. this.b = source.b;
  1999. this.a = source.a;
  2000. return this;
  2001. };
  2002. /**
  2003. * Copies the given float values into the current one
  2004. * @param r defines the red component to read from
  2005. * @param g defines the green component to read from
  2006. * @param b defines the blue component to read from
  2007. * @param a defines the alpha component to read from
  2008. * @returns the current updated Color4 object
  2009. */
  2010. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2011. this.r = r;
  2012. this.g = g;
  2013. this.b = b;
  2014. this.a = a;
  2015. return this;
  2016. };
  2017. /**
  2018. * Copies the given float values into the current one
  2019. * @param r defines the red component to read from
  2020. * @param g defines the green component to read from
  2021. * @param b defines the blue component to read from
  2022. * @param a defines the alpha component to read from
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.set = function (r, g, b, a) {
  2026. return this.copyFromFloats(r, g, b, a);
  2027. };
  2028. /**
  2029. * Compute the Color4 hexadecimal code as a string
  2030. * @returns a string containing the hexadecimal representation of the Color4 object
  2031. */
  2032. Color4.prototype.toHexString = function () {
  2033. var intR = (this.r * 255) | 0;
  2034. var intG = (this.g * 255) | 0;
  2035. var intB = (this.b * 255) | 0;
  2036. var intA = (this.a * 255) | 0;
  2037. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2038. };
  2039. /**
  2040. * Computes a new Color4 converted from the current one to linear space
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.toLinearSpace = function () {
  2044. var convertedColor = new Color4();
  2045. this.toLinearSpaceToRef(convertedColor);
  2046. return convertedColor;
  2047. };
  2048. /**
  2049. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2050. * @param convertedColor defines the Color4 object where to store the linear space version
  2051. * @returns the unmodified Color4
  2052. */
  2053. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2054. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2055. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2056. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2057. convertedColor.a = this.a;
  2058. return this;
  2059. };
  2060. /**
  2061. * Computes a new Color4 converted from the current one to gamma space
  2062. * @returns a new Color4 object
  2063. */
  2064. Color4.prototype.toGammaSpace = function () {
  2065. var convertedColor = new Color4();
  2066. this.toGammaSpaceToRef(convertedColor);
  2067. return convertedColor;
  2068. };
  2069. /**
  2070. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2071. * @param convertedColor defines the Color4 object where to store the gamma space version
  2072. * @returns the unmodified Color4
  2073. */
  2074. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2075. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2076. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2077. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2078. convertedColor.a = this.a;
  2079. return this;
  2080. };
  2081. // Statics
  2082. /**
  2083. * Creates a new Color4 from the string containing valid hexadecimal values
  2084. * @param hex defines a string containing valid hexadecimal values
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromHexString = function (hex) {
  2088. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2089. return new Color4(0.0, 0.0, 0.0, 0.0);
  2090. }
  2091. var r = parseInt(hex.substring(1, 3), 16);
  2092. var g = parseInt(hex.substring(3, 5), 16);
  2093. var b = parseInt(hex.substring(5, 7), 16);
  2094. var a = parseInt(hex.substring(7, 9), 16);
  2095. return Color4.FromInts(r, g, b, a);
  2096. };
  2097. /**
  2098. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2099. * @param left defines the start value
  2100. * @param right defines the end value
  2101. * @param amount defines the gradient factor
  2102. * @returns a new Color4 object
  2103. */
  2104. Color4.Lerp = function (left, right, amount) {
  2105. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2106. Color4.LerpToRef(left, right, amount, result);
  2107. return result;
  2108. };
  2109. /**
  2110. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2111. * @param left defines the start value
  2112. * @param right defines the end value
  2113. * @param amount defines the gradient factor
  2114. * @param result defines the Color4 object where to store data
  2115. */
  2116. Color4.LerpToRef = function (left, right, amount, result) {
  2117. result.r = left.r + (right.r - left.r) * amount;
  2118. result.g = left.g + (right.g - left.g) * amount;
  2119. result.b = left.b + (right.b - left.b) * amount;
  2120. result.a = left.a + (right.a - left.a) * amount;
  2121. };
  2122. /**
  2123. * Creates a new Color4 from the starting index element of the given array
  2124. * @param array defines the source array to read from
  2125. * @param offset defines the offset in the source array
  2126. * @returns a new Color4 object
  2127. */
  2128. Color4.FromArray = function (array, offset) {
  2129. if (offset === void 0) { offset = 0; }
  2130. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2131. };
  2132. /**
  2133. * Creates a new Color3 from integer values (< 256)
  2134. * @param r defines the red component to read from (value between 0 and 255)
  2135. * @param g defines the green component to read from (value between 0 and 255)
  2136. * @param b defines the blue component to read from (value between 0 and 255)
  2137. * @param a defines the alpha component to read from (value between 0 and 255)
  2138. * @returns a new Color3 object
  2139. */
  2140. Color4.FromInts = function (r, g, b, a) {
  2141. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2142. };
  2143. /**
  2144. * Check the content of a given array and convert it to an array containing RGBA data
  2145. * If the original array was already containing count * 4 values then it is returned directly
  2146. * @param colors defines the array to check
  2147. * @param count defines the number of RGBA data to expect
  2148. * @returns an array containing count * 4 values (RGBA)
  2149. */
  2150. Color4.CheckColors4 = function (colors, count) {
  2151. // Check if color3 was used
  2152. if (colors.length === count * 3) {
  2153. var colors4 = [];
  2154. for (var index = 0; index < colors.length; index += 3) {
  2155. var newIndex = (index / 3) * 4;
  2156. colors4[newIndex] = colors[index];
  2157. colors4[newIndex + 1] = colors[index + 1];
  2158. colors4[newIndex + 2] = colors[index + 2];
  2159. colors4[newIndex + 3] = 1.0;
  2160. }
  2161. return colors4;
  2162. }
  2163. return colors;
  2164. };
  2165. return Color4;
  2166. }());
  2167. BABYLON.Color4 = Color4;
  2168. var Vector2 = /** @class */ (function () {
  2169. /**
  2170. * Creates a new Vector2 from the given x and y coordinates.
  2171. */
  2172. function Vector2(x, y) {
  2173. this.x = x;
  2174. this.y = y;
  2175. }
  2176. /**
  2177. * Returns a string with the Vector2 coordinates.
  2178. */
  2179. Vector2.prototype.toString = function () {
  2180. return "{X: " + this.x + " Y:" + this.y + "}";
  2181. };
  2182. /**
  2183. * Returns the string "Vector2"
  2184. */
  2185. Vector2.prototype.getClassName = function () {
  2186. return "Vector2";
  2187. };
  2188. /**
  2189. * Returns the Vector2 hash code as a number.
  2190. */
  2191. Vector2.prototype.getHashCode = function () {
  2192. var hash = this.x || 0;
  2193. hash = (hash * 397) ^ (this.y || 0);
  2194. return hash;
  2195. };
  2196. // Operators
  2197. /**
  2198. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2199. * Returns the Vector2.
  2200. */
  2201. Vector2.prototype.toArray = function (array, index) {
  2202. if (index === void 0) { index = 0; }
  2203. array[index] = this.x;
  2204. array[index + 1] = this.y;
  2205. return this;
  2206. };
  2207. /**
  2208. * Returns a new array with 2 elements : the Vector2 coordinates.
  2209. */
  2210. Vector2.prototype.asArray = function () {
  2211. var result = new Array();
  2212. this.toArray(result, 0);
  2213. return result;
  2214. };
  2215. /**
  2216. * Sets the Vector2 coordinates with the given Vector2 coordinates.
  2217. * Returns the updated Vector2.
  2218. */
  2219. Vector2.prototype.copyFrom = function (source) {
  2220. this.x = source.x;
  2221. this.y = source.y;
  2222. return this;
  2223. };
  2224. /**
  2225. * Sets the Vector2 coordinates with the given floats.
  2226. * Returns the updated Vector2.
  2227. */
  2228. Vector2.prototype.copyFromFloats = function (x, y) {
  2229. this.x = x;
  2230. this.y = y;
  2231. return this;
  2232. };
  2233. /**
  2234. * Sets the Vector2 coordinates with the given floats.
  2235. * Returns the updated Vector2.
  2236. */
  2237. Vector2.prototype.set = function (x, y) {
  2238. return this.copyFromFloats(x, y);
  2239. };
  2240. /**
  2241. * Returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates.
  2242. */
  2243. Vector2.prototype.add = function (otherVector) {
  2244. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2245. };
  2246. /**
  2247. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates.
  2248. * Returns the Vector2.
  2249. */
  2250. Vector2.prototype.addToRef = function (otherVector, result) {
  2251. result.x = this.x + otherVector.x;
  2252. result.y = this.y + otherVector.y;
  2253. return this;
  2254. };
  2255. /**
  2256. * Set the Vector2 coordinates by adding the given Vector2 coordinates.
  2257. * Returns the updated Vector2.
  2258. */
  2259. Vector2.prototype.addInPlace = function (otherVector) {
  2260. this.x += otherVector.x;
  2261. this.y += otherVector.y;
  2262. return this;
  2263. };
  2264. /**
  2265. * Returns a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates.
  2266. */
  2267. Vector2.prototype.addVector3 = function (otherVector) {
  2268. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2269. };
  2270. /**
  2271. * Returns a new Vector2 set with the subtracted coordinates of the given one from the current Vector2.
  2272. */
  2273. Vector2.prototype.subtract = function (otherVector) {
  2274. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2275. };
  2276. /**
  2277. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2278. * Returns the Vector2.
  2279. */
  2280. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2281. result.x = this.x - otherVector.x;
  2282. result.y = this.y - otherVector.y;
  2283. return this;
  2284. };
  2285. /**
  2286. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates.
  2287. * Returns the updated Vector2.
  2288. */
  2289. Vector2.prototype.subtractInPlace = function (otherVector) {
  2290. this.x -= otherVector.x;
  2291. this.y -= otherVector.y;
  2292. return this;
  2293. };
  2294. /**
  2295. * Multiplies in place the current Vector2 coordinates by the given ones.
  2296. * Returns the updated Vector2.
  2297. */
  2298. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2299. this.x *= otherVector.x;
  2300. this.y *= otherVector.y;
  2301. return this;
  2302. };
  2303. /**
  2304. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates.
  2305. */
  2306. Vector2.prototype.multiply = function (otherVector) {
  2307. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2308. };
  2309. /**
  2310. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates.
  2311. * Returns the Vector2.
  2312. */
  2313. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2314. result.x = this.x * otherVector.x;
  2315. result.y = this.y * otherVector.y;
  2316. return this;
  2317. };
  2318. /**
  2319. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the given floats.
  2320. */
  2321. Vector2.prototype.multiplyByFloats = function (x, y) {
  2322. return new Vector2(this.x * x, this.y * y);
  2323. };
  2324. /**
  2325. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates.
  2326. */
  2327. Vector2.prototype.divide = function (otherVector) {
  2328. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2329. };
  2330. /**
  2331. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates.
  2332. * Returns the Vector2.
  2333. */
  2334. Vector2.prototype.divideToRef = function (otherVector, result) {
  2335. result.x = this.x / otherVector.x;
  2336. result.y = this.y / otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Divides the current Vector3 coordinates by the given ones.
  2341. * Returns the updated Vector3.
  2342. */
  2343. Vector2.prototype.divideInPlace = function (otherVector) {
  2344. return this.divideToRef(otherVector, this);
  2345. };
  2346. /**
  2347. * Returns a new Vector2 with current Vector2 negated coordinates.
  2348. */
  2349. Vector2.prototype.negate = function () {
  2350. return new Vector2(-this.x, -this.y);
  2351. };
  2352. /**
  2353. * Multiply the Vector2 coordinates by scale.
  2354. * Returns the updated Vector2.
  2355. */
  2356. Vector2.prototype.scaleInPlace = function (scale) {
  2357. this.x *= scale;
  2358. this.y *= scale;
  2359. return this;
  2360. };
  2361. /**
  2362. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2363. */
  2364. Vector2.prototype.scale = function (scale) {
  2365. var result = new Vector2(0, 0);
  2366. this.scaleToRef(scale, result);
  2367. return result;
  2368. };
  2369. /**
  2370. * Scale the current Vector2 values by a factor to a given Vector2
  2371. * @param scale defines the scale factor
  2372. * @param result defines the Vector2 object where to store the result
  2373. * @returns the unmodified current Vector2
  2374. */
  2375. Vector2.prototype.scaleToRef = function (scale, result) {
  2376. result.x = this.x * scale;
  2377. result.y = this.y * scale;
  2378. return this;
  2379. };
  2380. /**
  2381. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2382. * @param scale defines the scale factor
  2383. * @param result defines the Vector2 object where to store the result
  2384. * @returns the unmodified current Vector2
  2385. */
  2386. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2387. result.x += this.x * scale;
  2388. result.y += this.y * scale;
  2389. return this;
  2390. };
  2391. /**
  2392. * Boolean : True if the given vector coordinates strictly equal the current Vector2 ones.
  2393. */
  2394. Vector2.prototype.equals = function (otherVector) {
  2395. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2396. };
  2397. /**
  2398. * Boolean : True if the given vector coordinates are close to the current ones by a distance of epsilon.
  2399. */
  2400. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2401. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2402. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2403. };
  2404. // Properties
  2405. /**
  2406. * Returns the vector length (float).
  2407. */
  2408. Vector2.prototype.length = function () {
  2409. return Math.sqrt(this.x * this.x + this.y * this.y);
  2410. };
  2411. /**
  2412. * Returns the vector squared length (float);
  2413. */
  2414. Vector2.prototype.lengthSquared = function () {
  2415. return (this.x * this.x + this.y * this.y);
  2416. };
  2417. // Methods
  2418. /**
  2419. * Normalize the vector.
  2420. * Returns the updated Vector2.
  2421. */
  2422. Vector2.prototype.normalize = function () {
  2423. var len = this.length();
  2424. if (len === 0)
  2425. return this;
  2426. var num = 1.0 / len;
  2427. this.x *= num;
  2428. this.y *= num;
  2429. return this;
  2430. };
  2431. /**
  2432. * Returns a new Vector2 copied from the Vector2.
  2433. */
  2434. Vector2.prototype.clone = function () {
  2435. return new Vector2(this.x, this.y);
  2436. };
  2437. // Statics
  2438. /**
  2439. * Returns a new Vector2(0, 0)
  2440. */
  2441. Vector2.Zero = function () {
  2442. return new Vector2(0, 0);
  2443. };
  2444. /**
  2445. * Returns a new Vector2(1, 1)
  2446. */
  2447. Vector2.One = function () {
  2448. return new Vector2(1, 1);
  2449. };
  2450. /**
  2451. * Returns a new Vector2 set from the given index element of the given array.
  2452. */
  2453. Vector2.FromArray = function (array, offset) {
  2454. if (offset === void 0) { offset = 0; }
  2455. return new Vector2(array[offset], array[offset + 1]);
  2456. };
  2457. /**
  2458. * Sets "result" from the given index element of the given array.
  2459. */
  2460. Vector2.FromArrayToRef = function (array, offset, result) {
  2461. result.x = array[offset];
  2462. result.y = array[offset + 1];
  2463. };
  2464. /**
  2465. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2.
  2466. */
  2467. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2468. var squared = amount * amount;
  2469. var cubed = amount * squared;
  2470. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2471. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2472. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2473. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2474. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2475. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2476. return new Vector2(x, y);
  2477. };
  2478. /**
  2479. * 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".
  2480. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2481. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2482. */
  2483. Vector2.Clamp = function (value, min, max) {
  2484. var x = value.x;
  2485. x = (x > max.x) ? max.x : x;
  2486. x = (x < min.x) ? min.x : x;
  2487. var y = value.y;
  2488. y = (y > max.y) ? max.y : y;
  2489. y = (y < min.y) ? min.y : y;
  2490. return new Vector2(x, y);
  2491. };
  2492. /**
  2493. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2494. */
  2495. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2496. var squared = amount * amount;
  2497. var cubed = amount * squared;
  2498. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2499. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2500. var part3 = (cubed - (2.0 * squared)) + amount;
  2501. var part4 = cubed - squared;
  2502. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2503. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2504. return new Vector2(x, y);
  2505. };
  2506. /**
  2507. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2508. */
  2509. Vector2.Lerp = function (start, end, amount) {
  2510. var x = start.x + ((end.x - start.x) * amount);
  2511. var y = start.y + ((end.y - start.y) * amount);
  2512. return new Vector2(x, y);
  2513. };
  2514. /**
  2515. * Returns the dot product (float) of the vector "left" and the vector "right".
  2516. */
  2517. Vector2.Dot = function (left, right) {
  2518. return left.x * right.x + left.y * right.y;
  2519. };
  2520. /**
  2521. * Returns a new Vector2 equal to the normalized given vector.
  2522. */
  2523. Vector2.Normalize = function (vector) {
  2524. var newVector = vector.clone();
  2525. newVector.normalize();
  2526. return newVector;
  2527. };
  2528. /**
  2529. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2530. */
  2531. Vector2.Minimize = function (left, right) {
  2532. var x = (left.x < right.x) ? left.x : right.x;
  2533. var y = (left.y < right.y) ? left.y : right.y;
  2534. return new Vector2(x, y);
  2535. };
  2536. /**
  2537. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2538. */
  2539. Vector2.Maximize = function (left, right) {
  2540. var x = (left.x > right.x) ? left.x : right.x;
  2541. var y = (left.y > right.y) ? left.y : right.y;
  2542. return new Vector2(x, y);
  2543. };
  2544. /**
  2545. * Returns a new Vecto2 set with the transformed coordinates of the given vector by the given transformation matrix.
  2546. */
  2547. Vector2.Transform = function (vector, transformation) {
  2548. var r = Vector2.Zero();
  2549. Vector2.TransformToRef(vector, transformation, r);
  2550. return r;
  2551. };
  2552. /**
  2553. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates.
  2554. */
  2555. Vector2.TransformToRef = function (vector, transformation, result) {
  2556. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2557. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2558. result.x = x;
  2559. result.y = y;
  2560. };
  2561. /**
  2562. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2563. */
  2564. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2565. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2566. var sign = a < 0 ? -1 : 1;
  2567. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2568. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2569. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2570. };
  2571. /**
  2572. * Returns the distance (float) between the vectors "value1" and "value2".
  2573. */
  2574. Vector2.Distance = function (value1, value2) {
  2575. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2576. };
  2577. /**
  2578. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2579. */
  2580. Vector2.DistanceSquared = function (value1, value2) {
  2581. var x = value1.x - value2.x;
  2582. var y = value1.y - value2.y;
  2583. return (x * x) + (y * y);
  2584. };
  2585. /**
  2586. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2587. */
  2588. Vector2.Center = function (value1, value2) {
  2589. var center = value1.add(value2);
  2590. center.scaleInPlace(0.5);
  2591. return center;
  2592. };
  2593. /**
  2594. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2595. */
  2596. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2597. var l2 = Vector2.DistanceSquared(segA, segB);
  2598. if (l2 === 0.0) {
  2599. return Vector2.Distance(p, segA);
  2600. }
  2601. var v = segB.subtract(segA);
  2602. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2603. var proj = segA.add(v.multiplyByFloats(t, t));
  2604. return Vector2.Distance(p, proj);
  2605. };
  2606. return Vector2;
  2607. }());
  2608. BABYLON.Vector2 = Vector2;
  2609. /**
  2610. * Classed used to store (x,y,z) vector representation
  2611. * A Vector3 is the main object used in 3D geometry
  2612. * It can represent etiher the coordinates of a point the space, either a direction
  2613. * Reminder: Babylon.js uses a left handed forward facing system
  2614. */
  2615. var Vector3 = /** @class */ (function () {
  2616. /**
  2617. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2618. * @param x defines the first coordinates (on X axis)
  2619. * @param y defines the second coordinates (on Y axis)
  2620. * @param z defines the third coordinates (on Z axis)
  2621. */
  2622. function Vector3(
  2623. /**
  2624. * Defines the first coordinates (on X axis)
  2625. */
  2626. x,
  2627. /**
  2628. * Defines the second coordinates (on Y axis)
  2629. */
  2630. y,
  2631. /**
  2632. * Defines the third coordinates (on Z axis)
  2633. */
  2634. z) {
  2635. this.x = x;
  2636. this.y = y;
  2637. this.z = z;
  2638. }
  2639. /**
  2640. * Creates a string representation of the Vector3
  2641. * @returns a string with the Vector3 coordinates.
  2642. */
  2643. Vector3.prototype.toString = function () {
  2644. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2645. };
  2646. /**
  2647. * Gets the class name
  2648. * @returns the string "Vector3"
  2649. */
  2650. Vector3.prototype.getClassName = function () {
  2651. return "Vector3";
  2652. };
  2653. /**
  2654. * Creates the Vector3 hash code
  2655. * @returns a number which tends to be unique between Vector3 instances
  2656. */
  2657. Vector3.prototype.getHashCode = function () {
  2658. var hash = this.x || 0;
  2659. hash = (hash * 397) ^ (this.y || 0);
  2660. hash = (hash * 397) ^ (this.z || 0);
  2661. return hash;
  2662. };
  2663. // Operators
  2664. /**
  2665. * Creates an array containing three elements : the coordinates of the Vector3
  2666. * @returns a new array of numbers
  2667. */
  2668. Vector3.prototype.asArray = function () {
  2669. var result = [];
  2670. this.toArray(result, 0);
  2671. return result;
  2672. };
  2673. /**
  2674. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2675. * @param array defines the destination array
  2676. * @param index defines the offset in the destination array
  2677. * @returns the current Vector3
  2678. */
  2679. Vector3.prototype.toArray = function (array, index) {
  2680. if (index === void 0) { index = 0; }
  2681. array[index] = this.x;
  2682. array[index + 1] = this.y;
  2683. array[index + 2] = this.z;
  2684. return this;
  2685. };
  2686. /**
  2687. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2688. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2689. */
  2690. Vector3.prototype.toQuaternion = function () {
  2691. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2692. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2693. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2694. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2695. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2696. var cosy = Math.cos(this.y * 0.5);
  2697. var siny = Math.sin(this.y * 0.5);
  2698. result.x = coszMinusx * siny;
  2699. result.y = -sinzMinusx * siny;
  2700. result.z = sinxPlusz * cosy;
  2701. result.w = cosxPlusz * cosy;
  2702. return result;
  2703. };
  2704. /**
  2705. * Adds the given vector to the current Vector3
  2706. * @param otherVector defines the second operand
  2707. * @returns the current updated Vector3
  2708. */
  2709. Vector3.prototype.addInPlace = function (otherVector) {
  2710. this.x += otherVector.x;
  2711. this.y += otherVector.y;
  2712. this.z += otherVector.z;
  2713. return this;
  2714. };
  2715. /**
  2716. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2717. * @param otherVector defines the second operand
  2718. * @returns the resulting Vector3
  2719. */
  2720. Vector3.prototype.add = function (otherVector) {
  2721. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2722. };
  2723. /**
  2724. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2725. * @param otherVector defines the second operand
  2726. * @param result defines the Vector3 object where to store the result
  2727. * @returns the current Vector3
  2728. */
  2729. Vector3.prototype.addToRef = function (otherVector, result) {
  2730. result.x = this.x + otherVector.x;
  2731. result.y = this.y + otherVector.y;
  2732. result.z = this.z + otherVector.z;
  2733. return this;
  2734. };
  2735. /**
  2736. * Subtract the given vector from the current Vector3
  2737. * @param otherVector defines the second operand
  2738. * @returns the current updated Vector3
  2739. */
  2740. Vector3.prototype.subtractInPlace = function (otherVector) {
  2741. this.x -= otherVector.x;
  2742. this.y -= otherVector.y;
  2743. this.z -= otherVector.z;
  2744. return this;
  2745. };
  2746. /**
  2747. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2748. * @param otherVector defines the second operand
  2749. * @returns the resulting Vector3
  2750. */
  2751. Vector3.prototype.subtract = function (otherVector) {
  2752. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2753. };
  2754. /**
  2755. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2756. * @param otherVector defines the second operand
  2757. * @param result defines the Vector3 object where to store the result
  2758. * @returns the current Vector3
  2759. */
  2760. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2761. result.x = this.x - otherVector.x;
  2762. result.y = this.y - otherVector.y;
  2763. result.z = this.z - otherVector.z;
  2764. return this;
  2765. };
  2766. /**
  2767. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2768. * @param x defines the x coordinate of the operand
  2769. * @param y defines the y coordinate of the operand
  2770. * @param z defines the z coordinate of the operand
  2771. * @returns the resulting Vector3
  2772. */
  2773. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2774. return new Vector3(this.x - x, this.y - y, this.z - z);
  2775. };
  2776. /**
  2777. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2778. * @param x defines the x coordinate of the operand
  2779. * @param y defines the y coordinate of the operand
  2780. * @param z defines the z coordinate of the operand
  2781. * @param result defines the Vector3 object where to store the result
  2782. * @returns the current Vector3
  2783. */
  2784. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2785. result.x = this.x - x;
  2786. result.y = this.y - y;
  2787. result.z = this.z - z;
  2788. return this;
  2789. };
  2790. /**
  2791. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2792. * @returns a new Vector3
  2793. */
  2794. Vector3.prototype.negate = function () {
  2795. return new Vector3(-this.x, -this.y, -this.z);
  2796. };
  2797. /**
  2798. * Multiplies the Vector3 coordinates by the float "scale"
  2799. * @param scale defines the multiplier factor
  2800. * @returns the current updated Vector3
  2801. */
  2802. Vector3.prototype.scaleInPlace = function (scale) {
  2803. this.x *= scale;
  2804. this.y *= scale;
  2805. this.z *= scale;
  2806. return this;
  2807. };
  2808. /**
  2809. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2810. * @param scale defines the multiplier factor
  2811. * @returns a new Vector3
  2812. */
  2813. Vector3.prototype.scale = function (scale) {
  2814. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2815. };
  2816. /**
  2817. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2818. * @param scale defines the multiplier factor
  2819. * @param result defines the Vector3 object where to store the result
  2820. * @returns the current Vector3
  2821. */
  2822. Vector3.prototype.scaleToRef = function (scale, result) {
  2823. result.x = this.x * scale;
  2824. result.y = this.y * scale;
  2825. result.z = this.z * scale;
  2826. return this;
  2827. };
  2828. /**
  2829. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2830. * @param scale defines the scale factor
  2831. * @param result defines the Vector3 object where to store the result
  2832. * @returns the unmodified current Vector3
  2833. */
  2834. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2835. result.x += this.x * scale;
  2836. result.y += this.y * scale;
  2837. result.z += this.z * scale;
  2838. return this;
  2839. };
  2840. /**
  2841. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2842. * @param otherVector defines the second operand
  2843. * @returns true if both vectors are equals
  2844. */
  2845. Vector3.prototype.equals = function (otherVector) {
  2846. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2847. };
  2848. /**
  2849. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2850. * @param otherVector defines the second operand
  2851. * @param epsilon defines the minimal distance to define values as equals
  2852. * @returns true if both vectors are distant less than epsilon
  2853. */
  2854. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2855. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2856. 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);
  2857. };
  2858. /**
  2859. * Returns true if the current Vector3 coordinates equals the given floats
  2860. * @param x defines the x coordinate of the operand
  2861. * @param y defines the y coordinate of the operand
  2862. * @param z defines the z coordinate of the operand
  2863. * @returns true if both vectors are equals
  2864. */
  2865. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2866. return this.x === x && this.y === y && this.z === z;
  2867. };
  2868. /**
  2869. * Multiplies the current Vector3 coordinates by the given ones
  2870. * @param otherVector defines the second operand
  2871. * @returns the current updated Vector3
  2872. */
  2873. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2874. this.x *= otherVector.x;
  2875. this.y *= otherVector.y;
  2876. this.z *= otherVector.z;
  2877. return this;
  2878. };
  2879. /**
  2880. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2881. * @param otherVector defines the second operand
  2882. * @returns the new Vector3
  2883. */
  2884. Vector3.prototype.multiply = function (otherVector) {
  2885. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2886. };
  2887. /**
  2888. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  2889. * @param otherVector defines the second operand
  2890. * @param result defines the Vector3 object where to store the result
  2891. * @returns the current Vector3
  2892. */
  2893. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2894. result.x = this.x * otherVector.x;
  2895. result.y = this.y * otherVector.y;
  2896. result.z = this.z * otherVector.z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  2901. * @param x defines the x coordinate of the operand
  2902. * @param y defines the y coordinate of the operand
  2903. * @param z defines the z coordinate of the operand
  2904. * @returns the new Vector3
  2905. */
  2906. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2907. return new Vector3(this.x * x, this.y * y, this.z * z);
  2908. };
  2909. /**
  2910. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  2911. * @param otherVector defines the second operand
  2912. * @returns the new Vector3
  2913. */
  2914. Vector3.prototype.divide = function (otherVector) {
  2915. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2916. };
  2917. /**
  2918. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  2919. * @param otherVector defines the second operand
  2920. * @param result defines the Vector3 object where to store the result
  2921. * @returns the current Vector3
  2922. */
  2923. Vector3.prototype.divideToRef = function (otherVector, result) {
  2924. result.x = this.x / otherVector.x;
  2925. result.y = this.y / otherVector.y;
  2926. result.z = this.z / otherVector.z;
  2927. return this;
  2928. };
  2929. /**
  2930. * Divides the current Vector3 coordinates by the given ones.
  2931. * @param otherVector defines the second operand
  2932. * @returns the current updated Vector3
  2933. */
  2934. Vector3.prototype.divideInPlace = function (otherVector) {
  2935. return this.divideToRef(otherVector, this);
  2936. };
  2937. /**
  2938. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  2939. * @param other defines the second operand
  2940. * @returns the current updated Vector3
  2941. */
  2942. Vector3.prototype.minimizeInPlace = function (other) {
  2943. if (other.x < this.x)
  2944. this.x = other.x;
  2945. if (other.y < this.y)
  2946. this.y = other.y;
  2947. if (other.z < this.z)
  2948. this.z = other.z;
  2949. return this;
  2950. };
  2951. /**
  2952. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  2953. * @param other defines the second operand
  2954. * @returns the current updated Vector3
  2955. */
  2956. Vector3.prototype.maximizeInPlace = function (other) {
  2957. if (other.x > this.x)
  2958. this.x = other.x;
  2959. if (other.y > this.y)
  2960. this.y = other.y;
  2961. if (other.z > this.z)
  2962. this.z = other.z;
  2963. return this;
  2964. };
  2965. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2966. /**
  2967. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2968. */
  2969. get: function () {
  2970. var absX = Math.abs(this.x);
  2971. var absY = Math.abs(this.y);
  2972. if (absX !== absY) {
  2973. return true;
  2974. }
  2975. var absZ = Math.abs(this.z);
  2976. if (absX !== absZ) {
  2977. return true;
  2978. }
  2979. if (absY !== absZ) {
  2980. return true;
  2981. }
  2982. return false;
  2983. },
  2984. enumerable: true,
  2985. configurable: true
  2986. });
  2987. // Properties
  2988. /**
  2989. * Gets the length of the Vector3
  2990. * @returns the length of the Vecto3
  2991. */
  2992. Vector3.prototype.length = function () {
  2993. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2994. };
  2995. /**
  2996. * Gets the squared length of the Vector3
  2997. * @returns squared length of the Vector3
  2998. */
  2999. Vector3.prototype.lengthSquared = function () {
  3000. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3001. };
  3002. /**
  3003. * Normalize the current Vector3.
  3004. * Please note that this is an in place operation.
  3005. * @returns the current updated Vector3
  3006. */
  3007. Vector3.prototype.normalize = function () {
  3008. var len = this.length();
  3009. if (len === 0 || len === 1.0)
  3010. return this;
  3011. var num = 1.0 / len;
  3012. this.x *= num;
  3013. this.y *= num;
  3014. this.z *= num;
  3015. return this;
  3016. };
  3017. /**
  3018. * Normalize the current Vector3 to a new vector
  3019. * @returns the new Vector3
  3020. */
  3021. Vector3.prototype.normalizeToNew = function () {
  3022. var normalized = new Vector3(0, 0, 0);
  3023. this.normalizeToRef(normalized);
  3024. return normalized;
  3025. };
  3026. /**
  3027. * Normalize the current Vector3 to the reference
  3028. * @param reference define the Vector3 to update
  3029. * @returns the updated Vector3
  3030. */
  3031. Vector3.prototype.normalizeToRef = function (reference) {
  3032. var len = this.length();
  3033. if (len === 0 || len === 1.0) {
  3034. reference.set(this.x, this.y, this.z);
  3035. return reference;
  3036. }
  3037. var scale = 1.0 / len;
  3038. this.scaleToRef(scale, reference);
  3039. return reference;
  3040. };
  3041. /**
  3042. * Creates a new Vector3 copied from the current Vector3
  3043. * @returns the new Vector3
  3044. */
  3045. Vector3.prototype.clone = function () {
  3046. return new Vector3(this.x, this.y, this.z);
  3047. };
  3048. /**
  3049. * Copies the given vector coordinates to the current Vector3 ones
  3050. * @param source defines the source Vector3
  3051. * @returns the current updated Vector3
  3052. */
  3053. Vector3.prototype.copyFrom = function (source) {
  3054. this.x = source.x;
  3055. this.y = source.y;
  3056. this.z = source.z;
  3057. return this;
  3058. };
  3059. /**
  3060. * Copies the given floats to the current Vector3 coordinates
  3061. * @param x defines the x coordinate of the operand
  3062. * @param y defines the y coordinate of the operand
  3063. * @param z defines the z coordinate of the operand
  3064. * @returns the current updated Vector3
  3065. */
  3066. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3067. this.x = x;
  3068. this.y = y;
  3069. this.z = z;
  3070. return this;
  3071. };
  3072. /**
  3073. * Copies the given floats to the current Vector3 coordinates
  3074. * @param x defines the x coordinate of the operand
  3075. * @param y defines the y coordinate of the operand
  3076. * @param z defines the z coordinate of the operand
  3077. * @returns the current updated Vector3
  3078. */
  3079. Vector3.prototype.set = function (x, y, z) {
  3080. return this.copyFromFloats(x, y, z);
  3081. };
  3082. // Statics
  3083. /**
  3084. * Get the clip factor between two vectors
  3085. * @param vector0 defines the first operand
  3086. * @param vector1 defines the second operand
  3087. * @param axis defines the axis to use
  3088. * @param size defines the size along the axis
  3089. * @returns the clip factor
  3090. */
  3091. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3092. var d0 = Vector3.Dot(vector0, axis) - size;
  3093. var d1 = Vector3.Dot(vector1, axis) - size;
  3094. var s = d0 / (d0 - d1);
  3095. return s;
  3096. };
  3097. /**
  3098. * Get angle between two vectors
  3099. * @param vector0 angle between vector0 and vector1
  3100. * @param vector1 angle between vector0 and vector1
  3101. * @param normal direction of the normal
  3102. * @return the angle between vector0 and vector1
  3103. */
  3104. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3105. var v0 = vector0.clone().normalize();
  3106. var v1 = vector1.clone().normalize();
  3107. var dot = Vector3.Dot(v0, v1);
  3108. var n = Vector3.Cross(v0, v1);
  3109. if (Vector3.Dot(n, normal) > 0) {
  3110. return Math.acos(dot);
  3111. }
  3112. return -Math.acos(dot);
  3113. };
  3114. /**
  3115. * Returns a new Vector3 set from the index "offset" of the given array
  3116. * @param array defines the source array
  3117. * @param offset defines the offset in the source array
  3118. * @returns the new Vector3
  3119. */
  3120. Vector3.FromArray = function (array, offset) {
  3121. if (!offset) {
  3122. offset = 0;
  3123. }
  3124. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3125. };
  3126. /**
  3127. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3128. * This function is deprecated. Use FromArray instead
  3129. * @param array defines the source array
  3130. * @param offset defines the offset in the source array
  3131. * @returns the new Vector3
  3132. */
  3133. Vector3.FromFloatArray = function (array, offset) {
  3134. return Vector3.FromArray(array, offset);
  3135. };
  3136. /**
  3137. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3138. * @param array defines the source array
  3139. * @param offset defines the offset in the source array
  3140. * @param result defines the Vector3 where to store the result
  3141. */
  3142. Vector3.FromArrayToRef = function (array, offset, result) {
  3143. result.x = array[offset];
  3144. result.y = array[offset + 1];
  3145. result.z = array[offset + 2];
  3146. };
  3147. /**
  3148. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3149. * This function is deprecated. Use FromArrayToRef instead.
  3150. * @param array defines the source array
  3151. * @param offset defines the offset in the source array
  3152. * @param result defines the Vector3 where to store the result
  3153. */
  3154. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3155. return Vector3.FromArrayToRef(array, offset, result);
  3156. };
  3157. /**
  3158. * Sets the given vector "result" with the given floats.
  3159. * @param x defines the x coordinate of the source
  3160. * @param y defines the y coordinate of the source
  3161. * @param z defines the z coordinate of the source
  3162. * @param result defines the Vector3 where to store the result
  3163. */
  3164. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3165. result.x = x;
  3166. result.y = y;
  3167. result.z = z;
  3168. };
  3169. /**
  3170. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3171. * @returns a new empty Vector3
  3172. */
  3173. Vector3.Zero = function () {
  3174. return new Vector3(0.0, 0.0, 0.0);
  3175. };
  3176. /**
  3177. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3178. * @returns a new unit Vector3
  3179. */
  3180. Vector3.One = function () {
  3181. return new Vector3(1.0, 1.0, 1.0);
  3182. };
  3183. /**
  3184. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3185. * @returns a new up Vector3
  3186. */
  3187. Vector3.Up = function () {
  3188. return new Vector3(0.0, 1.0, 0.0);
  3189. };
  3190. /**
  3191. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3192. * @returns a new forward Vector3
  3193. */
  3194. Vector3.Forward = function () {
  3195. return new Vector3(0.0, 0.0, 1.0);
  3196. };
  3197. /**
  3198. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3199. * @returns a new right Vector3
  3200. */
  3201. Vector3.Right = function () {
  3202. return new Vector3(1.0, 0.0, 0.0);
  3203. };
  3204. /**
  3205. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3206. * @returns a new left Vector3
  3207. */
  3208. Vector3.Left = function () {
  3209. return new Vector3(-1.0, 0.0, 0.0);
  3210. };
  3211. /**
  3212. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3213. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3214. * @param vector defines the Vector3 to transform
  3215. * @param transformation defines the transformation matrix
  3216. * @returns the transformed Vector3
  3217. */
  3218. Vector3.TransformCoordinates = function (vector, transformation) {
  3219. var result = Vector3.Zero();
  3220. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3225. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3226. * @param vector defines the Vector3 to transform
  3227. * @param transformation defines the transformation matrix
  3228. * @param result defines the Vector3 where to store the result
  3229. */
  3230. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3231. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3232. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3233. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3234. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3235. result.x = x / w;
  3236. result.y = y / w;
  3237. result.z = z / w;
  3238. };
  3239. /**
  3240. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3241. * This method computes tranformed coordinates only, not transformed direction vectors
  3242. * @param x define the x coordinate of the source vector
  3243. * @param y define the y coordinate of the source vector
  3244. * @param z define the z coordinate of the source vector
  3245. * @param transformation defines the transformation matrix
  3246. * @param result defines the Vector3 where to store the result
  3247. */
  3248. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3249. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3250. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3251. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3252. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3253. result.x = rx / rw;
  3254. result.y = ry / rw;
  3255. result.z = rz / rw;
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3259. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3260. * @param vector defines the Vector3 to transform
  3261. * @param transformation defines the transformation matrix
  3262. * @returns the new Vector3
  3263. */
  3264. Vector3.TransformNormal = function (vector, transformation) {
  3265. var result = Vector3.Zero();
  3266. Vector3.TransformNormalToRef(vector, transformation, result);
  3267. return result;
  3268. };
  3269. /**
  3270. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3271. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3272. * @param vector defines the Vector3 to transform
  3273. * @param transformation defines the transformation matrix
  3274. * @param result defines the Vector3 where to store the result
  3275. */
  3276. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3277. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3278. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3279. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3280. result.x = x;
  3281. result.y = y;
  3282. result.z = z;
  3283. };
  3284. /**
  3285. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3286. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3287. * @param x define the x coordinate of the source vector
  3288. * @param y define the y coordinate of the source vector
  3289. * @param z define the z coordinate of the source vector
  3290. * @param transformation defines the transformation matrix
  3291. * @param result defines the Vector3 where to store the result
  3292. */
  3293. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3294. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3295. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3296. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3297. };
  3298. /**
  3299. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3300. * @param value1 defines the first control point
  3301. * @param value2 defines the second control point
  3302. * @param value3 defines the third control point
  3303. * @param value4 defines the fourth control point
  3304. * @param amount defines the amount on the spline to use
  3305. * @returns the new Vector3
  3306. */
  3307. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3308. var squared = amount * amount;
  3309. var cubed = amount * squared;
  3310. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3311. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3312. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3313. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3314. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3315. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3316. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3317. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3318. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3319. return new Vector3(x, y, z);
  3320. };
  3321. /**
  3322. * 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"
  3323. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3324. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3325. * @param value defines the current value
  3326. * @param min defines the lower range value
  3327. * @param max defines the upper range value
  3328. * @returns the new Vector3
  3329. */
  3330. Vector3.Clamp = function (value, min, max) {
  3331. var x = value.x;
  3332. x = (x > max.x) ? max.x : x;
  3333. x = (x < min.x) ? min.x : x;
  3334. var y = value.y;
  3335. y = (y > max.y) ? max.y : y;
  3336. y = (y < min.y) ? min.y : y;
  3337. var z = value.z;
  3338. z = (z > max.z) ? max.z : z;
  3339. z = (z < min.z) ? min.z : z;
  3340. return new Vector3(x, y, z);
  3341. };
  3342. /**
  3343. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3344. * @param value1 defines the first control point
  3345. * @param tangent1 defines the first tangent vector
  3346. * @param value2 defines the second control point
  3347. * @param tangent2 defines the second tangent vector
  3348. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3349. * @returns the new Vector3
  3350. */
  3351. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3352. var squared = amount * amount;
  3353. var cubed = amount * squared;
  3354. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3355. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3356. var part3 = (cubed - (2.0 * squared)) + amount;
  3357. var part4 = cubed - squared;
  3358. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3359. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3360. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3361. return new Vector3(x, y, z);
  3362. };
  3363. /**
  3364. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3365. * @param start defines the start value
  3366. * @param end defines the end value
  3367. * @param amount max defines amount between both (between 0 and 1)
  3368. * @returns the new Vector3
  3369. */
  3370. Vector3.Lerp = function (start, end, amount) {
  3371. var result = new Vector3(0, 0, 0);
  3372. Vector3.LerpToRef(start, end, amount, result);
  3373. return result;
  3374. };
  3375. /**
  3376. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3377. * @param start defines the start value
  3378. * @param end defines the end value
  3379. * @param amount max defines amount between both (between 0 and 1)
  3380. * @param result defines the Vector3 where to store the result
  3381. */
  3382. Vector3.LerpToRef = function (start, end, amount, result) {
  3383. result.x = start.x + ((end.x - start.x) * amount);
  3384. result.y = start.y + ((end.y - start.y) * amount);
  3385. result.z = start.z + ((end.z - start.z) * amount);
  3386. };
  3387. /**
  3388. * Returns the dot product (float) between the vectors "left" and "right"
  3389. * @param left defines the left operand
  3390. * @param right defines the right operand
  3391. * @returns the dot product
  3392. */
  3393. Vector3.Dot = function (left, right) {
  3394. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3395. };
  3396. /**
  3397. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3398. * The cross product is then orthogonal to both "left" and "right"
  3399. * @param left defines the left operand
  3400. * @param right defines the right operand
  3401. * @returns the cross product
  3402. */
  3403. Vector3.Cross = function (left, right) {
  3404. var result = Vector3.Zero();
  3405. Vector3.CrossToRef(left, right, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the given vector "result" with the cross product of "left" and "right"
  3410. * The cross product is then orthogonal to both "left" and "right"
  3411. * @param left defines the left operand
  3412. * @param right defines the right operand
  3413. * @param result defines the Vector3 where to store the result
  3414. */
  3415. Vector3.CrossToRef = function (left, right, result) {
  3416. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3417. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3418. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3419. result.copyFrom(MathTmp.Vector3[0]);
  3420. };
  3421. /**
  3422. * Returns a new Vector3 as the normalization of the given vector
  3423. * @param vector defines the Vector3 to normalize
  3424. * @returns the new Vector3
  3425. */
  3426. Vector3.Normalize = function (vector) {
  3427. var result = Vector3.Zero();
  3428. Vector3.NormalizeToRef(vector, result);
  3429. return result;
  3430. };
  3431. /**
  3432. * Sets the given vector "result" with the normalization of the given first vector
  3433. * @param vector defines the Vector3 to normalize
  3434. * @param result defines the Vector3 where to store the result
  3435. */
  3436. Vector3.NormalizeToRef = function (vector, result) {
  3437. result.copyFrom(vector);
  3438. result.normalize();
  3439. };
  3440. /**
  3441. * Project a Vector3 onto screen space
  3442. * @param vector defines the Vector3 to project
  3443. * @param world defines the world matrix to use
  3444. * @param transform defines the transform (view x projection) matrix to use
  3445. * @param viewport defines the screen viewport to use
  3446. * @returns the new Vector3
  3447. */
  3448. Vector3.Project = function (vector, world, transform, viewport) {
  3449. var cw = viewport.width;
  3450. var ch = viewport.height;
  3451. var cx = viewport.x;
  3452. var cy = viewport.y;
  3453. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3454. 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);
  3455. var matrix = MathTmp.Matrix[0];
  3456. world.multiplyToRef(transform, matrix);
  3457. matrix.multiplyToRef(viewportMatrix, matrix);
  3458. return Vector3.TransformCoordinates(vector, matrix);
  3459. };
  3460. /**
  3461. * Unproject from screen space to object space
  3462. * @param source defines the screen space Vector3 to use
  3463. * @param viewportWidth defines the current width of the viewport
  3464. * @param viewportHeight defines the current height of the viewport
  3465. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3466. * @param transform defines the transform (view x projection) matrix to use
  3467. * @returns the new Vector3
  3468. */
  3469. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3470. var matrix = MathTmp.Matrix[0];
  3471. world.multiplyToRef(transform, matrix);
  3472. matrix.invert();
  3473. source.x = source.x / viewportWidth * 2 - 1;
  3474. source.y = -(source.y / viewportHeight * 2 - 1);
  3475. var vector = Vector3.TransformCoordinates(source, matrix);
  3476. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3477. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3478. vector = vector.scale(1.0 / num);
  3479. }
  3480. return vector;
  3481. };
  3482. /**
  3483. * Unproject from screen space to object space
  3484. * @param source defines the screen space Vector3 to use
  3485. * @param viewportWidth defines the current width of the viewport
  3486. * @param viewportHeight defines the current height of the viewport
  3487. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3488. * @param view defines the view matrix to use
  3489. * @param projection defines the projection matrix to use
  3490. * @returns the new Vector3
  3491. */
  3492. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3493. var result = Vector3.Zero();
  3494. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3495. return result;
  3496. };
  3497. /**
  3498. * Unproject from screen space to object space
  3499. * @param source defines the screen space Vector3 to use
  3500. * @param viewportWidth defines the current width of the viewport
  3501. * @param viewportHeight defines the current height of the viewport
  3502. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3503. * @param view defines the view matrix to use
  3504. * @param projection defines the projection matrix to use
  3505. * @param result defines the Vector3 where to store the result
  3506. */
  3507. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3508. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3509. };
  3510. /**
  3511. * Unproject from screen space to object space
  3512. * @param sourceX defines the screen space x coordinate to use
  3513. * @param sourceY defines the screen space y coordinate to use
  3514. * @param sourceZ defines the screen space z coordinate to use
  3515. * @param viewportWidth defines the current width of the viewport
  3516. * @param viewportHeight defines the current height of the viewport
  3517. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3518. * @param view defines the view matrix to use
  3519. * @param projection defines the projection matrix to use
  3520. * @param result defines the Vector3 where to store the result
  3521. */
  3522. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3523. var matrix = MathTmp.Matrix[0];
  3524. world.multiplyToRef(view, matrix);
  3525. matrix.multiplyToRef(projection, matrix);
  3526. matrix.invert();
  3527. var screenSource = MathTmp.Vector3[0];
  3528. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3529. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3530. screenSource.z = 2 * sourceZ - 1.0;
  3531. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3532. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3533. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3534. result.scaleInPlace(1.0 / num);
  3535. }
  3536. };
  3537. /**
  3538. * Gets the minimal coordinate values between two Vector3
  3539. * @param left defines the first operand
  3540. * @param right defines the second operand
  3541. * @returns the new Vector3
  3542. */
  3543. Vector3.Minimize = function (left, right) {
  3544. var min = left.clone();
  3545. min.minimizeInPlace(right);
  3546. return min;
  3547. };
  3548. /**
  3549. * Gets the maximal coordinate values between two Vector3
  3550. * @param left defines the first operand
  3551. * @param right defines the second operand
  3552. * @returns the new Vector3
  3553. */
  3554. Vector3.Maximize = function (left, right) {
  3555. var max = left.clone();
  3556. max.maximizeInPlace(right);
  3557. return max;
  3558. };
  3559. /**
  3560. * Returns the distance between the vectors "value1" and "value2"
  3561. * @param value1 defines the first operand
  3562. * @param value2 defines the second operand
  3563. * @returns the distance
  3564. */
  3565. Vector3.Distance = function (value1, value2) {
  3566. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3567. };
  3568. /**
  3569. * Returns the squared distance between the vectors "value1" and "value2"
  3570. * @param value1 defines the first operand
  3571. * @param value2 defines the second operand
  3572. * @returns the squared distance
  3573. */
  3574. Vector3.DistanceSquared = function (value1, value2) {
  3575. var x = value1.x - value2.x;
  3576. var y = value1.y - value2.y;
  3577. var z = value1.z - value2.z;
  3578. return (x * x) + (y * y) + (z * z);
  3579. };
  3580. /**
  3581. * Returns a new Vector3 located at the center between "value1" and "value2"
  3582. * @param value1 defines the first operand
  3583. * @param value2 defines the second operand
  3584. * @returns the new Vector3
  3585. */
  3586. Vector3.Center = function (value1, value2) {
  3587. var center = value1.add(value2);
  3588. center.scaleInPlace(0.5);
  3589. return center;
  3590. };
  3591. /**
  3592. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3593. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3594. * to something in order to rotate it from its local system to the given target system
  3595. * Note: axis1, axis2 and axis3 are normalized during this operation
  3596. * @param axis1 defines the first axis
  3597. * @param axis2 defines the second axis
  3598. * @param axis3 defines the third axis
  3599. * @returns a new Vector3
  3600. */
  3601. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3602. var rotation = Vector3.Zero();
  3603. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3604. return rotation;
  3605. };
  3606. /**
  3607. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3608. * @param axis1 defines the first axis
  3609. * @param axis2 defines the second axis
  3610. * @param axis3 defines the third axis
  3611. * @param ref defines the Vector3 where to store the result
  3612. */
  3613. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3614. var quat = MathTmp.Quaternion[0];
  3615. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3616. quat.toEulerAnglesToRef(ref);
  3617. };
  3618. return Vector3;
  3619. }());
  3620. BABYLON.Vector3 = Vector3;
  3621. //Vector4 class created for EulerAngle class conversion to Quaternion
  3622. var Vector4 = /** @class */ (function () {
  3623. /**
  3624. * Creates a Vector4 object from the given floats.
  3625. */
  3626. function Vector4(x, y, z, w) {
  3627. this.x = x;
  3628. this.y = y;
  3629. this.z = z;
  3630. this.w = w;
  3631. }
  3632. /**
  3633. * Returns the string with the Vector4 coordinates.
  3634. */
  3635. Vector4.prototype.toString = function () {
  3636. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3637. };
  3638. /**
  3639. * Returns the string "Vector4".
  3640. */
  3641. Vector4.prototype.getClassName = function () {
  3642. return "Vector4";
  3643. };
  3644. /**
  3645. * Returns the Vector4 hash code.
  3646. */
  3647. Vector4.prototype.getHashCode = function () {
  3648. var hash = this.x || 0;
  3649. hash = (hash * 397) ^ (this.y || 0);
  3650. hash = (hash * 397) ^ (this.z || 0);
  3651. hash = (hash * 397) ^ (this.w || 0);
  3652. return hash;
  3653. };
  3654. // Operators
  3655. /**
  3656. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3657. */
  3658. Vector4.prototype.asArray = function () {
  3659. var result = new Array();
  3660. this.toArray(result, 0);
  3661. return result;
  3662. };
  3663. /**
  3664. * Populates the given array from the given index with the Vector4 coordinates.
  3665. * Returns the Vector4.
  3666. */
  3667. Vector4.prototype.toArray = function (array, index) {
  3668. if (index === undefined) {
  3669. index = 0;
  3670. }
  3671. array[index] = this.x;
  3672. array[index + 1] = this.y;
  3673. array[index + 2] = this.z;
  3674. array[index + 3] = this.w;
  3675. return this;
  3676. };
  3677. /**
  3678. * Adds the given vector to the current Vector4.
  3679. * Returns the updated Vector4.
  3680. */
  3681. Vector4.prototype.addInPlace = function (otherVector) {
  3682. this.x += otherVector.x;
  3683. this.y += otherVector.y;
  3684. this.z += otherVector.z;
  3685. this.w += otherVector.w;
  3686. return this;
  3687. };
  3688. /**
  3689. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3690. */
  3691. Vector4.prototype.add = function (otherVector) {
  3692. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3693. };
  3694. /**
  3695. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3696. * Returns the current Vector4.
  3697. */
  3698. Vector4.prototype.addToRef = function (otherVector, result) {
  3699. result.x = this.x + otherVector.x;
  3700. result.y = this.y + otherVector.y;
  3701. result.z = this.z + otherVector.z;
  3702. result.w = this.w + otherVector.w;
  3703. return this;
  3704. };
  3705. /**
  3706. * Subtract in place the given vector from the current Vector4.
  3707. * Returns the updated Vector4.
  3708. */
  3709. Vector4.prototype.subtractInPlace = function (otherVector) {
  3710. this.x -= otherVector.x;
  3711. this.y -= otherVector.y;
  3712. this.z -= otherVector.z;
  3713. this.w -= otherVector.w;
  3714. return this;
  3715. };
  3716. /**
  3717. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3718. */
  3719. Vector4.prototype.subtract = function (otherVector) {
  3720. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3721. };
  3722. /**
  3723. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3724. * Returns the current Vector4.
  3725. */
  3726. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3727. result.x = this.x - otherVector.x;
  3728. result.y = this.y - otherVector.y;
  3729. result.z = this.z - otherVector.z;
  3730. result.w = this.w - otherVector.w;
  3731. return this;
  3732. };
  3733. /**
  3734. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3735. */
  3736. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3737. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3738. };
  3739. /**
  3740. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3741. * Returns the current Vector4.
  3742. */
  3743. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3744. result.x = this.x - x;
  3745. result.y = this.y - y;
  3746. result.z = this.z - z;
  3747. result.w = this.w - w;
  3748. return this;
  3749. };
  3750. /**
  3751. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3752. */
  3753. Vector4.prototype.negate = function () {
  3754. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3755. };
  3756. /**
  3757. * Multiplies the current Vector4 coordinates by scale (float).
  3758. * Returns the updated Vector4.
  3759. */
  3760. Vector4.prototype.scaleInPlace = function (scale) {
  3761. this.x *= scale;
  3762. this.y *= scale;
  3763. this.z *= scale;
  3764. this.w *= scale;
  3765. return this;
  3766. };
  3767. /**
  3768. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3769. */
  3770. Vector4.prototype.scale = function (scale) {
  3771. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3772. };
  3773. /**
  3774. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3775. * Returns the current Vector4.
  3776. */
  3777. Vector4.prototype.scaleToRef = function (scale, result) {
  3778. result.x = this.x * scale;
  3779. result.y = this.y * scale;
  3780. result.z = this.z * scale;
  3781. result.w = this.w * scale;
  3782. return this;
  3783. };
  3784. /**
  3785. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3786. * @param scale defines the scale factor
  3787. * @param result defines the Vector4 object where to store the result
  3788. * @returns the unmodified current Vector4
  3789. */
  3790. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3791. result.x += this.x * scale;
  3792. result.y += this.y * scale;
  3793. result.z += this.z * scale;
  3794. result.w += this.w * scale;
  3795. return this;
  3796. };
  3797. /**
  3798. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3799. */
  3800. Vector4.prototype.equals = function (otherVector) {
  3801. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3802. };
  3803. /**
  3804. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3805. */
  3806. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3807. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3808. return otherVector
  3809. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3810. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3811. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3812. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3813. };
  3814. /**
  3815. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3816. */
  3817. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3818. return this.x === x && this.y === y && this.z === z && this.w === w;
  3819. };
  3820. /**
  3821. * Multiplies in place the current Vector4 by the given one.
  3822. * Returns the updated Vector4.
  3823. */
  3824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3825. this.x *= otherVector.x;
  3826. this.y *= otherVector.y;
  3827. this.z *= otherVector.z;
  3828. this.w *= otherVector.w;
  3829. return this;
  3830. };
  3831. /**
  3832. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3833. */
  3834. Vector4.prototype.multiply = function (otherVector) {
  3835. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3836. };
  3837. /**
  3838. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3839. * Returns the current Vector4.
  3840. */
  3841. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3842. result.x = this.x * otherVector.x;
  3843. result.y = this.y * otherVector.y;
  3844. result.z = this.z * otherVector.z;
  3845. result.w = this.w * otherVector.w;
  3846. return this;
  3847. };
  3848. /**
  3849. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3850. */
  3851. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3852. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3853. };
  3854. /**
  3855. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3856. */
  3857. Vector4.prototype.divide = function (otherVector) {
  3858. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3859. };
  3860. /**
  3861. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3862. * Returns the current Vector4.
  3863. */
  3864. Vector4.prototype.divideToRef = function (otherVector, result) {
  3865. result.x = this.x / otherVector.x;
  3866. result.y = this.y / otherVector.y;
  3867. result.z = this.z / otherVector.z;
  3868. result.w = this.w / otherVector.w;
  3869. return this;
  3870. };
  3871. /**
  3872. * Divides the current Vector3 coordinates by the given ones.
  3873. * @returns the updated Vector3.
  3874. */
  3875. Vector4.prototype.divideInPlace = function (otherVector) {
  3876. return this.divideToRef(otherVector, this);
  3877. };
  3878. /**
  3879. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3880. * @param other defines the second operand
  3881. * @returns the current updated Vector4
  3882. */
  3883. Vector4.prototype.minimizeInPlace = function (other) {
  3884. if (other.x < this.x)
  3885. this.x = other.x;
  3886. if (other.y < this.y)
  3887. this.y = other.y;
  3888. if (other.z < this.z)
  3889. this.z = other.z;
  3890. if (other.w < this.w)
  3891. this.w = other.w;
  3892. return this;
  3893. };
  3894. /**
  3895. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  3896. * @param other defines the second operand
  3897. * @returns the current updated Vector4
  3898. */
  3899. Vector4.prototype.maximizeInPlace = function (other) {
  3900. if (other.x > this.x)
  3901. this.x = other.x;
  3902. if (other.y > this.y)
  3903. this.y = other.y;
  3904. if (other.z > this.z)
  3905. this.z = other.z;
  3906. if (other.w > this.w)
  3907. this.w = other.w;
  3908. return this;
  3909. };
  3910. // Properties
  3911. /**
  3912. * Returns the Vector4 length (float).
  3913. */
  3914. Vector4.prototype.length = function () {
  3915. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3916. };
  3917. /**
  3918. * Returns the Vector4 squared length (float).
  3919. */
  3920. Vector4.prototype.lengthSquared = function () {
  3921. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3922. };
  3923. // Methods
  3924. /**
  3925. * Normalizes in place the Vector4.
  3926. * Returns the updated Vector4.
  3927. */
  3928. Vector4.prototype.normalize = function () {
  3929. var len = this.length();
  3930. if (len === 0)
  3931. return this;
  3932. var num = 1.0 / len;
  3933. this.x *= num;
  3934. this.y *= num;
  3935. this.z *= num;
  3936. this.w *= num;
  3937. return this;
  3938. };
  3939. /**
  3940. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3941. */
  3942. Vector4.prototype.toVector3 = function () {
  3943. return new Vector3(this.x, this.y, this.z);
  3944. };
  3945. /**
  3946. * Returns a new Vector4 copied from the current one.
  3947. */
  3948. Vector4.prototype.clone = function () {
  3949. return new Vector4(this.x, this.y, this.z, this.w);
  3950. };
  3951. /**
  3952. * Updates the current Vector4 with the given one coordinates.
  3953. * Returns the updated Vector4.
  3954. */
  3955. Vector4.prototype.copyFrom = function (source) {
  3956. this.x = source.x;
  3957. this.y = source.y;
  3958. this.z = source.z;
  3959. this.w = source.w;
  3960. return this;
  3961. };
  3962. /**
  3963. * Updates the current Vector4 coordinates with the given floats.
  3964. * Returns the updated Vector4.
  3965. */
  3966. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3967. this.x = x;
  3968. this.y = y;
  3969. this.z = z;
  3970. this.w = w;
  3971. return this;
  3972. };
  3973. /**
  3974. * Updates the current Vector4 coordinates with the given floats.
  3975. * Returns the updated Vector4.
  3976. */
  3977. Vector4.prototype.set = function (x, y, z, w) {
  3978. return this.copyFromFloats(x, y, z, w);
  3979. };
  3980. // Statics
  3981. /**
  3982. * Returns a new Vector4 set from the starting index of the given array.
  3983. */
  3984. Vector4.FromArray = function (array, offset) {
  3985. if (!offset) {
  3986. offset = 0;
  3987. }
  3988. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3989. };
  3990. /**
  3991. * Updates the given vector "result" from the starting index of the given array.
  3992. */
  3993. Vector4.FromArrayToRef = function (array, offset, result) {
  3994. result.x = array[offset];
  3995. result.y = array[offset + 1];
  3996. result.z = array[offset + 2];
  3997. result.w = array[offset + 3];
  3998. };
  3999. /**
  4000. * Updates the given vector "result" from the starting index of the given Float32Array.
  4001. */
  4002. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4003. Vector4.FromArrayToRef(array, offset, result);
  4004. };
  4005. /**
  4006. * Updates the given vector "result" coordinates from the given floats.
  4007. */
  4008. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4009. result.x = x;
  4010. result.y = y;
  4011. result.z = z;
  4012. result.w = w;
  4013. };
  4014. /**
  4015. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4016. */
  4017. Vector4.Zero = function () {
  4018. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4019. };
  4020. /**
  4021. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4022. */
  4023. Vector4.One = function () {
  4024. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4025. };
  4026. /**
  4027. * Returns a new normalized Vector4 from the given one.
  4028. */
  4029. Vector4.Normalize = function (vector) {
  4030. var result = Vector4.Zero();
  4031. Vector4.NormalizeToRef(vector, result);
  4032. return result;
  4033. };
  4034. /**
  4035. * Updates the given vector "result" from the normalization of the given one.
  4036. */
  4037. Vector4.NormalizeToRef = function (vector, result) {
  4038. result.copyFrom(vector);
  4039. result.normalize();
  4040. };
  4041. Vector4.Minimize = function (left, right) {
  4042. var min = left.clone();
  4043. min.minimizeInPlace(right);
  4044. return min;
  4045. };
  4046. Vector4.Maximize = function (left, right) {
  4047. var max = left.clone();
  4048. max.maximizeInPlace(right);
  4049. return max;
  4050. };
  4051. /**
  4052. * Returns the distance (float) between the vectors "value1" and "value2".
  4053. */
  4054. Vector4.Distance = function (value1, value2) {
  4055. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4056. };
  4057. /**
  4058. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4059. */
  4060. Vector4.DistanceSquared = function (value1, value2) {
  4061. var x = value1.x - value2.x;
  4062. var y = value1.y - value2.y;
  4063. var z = value1.z - value2.z;
  4064. var w = value1.w - value2.w;
  4065. return (x * x) + (y * y) + (z * z) + (w * w);
  4066. };
  4067. /**
  4068. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4069. */
  4070. Vector4.Center = function (value1, value2) {
  4071. var center = value1.add(value2);
  4072. center.scaleInPlace(0.5);
  4073. return center;
  4074. };
  4075. /**
  4076. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4077. * This methods computes transformed normalized direction vectors only.
  4078. */
  4079. Vector4.TransformNormal = function (vector, transformation) {
  4080. var result = Vector4.Zero();
  4081. Vector4.TransformNormalToRef(vector, transformation, result);
  4082. return result;
  4083. };
  4084. /**
  4085. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4086. * This methods computes transformed normalized direction vectors only.
  4087. */
  4088. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4089. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4090. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4091. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4092. result.x = x;
  4093. result.y = y;
  4094. result.z = z;
  4095. result.w = vector.w;
  4096. };
  4097. /**
  4098. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4099. * This methods computes transformed normalized direction vectors only.
  4100. */
  4101. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4102. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4103. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4104. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4105. result.w = w;
  4106. };
  4107. return Vector4;
  4108. }());
  4109. BABYLON.Vector4 = Vector4;
  4110. var Size = /** @class */ (function () {
  4111. /**
  4112. * Creates a Size object from the given width and height (floats).
  4113. */
  4114. function Size(width, height) {
  4115. this.width = width;
  4116. this.height = height;
  4117. }
  4118. // Returns a string with the Size width and height.
  4119. Size.prototype.toString = function () {
  4120. return "{W: " + this.width + ", H: " + this.height + "}";
  4121. };
  4122. /**
  4123. * Returns the string "Size"
  4124. */
  4125. Size.prototype.getClassName = function () {
  4126. return "Size";
  4127. };
  4128. /**
  4129. * Returns the Size hash code.
  4130. */
  4131. Size.prototype.getHashCode = function () {
  4132. var hash = this.width || 0;
  4133. hash = (hash * 397) ^ (this.height || 0);
  4134. return hash;
  4135. };
  4136. /**
  4137. * Updates the current size from the given one.
  4138. * Returns the updated Size.
  4139. */
  4140. Size.prototype.copyFrom = function (src) {
  4141. this.width = src.width;
  4142. this.height = src.height;
  4143. };
  4144. /**
  4145. * Updates in place the current Size from the given floats.
  4146. * Returns the updated Size.
  4147. */
  4148. Size.prototype.copyFromFloats = function (width, height) {
  4149. this.width = width;
  4150. this.height = height;
  4151. return this;
  4152. };
  4153. /**
  4154. * Updates in place the current Size from the given floats.
  4155. * Returns the updated Size.
  4156. */
  4157. Size.prototype.set = function (width, height) {
  4158. return this.copyFromFloats(width, height);
  4159. };
  4160. /**
  4161. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4162. */
  4163. Size.prototype.multiplyByFloats = function (w, h) {
  4164. return new Size(this.width * w, this.height * h);
  4165. };
  4166. /**
  4167. * Returns a new Size copied from the given one.
  4168. */
  4169. Size.prototype.clone = function () {
  4170. return new Size(this.width, this.height);
  4171. };
  4172. /**
  4173. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4174. */
  4175. Size.prototype.equals = function (other) {
  4176. if (!other) {
  4177. return false;
  4178. }
  4179. return (this.width === other.width) && (this.height === other.height);
  4180. };
  4181. Object.defineProperty(Size.prototype, "surface", {
  4182. /**
  4183. * Returns the surface of the Size : width * height (float).
  4184. */
  4185. get: function () {
  4186. return this.width * this.height;
  4187. },
  4188. enumerable: true,
  4189. configurable: true
  4190. });
  4191. /**
  4192. * Returns a new Size set to (0.0, 0.0)
  4193. */
  4194. Size.Zero = function () {
  4195. return new Size(0.0, 0.0);
  4196. };
  4197. /**
  4198. * Returns a new Size set as the addition result of the current Size and the given one.
  4199. */
  4200. Size.prototype.add = function (otherSize) {
  4201. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4202. return r;
  4203. };
  4204. /**
  4205. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4206. */
  4207. Size.prototype.subtract = function (otherSize) {
  4208. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4209. return r;
  4210. };
  4211. /**
  4212. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4213. */
  4214. Size.Lerp = function (start, end, amount) {
  4215. var w = start.width + ((end.width - start.width) * amount);
  4216. var h = start.height + ((end.height - start.height) * amount);
  4217. return new Size(w, h);
  4218. };
  4219. return Size;
  4220. }());
  4221. BABYLON.Size = Size;
  4222. /**
  4223. * Class used to store quaternion data
  4224. * @see https://en.wikipedia.org/wiki/Quaternion
  4225. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4226. */
  4227. var Quaternion = /** @class */ (function () {
  4228. /**
  4229. * Creates a new Quaternion from the given floats
  4230. * @param x defines the first component (0 by default)
  4231. * @param y defines the second component (0 by default)
  4232. * @param z defines the third component (0 by default)
  4233. * @param w defines the fourth component (1.0 by default)
  4234. */
  4235. function Quaternion(
  4236. /** defines the first component (0 by default) */
  4237. x,
  4238. /** defines the second component (0 by default) */
  4239. y,
  4240. /** defines the third component (0 by default) */
  4241. z,
  4242. /** defines the fourth component (1.0 by default) */
  4243. w) {
  4244. if (x === void 0) { x = 0.0; }
  4245. if (y === void 0) { y = 0.0; }
  4246. if (z === void 0) { z = 0.0; }
  4247. if (w === void 0) { w = 1.0; }
  4248. this.x = x;
  4249. this.y = y;
  4250. this.z = z;
  4251. this.w = w;
  4252. }
  4253. /**
  4254. * Gets a string representation for the current quaternion
  4255. * @returns a string with the Quaternion coordinates
  4256. */
  4257. Quaternion.prototype.toString = function () {
  4258. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4259. };
  4260. /**
  4261. * Gets the class name of the quaternion
  4262. * @returns the string "Quaternion"
  4263. */
  4264. Quaternion.prototype.getClassName = function () {
  4265. return "Quaternion";
  4266. };
  4267. /**
  4268. * Gets a hash code for this quaternion
  4269. * @returns the quaternion hash code
  4270. */
  4271. Quaternion.prototype.getHashCode = function () {
  4272. var hash = this.x || 0;
  4273. hash = (hash * 397) ^ (this.y || 0);
  4274. hash = (hash * 397) ^ (this.z || 0);
  4275. hash = (hash * 397) ^ (this.w || 0);
  4276. return hash;
  4277. };
  4278. /**
  4279. * Copy the quaternion to an array
  4280. * @returns a new array populated with 4 elements from the quaternion coordinates
  4281. */
  4282. Quaternion.prototype.asArray = function () {
  4283. return [this.x, this.y, this.z, this.w];
  4284. };
  4285. /**
  4286. * Check if two quaternions are equals
  4287. * @param otherQuaternion defines the second operand
  4288. * @return true if the current quaternion and the given one coordinates are strictly equals
  4289. */
  4290. Quaternion.prototype.equals = function (otherQuaternion) {
  4291. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4292. };
  4293. /**
  4294. * Clone the current quaternion
  4295. * @returns a new quaternion copied from the current one
  4296. */
  4297. Quaternion.prototype.clone = function () {
  4298. return new Quaternion(this.x, this.y, this.z, this.w);
  4299. };
  4300. /**
  4301. * Copy a quaternion to the current one
  4302. * @param other defines the other quaternion
  4303. * @returns the updated current quaternion
  4304. */
  4305. Quaternion.prototype.copyFrom = function (other) {
  4306. this.x = other.x;
  4307. this.y = other.y;
  4308. this.z = other.z;
  4309. this.w = other.w;
  4310. return this;
  4311. };
  4312. /**
  4313. * Updates the current quaternion with the given float coordinates
  4314. * @param x defines the x coordinate
  4315. * @param y defines the y coordinate
  4316. * @param z defines the z coordinate
  4317. * @param w defines the w coordinate
  4318. * @returns the updated current quaternion
  4319. */
  4320. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4321. this.x = x;
  4322. this.y = y;
  4323. this.z = z;
  4324. this.w = w;
  4325. return this;
  4326. };
  4327. /**
  4328. * Updates the current quaternion from the given float coordinates
  4329. * @param x defines the x coordinate
  4330. * @param y defines the y coordinate
  4331. * @param z defines the z coordinate
  4332. * @param w defines the w coordinate
  4333. * @returns the updated current quaternion
  4334. */
  4335. Quaternion.prototype.set = function (x, y, z, w) {
  4336. return this.copyFromFloats(x, y, z, w);
  4337. };
  4338. /**
  4339. * Adds two quaternions
  4340. * @param other defines the second operand
  4341. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4342. */
  4343. Quaternion.prototype.add = function (other) {
  4344. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4345. };
  4346. /**
  4347. * Add a quaternion to the current one
  4348. * @param other defines the quaternion to add
  4349. * @returns the current quaternion
  4350. */
  4351. Quaternion.prototype.addInPlace = function (other) {
  4352. this.x += other.x;
  4353. this.y += other.y;
  4354. this.z += other.z;
  4355. this.w += other.w;
  4356. return this;
  4357. };
  4358. /**
  4359. * Subtract two quaternions
  4360. * @param other defines the second operand
  4361. * @returns a new quaternion as the subtraction result of the given one from the current one
  4362. */
  4363. Quaternion.prototype.subtract = function (other) {
  4364. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4365. };
  4366. /**
  4367. * Multiplies the current quaternion by a scale factor
  4368. * @param value defines the scale factor
  4369. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4370. */
  4371. Quaternion.prototype.scale = function (value) {
  4372. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4373. };
  4374. /**
  4375. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4376. * @param scale defines the scale factor
  4377. * @param result defines the Quaternion object where to store the result
  4378. * @returns the unmodified current quaternion
  4379. */
  4380. Quaternion.prototype.scaleToRef = function (scale, result) {
  4381. result.x = this.x * scale;
  4382. result.y = this.y * scale;
  4383. result.z = this.z * scale;
  4384. result.w = this.w * scale;
  4385. return this;
  4386. };
  4387. /**
  4388. * Multiplies in place the current quaternion by a scale factor
  4389. * @param value defines the scale factor
  4390. * @returns the current modified quaternion
  4391. */
  4392. Quaternion.prototype.scaleInPlace = function (value) {
  4393. this.x *= value;
  4394. this.y *= value;
  4395. this.z *= value;
  4396. this.w *= value;
  4397. return this;
  4398. };
  4399. /**
  4400. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4401. * @param scale defines the scale factor
  4402. * @param result defines the Quaternion object where to store the result
  4403. * @returns the unmodified current quaternion
  4404. */
  4405. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4406. result.x += this.x * scale;
  4407. result.y += this.y * scale;
  4408. result.z += this.z * scale;
  4409. result.w += this.w * scale;
  4410. return this;
  4411. };
  4412. /**
  4413. * Multiplies two quaternions
  4414. * @param q1 defines the second operand
  4415. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4416. */
  4417. Quaternion.prototype.multiply = function (q1) {
  4418. var result = new Quaternion(0, 0, 0, 1.0);
  4419. this.multiplyToRef(q1, result);
  4420. return result;
  4421. };
  4422. /**
  4423. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4424. * @param q1 defines the second operand
  4425. * @param result defines the target quaternion
  4426. * @returns the current quaternion
  4427. */
  4428. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4429. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4430. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4431. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4432. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4433. result.copyFromFloats(x, y, z, w);
  4434. return this;
  4435. };
  4436. /**
  4437. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4438. * @param q1 defines the second operand
  4439. * @returns the currentupdated quaternion
  4440. */
  4441. Quaternion.prototype.multiplyInPlace = function (q1) {
  4442. this.multiplyToRef(q1, this);
  4443. return this;
  4444. };
  4445. /**
  4446. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4447. * @param ref defines the target quaternion
  4448. * @returns the current quaternion
  4449. */
  4450. Quaternion.prototype.conjugateToRef = function (ref) {
  4451. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4452. return this;
  4453. };
  4454. /**
  4455. * Conjugates in place (1-q) the current quaternion
  4456. * @returns the current updated quaternion
  4457. */
  4458. Quaternion.prototype.conjugateInPlace = function () {
  4459. this.x *= -1;
  4460. this.y *= -1;
  4461. this.z *= -1;
  4462. return this;
  4463. };
  4464. /**
  4465. * Conjugates in place (1-q) the current quaternion
  4466. * @returns a new quaternion
  4467. */
  4468. Quaternion.prototype.conjugate = function () {
  4469. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4470. return result;
  4471. };
  4472. /**
  4473. * Gets length of current quaternion
  4474. * @returns the quaternion length (float)
  4475. */
  4476. Quaternion.prototype.length = function () {
  4477. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4478. };
  4479. /**
  4480. * Normalize in place the current quaternion
  4481. * @returns the current updated quaternion
  4482. */
  4483. Quaternion.prototype.normalize = function () {
  4484. var length = 1.0 / this.length();
  4485. this.x *= length;
  4486. this.y *= length;
  4487. this.z *= length;
  4488. this.w *= length;
  4489. return this;
  4490. };
  4491. /**
  4492. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4493. * @param order is a reserved parameter and is ignore for now
  4494. * @returns a new Vector3 containing the Euler angles
  4495. */
  4496. Quaternion.prototype.toEulerAngles = function (order) {
  4497. if (order === void 0) { order = "YZX"; }
  4498. var result = Vector3.Zero();
  4499. this.toEulerAnglesToRef(result, order);
  4500. return result;
  4501. };
  4502. /**
  4503. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4504. * @param result defines the vector which will be filled with the Euler angles
  4505. * @param order is a reserved parameter and is ignore for now
  4506. * @returns the current unchanged quaternion
  4507. */
  4508. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4509. if (order === void 0) { order = "YZX"; }
  4510. var qz = this.z;
  4511. var qx = this.x;
  4512. var qy = this.y;
  4513. var qw = this.w;
  4514. var sqw = qw * qw;
  4515. var sqz = qz * qz;
  4516. var sqx = qx * qx;
  4517. var sqy = qy * qy;
  4518. var zAxisY = qy * qz - qx * qw;
  4519. var limit = .4999999;
  4520. if (zAxisY < -limit) {
  4521. result.y = 2 * Math.atan2(qy, qw);
  4522. result.x = Math.PI / 2;
  4523. result.z = 0;
  4524. }
  4525. else if (zAxisY > limit) {
  4526. result.y = 2 * Math.atan2(qy, qw);
  4527. result.x = -Math.PI / 2;
  4528. result.z = 0;
  4529. }
  4530. else {
  4531. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4532. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4533. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4534. }
  4535. return this;
  4536. };
  4537. /**
  4538. * Updates the given rotation matrix with the current quaternion values
  4539. * @param result defines the target matrix
  4540. * @returns the current unchanged quaternion
  4541. */
  4542. Quaternion.prototype.toRotationMatrix = function (result) {
  4543. var xx = this.x * this.x;
  4544. var yy = this.y * this.y;
  4545. var zz = this.z * this.z;
  4546. var xy = this.x * this.y;
  4547. var zw = this.z * this.w;
  4548. var zx = this.z * this.x;
  4549. var yw = this.y * this.w;
  4550. var yz = this.y * this.z;
  4551. var xw = this.x * this.w;
  4552. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4553. result.m[1] = 2.0 * (xy + zw);
  4554. result.m[2] = 2.0 * (zx - yw);
  4555. result.m[3] = 0;
  4556. result.m[4] = 2.0 * (xy - zw);
  4557. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4558. result.m[6] = 2.0 * (yz + xw);
  4559. result.m[7] = 0;
  4560. result.m[8] = 2.0 * (zx + yw);
  4561. result.m[9] = 2.0 * (yz - xw);
  4562. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4563. result.m[11] = 0;
  4564. result.m[12] = 0;
  4565. result.m[13] = 0;
  4566. result.m[14] = 0;
  4567. result.m[15] = 1.0;
  4568. result._markAsUpdated();
  4569. return this;
  4570. };
  4571. /**
  4572. * Updates the current quaternion from the given rotation matrix values
  4573. * @param matrix defines the source matrix
  4574. * @returns the current updated quaternion
  4575. */
  4576. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4577. Quaternion.FromRotationMatrixToRef(matrix, this);
  4578. return this;
  4579. };
  4580. // Statics
  4581. /**
  4582. * Creates a new quaternion from a rotation matrix
  4583. * @param matrix defines the source matrix
  4584. * @returns a new quaternion created from the given rotation matrix values
  4585. */
  4586. Quaternion.FromRotationMatrix = function (matrix) {
  4587. var result = new Quaternion();
  4588. Quaternion.FromRotationMatrixToRef(matrix, result);
  4589. return result;
  4590. };
  4591. /**
  4592. * Updates the given quaternion with the given rotation matrix values
  4593. * @param matrix defines the source matrix
  4594. * @param result defines the target quaternion
  4595. */
  4596. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4597. var data = matrix.m;
  4598. var m11 = data[0], m12 = data[4], m13 = data[8];
  4599. var m21 = data[1], m22 = data[5], m23 = data[9];
  4600. var m31 = data[2], m32 = data[6], m33 = data[10];
  4601. var trace = m11 + m22 + m33;
  4602. var s;
  4603. if (trace > 0) {
  4604. s = 0.5 / Math.sqrt(trace + 1.0);
  4605. result.w = 0.25 / s;
  4606. result.x = (m32 - m23) * s;
  4607. result.y = (m13 - m31) * s;
  4608. result.z = (m21 - m12) * s;
  4609. }
  4610. else if (m11 > m22 && m11 > m33) {
  4611. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4612. result.w = (m32 - m23) / s;
  4613. result.x = 0.25 * s;
  4614. result.y = (m12 + m21) / s;
  4615. result.z = (m13 + m31) / s;
  4616. }
  4617. else if (m22 > m33) {
  4618. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4619. result.w = (m13 - m31) / s;
  4620. result.x = (m12 + m21) / s;
  4621. result.y = 0.25 * s;
  4622. result.z = (m23 + m32) / s;
  4623. }
  4624. else {
  4625. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4626. result.w = (m21 - m12) / s;
  4627. result.x = (m13 + m31) / s;
  4628. result.y = (m23 + m32) / s;
  4629. result.z = 0.25 * s;
  4630. }
  4631. };
  4632. /**
  4633. * Creates an empty quaternion
  4634. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4635. */
  4636. Quaternion.Zero = function () {
  4637. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4638. };
  4639. /**
  4640. * Inverse a given quaternion
  4641. * @param q defines the source quaternion
  4642. * @returns a new quaternion as the inverted current quaternion
  4643. */
  4644. Quaternion.Inverse = function (q) {
  4645. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4646. };
  4647. /**
  4648. * Creates an identity quaternion
  4649. * @returns the identity quaternion
  4650. */
  4651. Quaternion.Identity = function () {
  4652. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4653. };
  4654. /**
  4655. * Gets a boolean indicating if the given quaternion is identity
  4656. * @param quaternion defines the quaternion to check
  4657. * @returns true if the quaternion is identity
  4658. */
  4659. Quaternion.IsIdentity = function (quaternion) {
  4660. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4661. };
  4662. /**
  4663. * Creates a quaternion from a rotation around an axis
  4664. * @param axis defines the axis to use
  4665. * @param angle defines the angle to use
  4666. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4667. */
  4668. Quaternion.RotationAxis = function (axis, angle) {
  4669. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4670. };
  4671. /**
  4672. * Creates a rotation around an axis and stores it into the given quaternion
  4673. * @param axis defines the axis to use
  4674. * @param angle defines the angle to use
  4675. * @param result defines the target quaternion
  4676. * @returns the target quaternion
  4677. */
  4678. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4679. var sin = Math.sin(angle / 2);
  4680. axis.normalize();
  4681. result.w = Math.cos(angle / 2);
  4682. result.x = axis.x * sin;
  4683. result.y = axis.y * sin;
  4684. result.z = axis.z * sin;
  4685. return result;
  4686. };
  4687. /**
  4688. * Creates a new quaternion from data stored into an array
  4689. * @param array defines the data source
  4690. * @param offset defines the offset in the source array where the data starts
  4691. * @returns a new quaternion
  4692. */
  4693. Quaternion.FromArray = function (array, offset) {
  4694. if (!offset) {
  4695. offset = 0;
  4696. }
  4697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4698. };
  4699. /**
  4700. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4701. * @param yaw defines the rotation around Y axis
  4702. * @param pitch defines the rotation around X axis
  4703. * @param roll defines the rotation around Z axis
  4704. * @returns the new quaternion
  4705. */
  4706. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4707. var q = new Quaternion();
  4708. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4709. return q;
  4710. };
  4711. /**
  4712. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4713. * @param yaw defines the rotation around Y axis
  4714. * @param pitch defines the rotation around X axis
  4715. * @param roll defines the rotation around Z axis
  4716. * @param result defines the target quaternion
  4717. */
  4718. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4719. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4720. var halfRoll = roll * 0.5;
  4721. var halfPitch = pitch * 0.5;
  4722. var halfYaw = yaw * 0.5;
  4723. var sinRoll = Math.sin(halfRoll);
  4724. var cosRoll = Math.cos(halfRoll);
  4725. var sinPitch = Math.sin(halfPitch);
  4726. var cosPitch = Math.cos(halfPitch);
  4727. var sinYaw = Math.sin(halfYaw);
  4728. var cosYaw = Math.cos(halfYaw);
  4729. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4730. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4731. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4732. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4733. };
  4734. /**
  4735. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4736. * @param alpha defines the rotation around first axis
  4737. * @param beta defines the rotation around second axis
  4738. * @param gamma defines the rotation around third axis
  4739. * @returns the new quaternion
  4740. */
  4741. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4742. var result = new Quaternion();
  4743. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4744. return result;
  4745. };
  4746. /**
  4747. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4748. * @param alpha defines the rotation around first axis
  4749. * @param beta defines the rotation around second axis
  4750. * @param gamma defines the rotation around third axis
  4751. * @param result defines the target quaternion
  4752. */
  4753. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4754. // Produces a quaternion from Euler angles in the z-x-z orientation
  4755. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4756. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4757. var halfBeta = beta * 0.5;
  4758. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4759. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4760. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4761. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4762. };
  4763. /**
  4764. * 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)
  4765. * @param axis1 defines the first axis
  4766. * @param axis2 defines the second axis
  4767. * @param axis3 defines the third axis
  4768. * @returns the new quaternion
  4769. */
  4770. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4771. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4772. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4773. return quat;
  4774. };
  4775. /**
  4776. * 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
  4777. * @param axis1 defines the first axis
  4778. * @param axis2 defines the second axis
  4779. * @param axis3 defines the third axis
  4780. * @param ref defines the target quaternion
  4781. */
  4782. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4783. var rotMat = MathTmp.Matrix[0];
  4784. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4785. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4786. };
  4787. /**
  4788. * Interpolates between two quaternions
  4789. * @param left defines first quaternion
  4790. * @param right defines second quaternion
  4791. * @param amount defines the gradient to use
  4792. * @returns the new interpolated quaternion
  4793. */
  4794. Quaternion.Slerp = function (left, right, amount) {
  4795. var result = Quaternion.Identity();
  4796. Quaternion.SlerpToRef(left, right, amount, result);
  4797. return result;
  4798. };
  4799. /**
  4800. * Interpolates between two quaternions and stores it into a target quaternion
  4801. * @param left defines first quaternion
  4802. * @param right defines second quaternion
  4803. * @param amount defines the gradient to use
  4804. * @param result defines the target quaternion
  4805. */
  4806. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4807. var num2;
  4808. var num3;
  4809. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4810. var flag = false;
  4811. if (num4 < 0) {
  4812. flag = true;
  4813. num4 = -num4;
  4814. }
  4815. if (num4 > 0.999999) {
  4816. num3 = 1 - amount;
  4817. num2 = flag ? -amount : amount;
  4818. }
  4819. else {
  4820. var num5 = Math.acos(num4);
  4821. var num6 = (1.0 / Math.sin(num5));
  4822. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4823. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4824. }
  4825. result.x = (num3 * left.x) + (num2 * right.x);
  4826. result.y = (num3 * left.y) + (num2 * right.y);
  4827. result.z = (num3 * left.z) + (num2 * right.z);
  4828. result.w = (num3 * left.w) + (num2 * right.w);
  4829. };
  4830. /**
  4831. * Interpolate between two quaternions using Hermite interpolation
  4832. * @param value1 defines first quaternion
  4833. * @param tangent1 defines the incoming tangent
  4834. * @param value2 defines second quaternion
  4835. * @param tangent2 defines the outgoing tangent
  4836. * @param amount defines the target quaternion
  4837. * @returns the new interpolated quaternion
  4838. */
  4839. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4840. var squared = amount * amount;
  4841. var cubed = amount * squared;
  4842. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4843. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4844. var part3 = (cubed - (2.0 * squared)) + amount;
  4845. var part4 = cubed - squared;
  4846. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4847. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4848. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4849. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4850. return new Quaternion(x, y, z, w);
  4851. };
  4852. return Quaternion;
  4853. }());
  4854. BABYLON.Quaternion = Quaternion;
  4855. /**
  4856. * Class used to store matrix data (4x4)
  4857. */
  4858. var Matrix = /** @class */ (function () {
  4859. /**
  4860. * Creates an empty matrix (filled with zeros)
  4861. */
  4862. function Matrix() {
  4863. this._isIdentity = false;
  4864. this._isIdentityDirty = true;
  4865. /**
  4866. * Gets or sets the internal data of the matrix
  4867. */
  4868. this.m = new Float32Array(16);
  4869. this._markAsUpdated();
  4870. }
  4871. /** @ignore */
  4872. Matrix.prototype._markAsUpdated = function () {
  4873. this.updateFlag = Matrix._updateFlagSeed++;
  4874. this._isIdentityDirty = true;
  4875. };
  4876. // Properties
  4877. /**
  4878. * Check if the current matrix is indentity
  4879. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4880. * @returns true is the matrix is the identity matrix
  4881. */
  4882. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4883. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4884. if (this._isIdentityDirty) {
  4885. this._isIdentityDirty = false;
  4886. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4887. this._isIdentity = false;
  4888. }
  4889. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4890. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4891. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4892. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4893. this._isIdentity = false;
  4894. }
  4895. else {
  4896. this._isIdentity = true;
  4897. }
  4898. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4899. this._isIdentity = false;
  4900. }
  4901. }
  4902. return this._isIdentity;
  4903. };
  4904. /**
  4905. * Gets the determinant of the matrix
  4906. * @returns the matrix determinant
  4907. */
  4908. Matrix.prototype.determinant = function () {
  4909. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4910. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4911. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4912. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4913. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4914. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4915. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4916. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4917. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4918. };
  4919. // Methods
  4920. /**
  4921. * Returns the matrix as a Float32Array
  4922. * @returns the matrix underlying array
  4923. */
  4924. Matrix.prototype.toArray = function () {
  4925. return this.m;
  4926. };
  4927. /**
  4928. * Returns the matrix as a Float32Array
  4929. * @returns the matrix underlying array.
  4930. */
  4931. Matrix.prototype.asArray = function () {
  4932. return this.toArray();
  4933. };
  4934. /**
  4935. * Inverts the current matrix in place
  4936. * @returns the current inverted matrix
  4937. */
  4938. Matrix.prototype.invert = function () {
  4939. this.invertToRef(this);
  4940. return this;
  4941. };
  4942. /**
  4943. * Sets all the matrix elements to zero
  4944. * @returns the current matrix
  4945. */
  4946. Matrix.prototype.reset = function () {
  4947. for (var index = 0; index < 16; index++) {
  4948. this.m[index] = 0.0;
  4949. }
  4950. this._markAsUpdated();
  4951. return this;
  4952. };
  4953. /**
  4954. * Adds the current matrix with a second one
  4955. * @param other defines the matrix to add
  4956. * @returns a new matrix as the addition of the current matrix and the given one
  4957. */
  4958. Matrix.prototype.add = function (other) {
  4959. var result = new Matrix();
  4960. this.addToRef(other, result);
  4961. return result;
  4962. };
  4963. /**
  4964. * Sets the given matrix "result" to the addition of the current matrix and the given one
  4965. * @param other defines the matrix to add
  4966. * @param result defines the target matrix
  4967. * @returns the current matrix
  4968. */
  4969. Matrix.prototype.addToRef = function (other, result) {
  4970. for (var index = 0; index < 16; index++) {
  4971. result.m[index] = this.m[index] + other.m[index];
  4972. }
  4973. result._markAsUpdated();
  4974. return this;
  4975. };
  4976. /**
  4977. * Adds in place the given matrix to the current matrix
  4978. * @param other defines the second operand
  4979. * @returns the current updated matrix
  4980. */
  4981. Matrix.prototype.addToSelf = function (other) {
  4982. for (var index = 0; index < 16; index++) {
  4983. this.m[index] += other.m[index];
  4984. }
  4985. this._markAsUpdated();
  4986. return this;
  4987. };
  4988. /**
  4989. * Sets the given matrix to the current inverted Matrix
  4990. * @param other defines the target matrix
  4991. * @returns the unmodified current matrix
  4992. */
  4993. Matrix.prototype.invertToRef = function (other) {
  4994. var l1 = this.m[0];
  4995. var l2 = this.m[1];
  4996. var l3 = this.m[2];
  4997. var l4 = this.m[3];
  4998. var l5 = this.m[4];
  4999. var l6 = this.m[5];
  5000. var l7 = this.m[6];
  5001. var l8 = this.m[7];
  5002. var l9 = this.m[8];
  5003. var l10 = this.m[9];
  5004. var l11 = this.m[10];
  5005. var l12 = this.m[11];
  5006. var l13 = this.m[12];
  5007. var l14 = this.m[13];
  5008. var l15 = this.m[14];
  5009. var l16 = this.m[15];
  5010. var l17 = (l11 * l16) - (l12 * l15);
  5011. var l18 = (l10 * l16) - (l12 * l14);
  5012. var l19 = (l10 * l15) - (l11 * l14);
  5013. var l20 = (l9 * l16) - (l12 * l13);
  5014. var l21 = (l9 * l15) - (l11 * l13);
  5015. var l22 = (l9 * l14) - (l10 * l13);
  5016. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5017. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5018. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5019. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5020. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5021. var l28 = (l7 * l16) - (l8 * l15);
  5022. var l29 = (l6 * l16) - (l8 * l14);
  5023. var l30 = (l6 * l15) - (l7 * l14);
  5024. var l31 = (l5 * l16) - (l8 * l13);
  5025. var l32 = (l5 * l15) - (l7 * l13);
  5026. var l33 = (l5 * l14) - (l6 * l13);
  5027. var l34 = (l7 * l12) - (l8 * l11);
  5028. var l35 = (l6 * l12) - (l8 * l10);
  5029. var l36 = (l6 * l11) - (l7 * l10);
  5030. var l37 = (l5 * l12) - (l8 * l9);
  5031. var l38 = (l5 * l11) - (l7 * l9);
  5032. var l39 = (l5 * l10) - (l6 * l9);
  5033. other.m[0] = l23 * l27;
  5034. other.m[4] = l24 * l27;
  5035. other.m[8] = l25 * l27;
  5036. other.m[12] = l26 * l27;
  5037. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5038. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5039. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5040. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5041. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5042. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5043. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5044. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5045. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5046. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5047. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5048. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5049. other._markAsUpdated();
  5050. return this;
  5051. };
  5052. /**
  5053. * Inserts the translation vector (using 3 floats) in the current matrix
  5054. * @param x defines the 1st component of the translation
  5055. * @param y defines the 2nd component of the translation
  5056. * @param z defines the 3rd component of the translation
  5057. * @returns the current updated matrix
  5058. */
  5059. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5060. this.m[12] = x;
  5061. this.m[13] = y;
  5062. this.m[14] = z;
  5063. this._markAsUpdated();
  5064. return this;
  5065. };
  5066. /**
  5067. * Inserts the translation vector in the current matrix
  5068. * @param vector3 defines the translation to insert
  5069. * @returns the current updated matrix
  5070. */
  5071. Matrix.prototype.setTranslation = function (vector3) {
  5072. this.m[12] = vector3.x;
  5073. this.m[13] = vector3.y;
  5074. this.m[14] = vector3.z;
  5075. this._markAsUpdated();
  5076. return this;
  5077. };
  5078. /**
  5079. * Gets the translation value of the current matrix
  5080. * @returns a new Vector3 as the extracted translation from the matrix
  5081. */
  5082. Matrix.prototype.getTranslation = function () {
  5083. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5084. };
  5085. /**
  5086. * Fill a Vector3 with the extracted translation from the matrix
  5087. * @param result defines the Vector3 where to store the translation
  5088. * @returns the current matrix
  5089. */
  5090. Matrix.prototype.getTranslationToRef = function (result) {
  5091. result.x = this.m[12];
  5092. result.y = this.m[13];
  5093. result.z = this.m[14];
  5094. return this;
  5095. };
  5096. /**
  5097. * Remove rotation and scaling part from the matrix
  5098. * @returns the updated matrix
  5099. */
  5100. Matrix.prototype.removeRotationAndScaling = function () {
  5101. this.setRowFromFloats(0, 1, 0, 0, 0);
  5102. this.setRowFromFloats(1, 0, 1, 0, 0);
  5103. this.setRowFromFloats(2, 0, 0, 1, 0);
  5104. return this;
  5105. };
  5106. /**
  5107. * Multiply two matrices
  5108. * @param other defines the second operand
  5109. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5110. */
  5111. Matrix.prototype.multiply = function (other) {
  5112. var result = new Matrix();
  5113. this.multiplyToRef(other, result);
  5114. return result;
  5115. };
  5116. /**
  5117. * Copy the current matrix from the given one
  5118. * @param other defines the source matrix
  5119. * @returns the current updated matrix
  5120. */
  5121. Matrix.prototype.copyFrom = function (other) {
  5122. for (var index = 0; index < 16; index++) {
  5123. this.m[index] = other.m[index];
  5124. }
  5125. this._markAsUpdated();
  5126. return this;
  5127. };
  5128. /**
  5129. * Populates the given array from the starting index with the current matrix values
  5130. * @param array defines the target array
  5131. * @param offset defines the offset in the target array where to start storing values
  5132. * @returns the current matrix
  5133. */
  5134. Matrix.prototype.copyToArray = function (array, offset) {
  5135. if (offset === void 0) { offset = 0; }
  5136. for (var index = 0; index < 16; index++) {
  5137. array[offset + index] = this.m[index];
  5138. }
  5139. return this;
  5140. };
  5141. /**
  5142. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5143. * @param other defines the second operand
  5144. * @param result defines the matrix where to store the multiplication
  5145. * @returns the current matrix
  5146. */
  5147. Matrix.prototype.multiplyToRef = function (other, result) {
  5148. this.multiplyToArray(other, result.m, 0);
  5149. result._markAsUpdated();
  5150. return this;
  5151. };
  5152. /**
  5153. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5154. * @param other defines the second operand
  5155. * @param result defines the array where to store the multiplication
  5156. * @param offset defines the offset in the target array where to start storing values
  5157. * @returns the current matrix
  5158. */
  5159. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5160. var tm0 = this.m[0];
  5161. var tm1 = this.m[1];
  5162. var tm2 = this.m[2];
  5163. var tm3 = this.m[3];
  5164. var tm4 = this.m[4];
  5165. var tm5 = this.m[5];
  5166. var tm6 = this.m[6];
  5167. var tm7 = this.m[7];
  5168. var tm8 = this.m[8];
  5169. var tm9 = this.m[9];
  5170. var tm10 = this.m[10];
  5171. var tm11 = this.m[11];
  5172. var tm12 = this.m[12];
  5173. var tm13 = this.m[13];
  5174. var tm14 = this.m[14];
  5175. var tm15 = this.m[15];
  5176. var om0 = other.m[0];
  5177. var om1 = other.m[1];
  5178. var om2 = other.m[2];
  5179. var om3 = other.m[3];
  5180. var om4 = other.m[4];
  5181. var om5 = other.m[5];
  5182. var om6 = other.m[6];
  5183. var om7 = other.m[7];
  5184. var om8 = other.m[8];
  5185. var om9 = other.m[9];
  5186. var om10 = other.m[10];
  5187. var om11 = other.m[11];
  5188. var om12 = other.m[12];
  5189. var om13 = other.m[13];
  5190. var om14 = other.m[14];
  5191. var om15 = other.m[15];
  5192. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5193. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5194. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5195. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5196. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5197. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5198. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5199. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5200. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5201. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5202. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5203. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5204. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5205. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5206. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5207. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5208. return this;
  5209. };
  5210. /**
  5211. * Check equality between this matrix and a second one
  5212. * @param value defines the second matrix to compare
  5213. * @returns true is the current matrix and the given one values are strictly equal
  5214. */
  5215. Matrix.prototype.equals = function (value) {
  5216. return value &&
  5217. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5218. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5219. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5220. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5221. };
  5222. /**
  5223. * Clone the current matrix
  5224. * @returns a new matrix from the current matrix
  5225. */
  5226. Matrix.prototype.clone = function () {
  5227. 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]);
  5228. };
  5229. /**
  5230. * Returns the name of the current matrix class
  5231. * @returns the string "Matrix"
  5232. */
  5233. Matrix.prototype.getClassName = function () {
  5234. return "Matrix";
  5235. };
  5236. /**
  5237. * Gets the hash code of the current matrix
  5238. * @returns the hash code
  5239. */
  5240. Matrix.prototype.getHashCode = function () {
  5241. var hash = this.m[0] || 0;
  5242. for (var i = 1; i < 16; i++) {
  5243. hash = (hash * 397) ^ (this.m[i] || 0);
  5244. }
  5245. return hash;
  5246. };
  5247. /**
  5248. * Decomposes the current Matrix into a translation, rotation and scaling components
  5249. * @param scale defines the scale vector3 given as a reference to update
  5250. * @param rotation defines the rotation quaternion given as a reference to update
  5251. * @param translation defines the translation vector3 given as a reference to update
  5252. * @returns true if operation was successful
  5253. */
  5254. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5255. if (translation) {
  5256. translation.x = this.m[12];
  5257. translation.y = this.m[13];
  5258. translation.z = this.m[14];
  5259. }
  5260. scale = scale || MathTmp.Vector3[0];
  5261. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5262. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5263. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5264. if (this.determinant() <= 0) {
  5265. scale.y *= -1;
  5266. }
  5267. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5268. if (rotation) {
  5269. rotation.x = 0;
  5270. rotation.y = 0;
  5271. rotation.z = 0;
  5272. rotation.w = 1;
  5273. }
  5274. return false;
  5275. }
  5276. if (rotation) {
  5277. 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]);
  5278. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5279. }
  5280. return true;
  5281. };
  5282. /**
  5283. * Gets specific row of the matrix
  5284. * @param index defines the number of the row to get
  5285. * @returns the index-th row of the current matrix as a new Vector4
  5286. */
  5287. Matrix.prototype.getRow = function (index) {
  5288. if (index < 0 || index > 3) {
  5289. return null;
  5290. }
  5291. var i = index * 4;
  5292. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5293. };
  5294. /**
  5295. * Sets the index-th row of the current matrix to the vector4 values
  5296. * @param index defines the number of the row to set
  5297. * @param row defines the target vector4
  5298. * @returns the updated current matrix
  5299. */
  5300. Matrix.prototype.setRow = function (index, row) {
  5301. if (index < 0 || index > 3) {
  5302. return this;
  5303. }
  5304. var i = index * 4;
  5305. this.m[i + 0] = row.x;
  5306. this.m[i + 1] = row.y;
  5307. this.m[i + 2] = row.z;
  5308. this.m[i + 3] = row.w;
  5309. this._markAsUpdated();
  5310. return this;
  5311. };
  5312. /**
  5313. * Compute the transpose of the matrix
  5314. * @returns the new transposed matrix
  5315. */
  5316. Matrix.prototype.transpose = function () {
  5317. return Matrix.Transpose(this);
  5318. };
  5319. /**
  5320. * Compute the transpose of the matrix and store it in a given matrix
  5321. * @param result defines the target matrix
  5322. * @returns the current matrix
  5323. */
  5324. Matrix.prototype.transposeToRef = function (result) {
  5325. Matrix.TransposeToRef(this, result);
  5326. return this;
  5327. };
  5328. /**
  5329. * Sets the index-th row of the current matrix with the given 4 x float values
  5330. * @param index defines the row index
  5331. * @param x defines the x component to set
  5332. * @param y defines the y component to set
  5333. * @param z defines the z component to set
  5334. * @param w defines the w component to set
  5335. * @returns the updated current matrix
  5336. */
  5337. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5338. if (index < 0 || index > 3) {
  5339. return this;
  5340. }
  5341. var i = index * 4;
  5342. this.m[i + 0] = x;
  5343. this.m[i + 1] = y;
  5344. this.m[i + 2] = z;
  5345. this.m[i + 3] = w;
  5346. this._markAsUpdated();
  5347. return this;
  5348. };
  5349. /**
  5350. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5351. * @param scale defines the scale factor
  5352. * @returns a new matrix
  5353. */
  5354. Matrix.prototype.scale = function (scale) {
  5355. var result = new Matrix();
  5356. this.scaleToRef(scale, result);
  5357. return result;
  5358. };
  5359. /**
  5360. * Scale the current matrix values by a factor to a given result matrix
  5361. * @param scale defines the scale factor
  5362. * @param result defines the matrix to store the result
  5363. * @returns the current matrix
  5364. */
  5365. Matrix.prototype.scaleToRef = function (scale, result) {
  5366. for (var index = 0; index < 16; index++) {
  5367. result.m[index] = this.m[index] * scale;
  5368. }
  5369. result._markAsUpdated();
  5370. return this;
  5371. };
  5372. /**
  5373. * Scale the current matrix values by a factor and add the result to a given matrix
  5374. * @param scale defines the scale factor
  5375. * @param result defines the Matrix to store the result
  5376. * @returns the current matrix
  5377. */
  5378. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5379. for (var index = 0; index < 16; index++) {
  5380. result.m[index] += this.m[index] * scale;
  5381. }
  5382. result._markAsUpdated();
  5383. return this;
  5384. };
  5385. /**
  5386. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5387. * @param ref matrix to store the result
  5388. */
  5389. Matrix.prototype.toNormalMatrix = function (ref) {
  5390. this.invertToRef(ref);
  5391. ref.transpose();
  5392. var m = ref.m;
  5393. 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);
  5394. };
  5395. /**
  5396. * Gets only rotation part of the current matrix
  5397. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5398. */
  5399. Matrix.prototype.getRotationMatrix = function () {
  5400. var result = Matrix.Identity();
  5401. this.getRotationMatrixToRef(result);
  5402. return result;
  5403. };
  5404. /**
  5405. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5406. * @param result defines the target matrix to store data to
  5407. * @returns the current matrix
  5408. */
  5409. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5410. var m = this.m;
  5411. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5412. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5413. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5414. if (this.determinant() <= 0) {
  5415. sy *= -1;
  5416. }
  5417. if (sx === 0 || sy === 0 || sz === 0) {
  5418. Matrix.IdentityToRef(result);
  5419. }
  5420. else {
  5421. 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);
  5422. }
  5423. return this;
  5424. };
  5425. // Statics
  5426. /**
  5427. * Creates a matrix from an array
  5428. * @param array defines the source array
  5429. * @param offset defines an offset in the source array
  5430. * @returns a new Matrix set from the starting index of the given array
  5431. */
  5432. Matrix.FromArray = function (array, offset) {
  5433. var result = new Matrix();
  5434. if (!offset) {
  5435. offset = 0;
  5436. }
  5437. Matrix.FromArrayToRef(array, offset, result);
  5438. return result;
  5439. };
  5440. /**
  5441. * Copy the content of an array into a given matrix
  5442. * @param array defines the source array
  5443. * @param offset defines an offset in the source array
  5444. * @param result defines the target matrix
  5445. */
  5446. Matrix.FromArrayToRef = function (array, offset, result) {
  5447. for (var index = 0; index < 16; index++) {
  5448. result.m[index] = array[index + offset];
  5449. }
  5450. result._markAsUpdated();
  5451. };
  5452. /**
  5453. * Stores an array into a matrix after having multiplied each component by a given factor
  5454. * @param array defines the source array
  5455. * @param offset defines the offset in the source array
  5456. * @param scale defines the scaling factor
  5457. * @param result defines the target matrix
  5458. */
  5459. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5460. for (var index = 0; index < 16; index++) {
  5461. result.m[index] = array[index + offset] * scale;
  5462. }
  5463. result._markAsUpdated();
  5464. };
  5465. /**
  5466. * Stores a list of values (16) inside a given matrix
  5467. * @param initialM11 defines 1st value of 1st row
  5468. * @param initialM12 defines 2nd value of 1st row
  5469. * @param initialM13 defines 3rd value of 1st row
  5470. * @param initialM14 defines 4th value of 1st row
  5471. * @param initialM21 defines 1st value of 2nd row
  5472. * @param initialM22 defines 2nd value of 2nd row
  5473. * @param initialM23 defines 3rd value of 2nd row
  5474. * @param initialM24 defines 4th value of 2nd row
  5475. * @param initialM31 defines 1st value of 3rd row
  5476. * @param initialM32 defines 2nd value of 3rd row
  5477. * @param initialM33 defines 3rd value of 3rd row
  5478. * @param initialM34 defines 4th value of 3rd row
  5479. * @param initialM41 defines 1st value of 4th row
  5480. * @param initialM42 defines 2nd value of 4th row
  5481. * @param initialM43 defines 3rd value of 4th row
  5482. * @param initialM44 defines 4th value of 4th row
  5483. * @param result defines the target matrix
  5484. */
  5485. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5486. result.m[0] = initialM11;
  5487. result.m[1] = initialM12;
  5488. result.m[2] = initialM13;
  5489. result.m[3] = initialM14;
  5490. result.m[4] = initialM21;
  5491. result.m[5] = initialM22;
  5492. result.m[6] = initialM23;
  5493. result.m[7] = initialM24;
  5494. result.m[8] = initialM31;
  5495. result.m[9] = initialM32;
  5496. result.m[10] = initialM33;
  5497. result.m[11] = initialM34;
  5498. result.m[12] = initialM41;
  5499. result.m[13] = initialM42;
  5500. result.m[14] = initialM43;
  5501. result.m[15] = initialM44;
  5502. result._markAsUpdated();
  5503. };
  5504. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5505. /**
  5506. * Gets an identity matrix that must not be updated
  5507. */
  5508. get: function () {
  5509. return Matrix._identityReadOnly;
  5510. },
  5511. enumerable: true,
  5512. configurable: true
  5513. });
  5514. /**
  5515. * Creates new matrix from a list of values (16)
  5516. * @param initialM11 defines 1st value of 1st row
  5517. * @param initialM12 defines 2nd value of 1st row
  5518. * @param initialM13 defines 3rd value of 1st row
  5519. * @param initialM14 defines 4th value of 1st row
  5520. * @param initialM21 defines 1st value of 2nd row
  5521. * @param initialM22 defines 2nd value of 2nd row
  5522. * @param initialM23 defines 3rd value of 2nd row
  5523. * @param initialM24 defines 4th value of 2nd row
  5524. * @param initialM31 defines 1st value of 3rd row
  5525. * @param initialM32 defines 2nd value of 3rd row
  5526. * @param initialM33 defines 3rd value of 3rd row
  5527. * @param initialM34 defines 4th value of 3rd row
  5528. * @param initialM41 defines 1st value of 4th row
  5529. * @param initialM42 defines 2nd value of 4th row
  5530. * @param initialM43 defines 3rd value of 4th row
  5531. * @param initialM44 defines 4th value of 4th row
  5532. * @returns the new matrix
  5533. */
  5534. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5535. var result = new Matrix();
  5536. result.m[0] = initialM11;
  5537. result.m[1] = initialM12;
  5538. result.m[2] = initialM13;
  5539. result.m[3] = initialM14;
  5540. result.m[4] = initialM21;
  5541. result.m[5] = initialM22;
  5542. result.m[6] = initialM23;
  5543. result.m[7] = initialM24;
  5544. result.m[8] = initialM31;
  5545. result.m[9] = initialM32;
  5546. result.m[10] = initialM33;
  5547. result.m[11] = initialM34;
  5548. result.m[12] = initialM41;
  5549. result.m[13] = initialM42;
  5550. result.m[14] = initialM43;
  5551. result.m[15] = initialM44;
  5552. return result;
  5553. };
  5554. /**
  5555. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5556. * @param scale defines the scale vector3
  5557. * @param rotation defines the rotation quaternion
  5558. * @param translation defines the translation vector3
  5559. * @returns a new matrix
  5560. */
  5561. Matrix.Compose = function (scale, rotation, translation) {
  5562. var result = Matrix.Identity();
  5563. Matrix.ComposeToRef(scale, rotation, translation, result);
  5564. return result;
  5565. };
  5566. /**
  5567. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5568. * @param scale defines the scale vector3
  5569. * @param rotation defines the rotation quaternion
  5570. * @param translation defines the translation vector3
  5571. * @param result defines the target matrix
  5572. */
  5573. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5574. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5575. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5576. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5577. result.setTranslation(translation);
  5578. };
  5579. /**
  5580. * Creates a new identity matrix
  5581. * @returns a new identity matrix
  5582. */
  5583. Matrix.Identity = function () {
  5584. 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);
  5585. };
  5586. /**
  5587. * Creates a new identity matrix and stores the result in a given matrix
  5588. * @param result defines the target matrix
  5589. */
  5590. Matrix.IdentityToRef = function (result) {
  5591. 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);
  5592. };
  5593. /**
  5594. * Creates a new zero matrix
  5595. * @returns a new zero matrix
  5596. */
  5597. Matrix.Zero = function () {
  5598. 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);
  5599. };
  5600. /**
  5601. * Creates a new rotation matrix for "angle" radians around the X axis
  5602. * @param angle defines the angle (in radians) to use
  5603. * @return the new matrix
  5604. */
  5605. Matrix.RotationX = function (angle) {
  5606. var result = new Matrix();
  5607. Matrix.RotationXToRef(angle, result);
  5608. return result;
  5609. };
  5610. /**
  5611. * Creates a new matrix as the invert of a given matrix
  5612. * @param source defines the source matrix
  5613. * @returns the new matrix
  5614. */
  5615. Matrix.Invert = function (source) {
  5616. var result = new Matrix();
  5617. source.invertToRef(result);
  5618. return result;
  5619. };
  5620. /**
  5621. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5622. * @param angle defines the angle (in radians) to use
  5623. * @param result defines the target matrix
  5624. */
  5625. Matrix.RotationXToRef = function (angle, result) {
  5626. var s = Math.sin(angle);
  5627. var c = Math.cos(angle);
  5628. result.m[0] = 1.0;
  5629. result.m[15] = 1.0;
  5630. result.m[5] = c;
  5631. result.m[10] = c;
  5632. result.m[9] = -s;
  5633. result.m[6] = s;
  5634. result.m[1] = 0.0;
  5635. result.m[2] = 0.0;
  5636. result.m[3] = 0.0;
  5637. result.m[4] = 0.0;
  5638. result.m[7] = 0.0;
  5639. result.m[8] = 0.0;
  5640. result.m[11] = 0.0;
  5641. result.m[12] = 0.0;
  5642. result.m[13] = 0.0;
  5643. result.m[14] = 0.0;
  5644. result._markAsUpdated();
  5645. };
  5646. /**
  5647. * Creates a new rotation matrix for "angle" radians around the Y axis
  5648. * @param angle defines the angle (in radians) to use
  5649. * @return the new matrix
  5650. */
  5651. Matrix.RotationY = function (angle) {
  5652. var result = new Matrix();
  5653. Matrix.RotationYToRef(angle, result);
  5654. return result;
  5655. };
  5656. /**
  5657. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5658. * @param angle defines the angle (in radians) to use
  5659. * @param result defines the target matrix
  5660. */
  5661. Matrix.RotationYToRef = function (angle, result) {
  5662. var s = Math.sin(angle);
  5663. var c = Math.cos(angle);
  5664. result.m[5] = 1.0;
  5665. result.m[15] = 1.0;
  5666. result.m[0] = c;
  5667. result.m[2] = -s;
  5668. result.m[8] = s;
  5669. result.m[10] = c;
  5670. result.m[1] = 0.0;
  5671. result.m[3] = 0.0;
  5672. result.m[4] = 0.0;
  5673. result.m[6] = 0.0;
  5674. result.m[7] = 0.0;
  5675. result.m[9] = 0.0;
  5676. result.m[11] = 0.0;
  5677. result.m[12] = 0.0;
  5678. result.m[13] = 0.0;
  5679. result.m[14] = 0.0;
  5680. result._markAsUpdated();
  5681. };
  5682. /**
  5683. * Creates a new rotation matrix for "angle" radians around the Z axis
  5684. * @param angle defines the angle (in radians) to use
  5685. * @return the new matrix
  5686. */
  5687. Matrix.RotationZ = function (angle) {
  5688. var result = new Matrix();
  5689. Matrix.RotationZToRef(angle, result);
  5690. return result;
  5691. };
  5692. /**
  5693. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5694. * @param angle defines the angle (in radians) to use
  5695. * @param result defines the target matrix
  5696. */
  5697. Matrix.RotationZToRef = function (angle, result) {
  5698. var s = Math.sin(angle);
  5699. var c = Math.cos(angle);
  5700. result.m[10] = 1.0;
  5701. result.m[15] = 1.0;
  5702. result.m[0] = c;
  5703. result.m[1] = s;
  5704. result.m[4] = -s;
  5705. result.m[5] = c;
  5706. result.m[2] = 0.0;
  5707. result.m[3] = 0.0;
  5708. result.m[6] = 0.0;
  5709. result.m[7] = 0.0;
  5710. result.m[8] = 0.0;
  5711. result.m[9] = 0.0;
  5712. result.m[11] = 0.0;
  5713. result.m[12] = 0.0;
  5714. result.m[13] = 0.0;
  5715. result.m[14] = 0.0;
  5716. result._markAsUpdated();
  5717. };
  5718. /**
  5719. * Creates a new rotation matrix for "angle" radians around the given axis
  5720. * @param axis defines the axis to use
  5721. * @param angle defines the angle (in radians) to use
  5722. * @return the new matrix
  5723. */
  5724. Matrix.RotationAxis = function (axis, angle) {
  5725. var result = Matrix.Zero();
  5726. Matrix.RotationAxisToRef(axis, angle, result);
  5727. return result;
  5728. };
  5729. /**
  5730. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5731. * @param axis defines the axis to use
  5732. * @param angle defines the angle (in radians) to use
  5733. * @param result defines the target matrix
  5734. */
  5735. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5736. var s = Math.sin(-angle);
  5737. var c = Math.cos(-angle);
  5738. var c1 = 1 - c;
  5739. axis.normalize();
  5740. result.m[0] = (axis.x * axis.x) * c1 + c;
  5741. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5742. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5743. result.m[3] = 0.0;
  5744. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5745. result.m[5] = (axis.y * axis.y) * c1 + c;
  5746. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5747. result.m[7] = 0.0;
  5748. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5749. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5750. result.m[10] = (axis.z * axis.z) * c1 + c;
  5751. result.m[11] = 0.0;
  5752. result.m[15] = 1.0;
  5753. result._markAsUpdated();
  5754. };
  5755. /**
  5756. * Creates a rotation matrix
  5757. * @param yaw defines the yaw angle in radians (Y axis)
  5758. * @param pitch defines the pitch angle in radians (X axis)
  5759. * @param roll defines the roll angle in radians (X axis)
  5760. * @returns the new rotation matrix
  5761. */
  5762. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5763. var result = new Matrix();
  5764. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5765. return result;
  5766. };
  5767. /**
  5768. * Creates a rotation matrix and stores it in a given matrix
  5769. * @param yaw defines the yaw angle in radians (Y axis)
  5770. * @param pitch defines the pitch angle in radians (X axis)
  5771. * @param roll defines the roll angle in radians (X axis)
  5772. * @param result defines the target matrix
  5773. */
  5774. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5775. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5776. this._tempQuaternion.toRotationMatrix(result);
  5777. };
  5778. /**
  5779. * Creates a scaling matrix
  5780. * @param x defines the scale factor on X axis
  5781. * @param y defines the scale factor on Y axis
  5782. * @param z defines the scale factor on Z axis
  5783. * @returns the new matrix
  5784. */
  5785. Matrix.Scaling = function (x, y, z) {
  5786. var result = Matrix.Zero();
  5787. Matrix.ScalingToRef(x, y, z, result);
  5788. return result;
  5789. };
  5790. /**
  5791. * Creates a scaling matrix and stores it in a given matrix
  5792. * @param x defines the scale factor on X axis
  5793. * @param y defines the scale factor on Y axis
  5794. * @param z defines the scale factor on Z axis
  5795. * @param result defines the target matrix
  5796. */
  5797. Matrix.ScalingToRef = function (x, y, z, result) {
  5798. result.m[0] = x;
  5799. result.m[1] = 0.0;
  5800. result.m[2] = 0.0;
  5801. result.m[3] = 0.0;
  5802. result.m[4] = 0.0;
  5803. result.m[5] = y;
  5804. result.m[6] = 0.0;
  5805. result.m[7] = 0.0;
  5806. result.m[8] = 0.0;
  5807. result.m[9] = 0.0;
  5808. result.m[10] = z;
  5809. result.m[11] = 0.0;
  5810. result.m[12] = 0.0;
  5811. result.m[13] = 0.0;
  5812. result.m[14] = 0.0;
  5813. result.m[15] = 1.0;
  5814. result._markAsUpdated();
  5815. };
  5816. /**
  5817. * Creates a translation matrix
  5818. * @param x defines the translation on X axis
  5819. * @param y defines the translation on Y axis
  5820. * @param z defines the translationon Z axis
  5821. * @returns the new matrix
  5822. */
  5823. Matrix.Translation = function (x, y, z) {
  5824. var result = Matrix.Identity();
  5825. Matrix.TranslationToRef(x, y, z, result);
  5826. return result;
  5827. };
  5828. /**
  5829. * Creates a translation matrix and stores it in a given matrix
  5830. * @param x defines the translation on X axis
  5831. * @param y defines the translation on Y axis
  5832. * @param z defines the translationon Z axis
  5833. * @param result defines the target matrix
  5834. */
  5835. Matrix.TranslationToRef = function (x, y, z, result) {
  5836. 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);
  5837. };
  5838. /**
  5839. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5840. * @param startValue defines the start value
  5841. * @param endValue defines the end value
  5842. * @param gradient defines the gradient factor
  5843. * @returns the new matrix
  5844. */
  5845. Matrix.Lerp = function (startValue, endValue, gradient) {
  5846. var result = Matrix.Zero();
  5847. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5848. return result;
  5849. };
  5850. /**
  5851. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5852. * @param startValue defines the start value
  5853. * @param endValue defines the end value
  5854. * @param gradient defines the gradient factor
  5855. * @param result defines the Matrix object where to store data
  5856. */
  5857. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5858. for (var index = 0; index < 16; index++) {
  5859. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5860. }
  5861. result._markAsUpdated();
  5862. };
  5863. /**
  5864. * Builds a new matrix whose values are computed by:
  5865. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5866. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5867. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5868. * @param startValue defines the first matrix
  5869. * @param endValue defines the second matrix
  5870. * @param gradient defines the gradient between the two matrices
  5871. * @returns the new matrix
  5872. */
  5873. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5874. var result = Matrix.Zero();
  5875. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5876. return result;
  5877. };
  5878. /**
  5879. * Update a matrix to values which are computed by:
  5880. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5881. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5882. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5883. * @param startValue defines the first matrix
  5884. * @param endValue defines the second matrix
  5885. * @param gradient defines the gradient between the two matrices
  5886. * @param result defines the target matrix
  5887. */
  5888. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5889. var startScale = MathTmp.Vector3[0];
  5890. var startRotation = MathTmp.Quaternion[0];
  5891. var startTranslation = MathTmp.Vector3[1];
  5892. startValue.decompose(startScale, startRotation, startTranslation);
  5893. var endScale = MathTmp.Vector3[2];
  5894. var endRotation = MathTmp.Quaternion[1];
  5895. var endTranslation = MathTmp.Vector3[3];
  5896. endValue.decompose(endScale, endRotation, endTranslation);
  5897. var resultScale = MathTmp.Vector3[4];
  5898. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  5899. var resultRotation = MathTmp.Quaternion[2];
  5900. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  5901. var resultTranslation = MathTmp.Vector3[5];
  5902. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  5903. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  5904. };
  5905. /**
  5906. * 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"
  5907. * This function works in left handed mode
  5908. * @param eye defines the final position of the entity
  5909. * @param target defines where the entity should look at
  5910. * @param up defines the up vector for the entity
  5911. * @returns the new matrix
  5912. */
  5913. Matrix.LookAtLH = function (eye, target, up) {
  5914. var result = Matrix.Zero();
  5915. Matrix.LookAtLHToRef(eye, target, up, result);
  5916. return result;
  5917. };
  5918. /**
  5919. * 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".
  5920. * This function works in left handed mode
  5921. * @param eye defines the final position of the entity
  5922. * @param target defines where the entity should look at
  5923. * @param up defines the up vector for the entity
  5924. * @param result defines the target matrix
  5925. */
  5926. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5927. // Z axis
  5928. target.subtractToRef(eye, this._zAxis);
  5929. this._zAxis.normalize();
  5930. // X axis
  5931. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5932. if (this._xAxis.lengthSquared() === 0) {
  5933. this._xAxis.x = 1.0;
  5934. }
  5935. else {
  5936. this._xAxis.normalize();
  5937. }
  5938. // Y axis
  5939. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5940. this._yAxis.normalize();
  5941. // Eye angles
  5942. var ex = -Vector3.Dot(this._xAxis, eye);
  5943. var ey = -Vector3.Dot(this._yAxis, eye);
  5944. var ez = -Vector3.Dot(this._zAxis, eye);
  5945. 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);
  5946. };
  5947. /**
  5948. * 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"
  5949. * This function works in right handed mode
  5950. * @param eye defines the final position of the entity
  5951. * @param target defines where the entity should look at
  5952. * @param up defines the up vector for the entity
  5953. * @returns the new matrix
  5954. */
  5955. Matrix.LookAtRH = function (eye, target, up) {
  5956. var result = Matrix.Zero();
  5957. Matrix.LookAtRHToRef(eye, target, up, result);
  5958. return result;
  5959. };
  5960. /**
  5961. * 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".
  5962. * This function works in right handed mode
  5963. * @param eye defines the final position of the entity
  5964. * @param target defines where the entity should look at
  5965. * @param up defines the up vector for the entity
  5966. * @param result defines the target matrix
  5967. */
  5968. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5969. // Z axis
  5970. eye.subtractToRef(target, this._zAxis);
  5971. this._zAxis.normalize();
  5972. // X axis
  5973. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5974. if (this._xAxis.lengthSquared() === 0) {
  5975. this._xAxis.x = 1.0;
  5976. }
  5977. else {
  5978. this._xAxis.normalize();
  5979. }
  5980. // Y axis
  5981. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5982. this._yAxis.normalize();
  5983. // Eye angles
  5984. var ex = -Vector3.Dot(this._xAxis, eye);
  5985. var ey = -Vector3.Dot(this._yAxis, eye);
  5986. var ez = -Vector3.Dot(this._zAxis, eye);
  5987. 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);
  5988. };
  5989. /**
  5990. * Create a left-handed orthographic projection matrix
  5991. * @param width defines the viewport width
  5992. * @param height defines the viewport height
  5993. * @param znear defines the near clip plane
  5994. * @param zfar defines the far clip plane
  5995. * @returns a new matrix as a left-handed orthographic projection matrix
  5996. */
  5997. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5998. var matrix = Matrix.Zero();
  5999. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6000. return matrix;
  6001. };
  6002. /**
  6003. * Store a left-handed orthographic projection to a given matrix
  6004. * @param width defines the viewport width
  6005. * @param height defines the viewport height
  6006. * @param znear defines the near clip plane
  6007. * @param zfar defines the far clip plane
  6008. * @param result defines the target matrix
  6009. */
  6010. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6011. var n = znear;
  6012. var f = zfar;
  6013. var a = 2.0 / width;
  6014. var b = 2.0 / height;
  6015. var c = 2.0 / (f - n);
  6016. var d = -(f + n) / (f - n);
  6017. 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);
  6018. };
  6019. /**
  6020. * Create a left-handed orthographic projection matrix
  6021. * @param left defines the viewport left coordinate
  6022. * @param right defines the viewport right coordinate
  6023. * @param bottom defines the viewport bottom coordinate
  6024. * @param top defines the viewport top coordinate
  6025. * @param znear defines the near clip plane
  6026. * @param zfar defines the far clip plane
  6027. * @returns a new matrix as a left-handed orthographic projection matrix
  6028. */
  6029. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6030. var matrix = Matrix.Zero();
  6031. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6032. return matrix;
  6033. };
  6034. /**
  6035. * Stores a left-handed orthographic projection into a given matrix
  6036. * @param left defines the viewport left coordinate
  6037. * @param right defines the viewport right coordinate
  6038. * @param bottom defines the viewport bottom coordinate
  6039. * @param top defines the viewport top coordinate
  6040. * @param znear defines the near clip plane
  6041. * @param zfar defines the far clip plane
  6042. * @param result defines the target matrix
  6043. */
  6044. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6045. var n = znear;
  6046. var f = zfar;
  6047. var a = 2.0 / (right - left);
  6048. var b = 2.0 / (top - bottom);
  6049. var c = 2.0 / (f - n);
  6050. var d = -(f + n) / (f - n);
  6051. var i0 = (left + right) / (left - right);
  6052. var i1 = (top + bottom) / (bottom - top);
  6053. 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);
  6054. };
  6055. /**
  6056. * Creates a right-handed orthographic projection matrix
  6057. * @param left defines the viewport left coordinate
  6058. * @param right defines the viewport right coordinate
  6059. * @param bottom defines the viewport bottom coordinate
  6060. * @param top defines the viewport top coordinate
  6061. * @param znear defines the near clip plane
  6062. * @param zfar defines the far clip plane
  6063. * @returns a new matrix as a right-handed orthographic projection matrix
  6064. */
  6065. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6066. var matrix = Matrix.Zero();
  6067. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6068. return matrix;
  6069. };
  6070. /**
  6071. * Stores a right-handed orthographic projection into a given matrix
  6072. * @param left defines the viewport left coordinate
  6073. * @param right defines the viewport right coordinate
  6074. * @param bottom defines the viewport bottom coordinate
  6075. * @param top defines the viewport top coordinate
  6076. * @param znear defines the near clip plane
  6077. * @param zfar defines the far clip plane
  6078. * @param result defines the target matrix
  6079. */
  6080. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6081. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6082. result.m[10] *= -1.0;
  6083. };
  6084. /**
  6085. * Creates a left-handed perspective projection matrix
  6086. * @param width defines the viewport width
  6087. * @param height defines the viewport height
  6088. * @param znear defines the near clip plane
  6089. * @param zfar defines the far clip plane
  6090. * @returns a new matrix as a left-handed perspective projection matrix
  6091. */
  6092. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6093. var matrix = Matrix.Zero();
  6094. var n = znear;
  6095. var f = zfar;
  6096. var a = 2.0 * n / width;
  6097. var b = 2.0 * n / height;
  6098. var c = (f + n) / (f - n);
  6099. var d = -2.0 * f * n / (f - n);
  6100. 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);
  6101. return matrix;
  6102. };
  6103. /**
  6104. * Creates a left-handed perspective projection matrix
  6105. * @param fov defines the horizontal field of view
  6106. * @param aspect defines the aspect ratio
  6107. * @param znear defines the near clip plane
  6108. * @param zfar defines the far clip plane
  6109. * @returns a new matrix as a left-handed perspective projection matrix
  6110. */
  6111. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6112. var matrix = Matrix.Zero();
  6113. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6114. return matrix;
  6115. };
  6116. /**
  6117. * Stores a left-handed perspective projection into a given matrix
  6118. * @param fov defines the horizontal field of view
  6119. * @param aspect defines the aspect ratio
  6120. * @param znear defines the near clip plane
  6121. * @param zfar defines the far clip plane
  6122. * @param result defines the target matrix
  6123. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6124. */
  6125. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6126. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6127. var n = znear;
  6128. var f = zfar;
  6129. var t = 1.0 / (Math.tan(fov * 0.5));
  6130. var a = isVerticalFovFixed ? (t / aspect) : t;
  6131. var b = isVerticalFovFixed ? t : (t * aspect);
  6132. var c = (f + n) / (f - n);
  6133. var d = -2.0 * f * n / (f - n);
  6134. 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);
  6135. };
  6136. /**
  6137. * Creates a right-handed perspective projection matrix
  6138. * @param fov defines the horizontal field of view
  6139. * @param aspect defines the aspect ratio
  6140. * @param znear defines the near clip plane
  6141. * @param zfar defines the far clip plane
  6142. * @returns a new matrix as a right-handed perspective projection matrix
  6143. */
  6144. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6145. var matrix = Matrix.Zero();
  6146. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6147. return matrix;
  6148. };
  6149. /**
  6150. * Stores a right-handed perspective projection into a given matrix
  6151. * @param fov defines the horizontal field of view
  6152. * @param aspect defines the aspect ratio
  6153. * @param znear defines the near clip plane
  6154. * @param zfar defines the far clip plane
  6155. * @param result defines the target matrix
  6156. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6157. */
  6158. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6159. //alternatively this could be expressed as:
  6160. // m = PerspectiveFovLHToRef
  6161. // m[10] *= -1.0;
  6162. // m[11] *= -1.0;
  6163. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6164. var n = znear;
  6165. var f = zfar;
  6166. var t = 1.0 / (Math.tan(fov * 0.5));
  6167. var a = isVerticalFovFixed ? (t / aspect) : t;
  6168. var b = isVerticalFovFixed ? t : (t * aspect);
  6169. var c = -(f + n) / (f - n);
  6170. var d = -2 * f * n / (f - n);
  6171. 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);
  6172. };
  6173. /**
  6174. * Stores a perspective projection for WebVR info a given matrix
  6175. * @param fov defines the field of view
  6176. * @param znear defines the near clip plane
  6177. * @param zfar defines the far clip plane
  6178. * @param result defines the target matrix
  6179. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6180. */
  6181. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6182. if (rightHanded === void 0) { rightHanded = false; }
  6183. var rightHandedFactor = rightHanded ? -1 : 1;
  6184. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6185. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6186. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6187. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6188. var xScale = 2.0 / (leftTan + rightTan);
  6189. var yScale = 2.0 / (upTan + downTan);
  6190. result.m[0] = xScale;
  6191. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6192. result.m[5] = yScale;
  6193. result.m[6] = result.m[7] = 0.0;
  6194. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6195. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6196. result.m[10] = -zfar / (znear - zfar);
  6197. result.m[11] = 1.0 * rightHandedFactor;
  6198. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6199. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6200. result._markAsUpdated();
  6201. };
  6202. /**
  6203. * Computes a complete transformation matrix
  6204. * @param viewport defines the viewport to use
  6205. * @param world defines the world matrix
  6206. * @param view defines the view matrix
  6207. * @param projection defines the projection matrix
  6208. * @param zmin defines the near clip plane
  6209. * @param zmax defines the far clip plane
  6210. * @returns the transformation matrix
  6211. */
  6212. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6213. var cw = viewport.width;
  6214. var ch = viewport.height;
  6215. var cx = viewport.x;
  6216. var cy = viewport.y;
  6217. 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);
  6218. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6219. };
  6220. /**
  6221. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6222. * @param matrix defines the matrix to use
  6223. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6224. */
  6225. Matrix.GetAsMatrix2x2 = function (matrix) {
  6226. return new Float32Array([
  6227. matrix.m[0], matrix.m[1],
  6228. matrix.m[4], matrix.m[5]
  6229. ]);
  6230. };
  6231. /**
  6232. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6233. * @param matrix defines the matrix to use
  6234. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6235. */
  6236. Matrix.GetAsMatrix3x3 = function (matrix) {
  6237. return new Float32Array([
  6238. matrix.m[0], matrix.m[1], matrix.m[2],
  6239. matrix.m[4], matrix.m[5], matrix.m[6],
  6240. matrix.m[8], matrix.m[9], matrix.m[10]
  6241. ]);
  6242. };
  6243. /**
  6244. * Compute the transpose of a given matrix
  6245. * @param matrix defines the matrix to transpose
  6246. * @returns the new matrix
  6247. */
  6248. Matrix.Transpose = function (matrix) {
  6249. var result = new Matrix();
  6250. Matrix.TransposeToRef(matrix, result);
  6251. return result;
  6252. };
  6253. /**
  6254. * Compute the transpose of a matrix and store it in a target matrix
  6255. * @param matrix defines the matrix to transpose
  6256. * @param result defines the target matrix
  6257. */
  6258. Matrix.TransposeToRef = function (matrix, result) {
  6259. result.m[0] = matrix.m[0];
  6260. result.m[1] = matrix.m[4];
  6261. result.m[2] = matrix.m[8];
  6262. result.m[3] = matrix.m[12];
  6263. result.m[4] = matrix.m[1];
  6264. result.m[5] = matrix.m[5];
  6265. result.m[6] = matrix.m[9];
  6266. result.m[7] = matrix.m[13];
  6267. result.m[8] = matrix.m[2];
  6268. result.m[9] = matrix.m[6];
  6269. result.m[10] = matrix.m[10];
  6270. result.m[11] = matrix.m[14];
  6271. result.m[12] = matrix.m[3];
  6272. result.m[13] = matrix.m[7];
  6273. result.m[14] = matrix.m[11];
  6274. result.m[15] = matrix.m[15];
  6275. };
  6276. /**
  6277. * Computes a reflection matrix from a plane
  6278. * @param plane defines the reflection plane
  6279. * @returns a new matrix
  6280. */
  6281. Matrix.Reflection = function (plane) {
  6282. var matrix = new Matrix();
  6283. Matrix.ReflectionToRef(plane, matrix);
  6284. return matrix;
  6285. };
  6286. /**
  6287. * Computes a reflection matrix from a plane
  6288. * @param plane defines the reflection plane
  6289. * @param result defines the target matrix
  6290. */
  6291. Matrix.ReflectionToRef = function (plane, result) {
  6292. plane.normalize();
  6293. var x = plane.normal.x;
  6294. var y = plane.normal.y;
  6295. var z = plane.normal.z;
  6296. var temp = -2 * x;
  6297. var temp2 = -2 * y;
  6298. var temp3 = -2 * z;
  6299. result.m[0] = (temp * x) + 1;
  6300. result.m[1] = temp2 * x;
  6301. result.m[2] = temp3 * x;
  6302. result.m[3] = 0.0;
  6303. result.m[4] = temp * y;
  6304. result.m[5] = (temp2 * y) + 1;
  6305. result.m[6] = temp3 * y;
  6306. result.m[7] = 0.0;
  6307. result.m[8] = temp * z;
  6308. result.m[9] = temp2 * z;
  6309. result.m[10] = (temp3 * z) + 1;
  6310. result.m[11] = 0.0;
  6311. result.m[12] = temp * plane.d;
  6312. result.m[13] = temp2 * plane.d;
  6313. result.m[14] = temp3 * plane.d;
  6314. result.m[15] = 1.0;
  6315. result._markAsUpdated();
  6316. };
  6317. /**
  6318. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6319. * @param xaxis defines the value of the 1st axis
  6320. * @param yaxis defines the value of the 2nd axis
  6321. * @param zaxis defines the value of the 3rd axis
  6322. * @param result defines the target matrix
  6323. */
  6324. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6325. result.m[0] = xaxis.x;
  6326. result.m[1] = xaxis.y;
  6327. result.m[2] = xaxis.z;
  6328. result.m[3] = 0.0;
  6329. result.m[4] = yaxis.x;
  6330. result.m[5] = yaxis.y;
  6331. result.m[6] = yaxis.z;
  6332. result.m[7] = 0.0;
  6333. result.m[8] = zaxis.x;
  6334. result.m[9] = zaxis.y;
  6335. result.m[10] = zaxis.z;
  6336. result.m[11] = 0.0;
  6337. result.m[12] = 0.0;
  6338. result.m[13] = 0.0;
  6339. result.m[14] = 0.0;
  6340. result.m[15] = 1.0;
  6341. result._markAsUpdated();
  6342. };
  6343. /**
  6344. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6345. * @param quat defines the quaternion to use
  6346. * @param result defines the target matrix
  6347. */
  6348. Matrix.FromQuaternionToRef = function (quat, result) {
  6349. var xx = quat.x * quat.x;
  6350. var yy = quat.y * quat.y;
  6351. var zz = quat.z * quat.z;
  6352. var xy = quat.x * quat.y;
  6353. var zw = quat.z * quat.w;
  6354. var zx = quat.z * quat.x;
  6355. var yw = quat.y * quat.w;
  6356. var yz = quat.y * quat.z;
  6357. var xw = quat.x * quat.w;
  6358. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6359. result.m[1] = 2.0 * (xy + zw);
  6360. result.m[2] = 2.0 * (zx - yw);
  6361. result.m[3] = 0.0;
  6362. result.m[4] = 2.0 * (xy - zw);
  6363. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6364. result.m[6] = 2.0 * (yz + xw);
  6365. result.m[7] = 0.0;
  6366. result.m[8] = 2.0 * (zx + yw);
  6367. result.m[9] = 2.0 * (yz - xw);
  6368. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6369. result.m[11] = 0.0;
  6370. result.m[12] = 0.0;
  6371. result.m[13] = 0.0;
  6372. result.m[14] = 0.0;
  6373. result.m[15] = 1.0;
  6374. result._markAsUpdated();
  6375. };
  6376. Matrix._tempQuaternion = new Quaternion();
  6377. Matrix._xAxis = Vector3.Zero();
  6378. Matrix._yAxis = Vector3.Zero();
  6379. Matrix._zAxis = Vector3.Zero();
  6380. Matrix._updateFlagSeed = 0;
  6381. Matrix._identityReadOnly = Matrix.Identity();
  6382. return Matrix;
  6383. }());
  6384. BABYLON.Matrix = Matrix;
  6385. var Plane = /** @class */ (function () {
  6386. /**
  6387. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6388. */
  6389. function Plane(a, b, c, d) {
  6390. this.normal = new Vector3(a, b, c);
  6391. this.d = d;
  6392. }
  6393. /**
  6394. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6395. */
  6396. Plane.prototype.asArray = function () {
  6397. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6398. };
  6399. // Methods
  6400. /**
  6401. * Returns a new plane copied from the current Plane.
  6402. */
  6403. Plane.prototype.clone = function () {
  6404. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6405. };
  6406. /**
  6407. * Returns the string "Plane".
  6408. */
  6409. Plane.prototype.getClassName = function () {
  6410. return "Plane";
  6411. };
  6412. /**
  6413. * Returns the Plane hash code.
  6414. */
  6415. Plane.prototype.getHashCode = function () {
  6416. var hash = this.normal.getHashCode();
  6417. hash = (hash * 397) ^ (this.d || 0);
  6418. return hash;
  6419. };
  6420. /**
  6421. * Normalize the current Plane in place.
  6422. * Returns the updated Plane.
  6423. */
  6424. Plane.prototype.normalize = function () {
  6425. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6426. var magnitude = 0.0;
  6427. if (norm !== 0) {
  6428. magnitude = 1.0 / norm;
  6429. }
  6430. this.normal.x *= magnitude;
  6431. this.normal.y *= magnitude;
  6432. this.normal.z *= magnitude;
  6433. this.d *= magnitude;
  6434. return this;
  6435. };
  6436. /**
  6437. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6438. */
  6439. Plane.prototype.transform = function (transformation) {
  6440. var transposedMatrix = Matrix.Transpose(transformation);
  6441. var x = this.normal.x;
  6442. var y = this.normal.y;
  6443. var z = this.normal.z;
  6444. var d = this.d;
  6445. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6446. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6447. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6448. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6449. return new Plane(normalX, normalY, normalZ, finalD);
  6450. };
  6451. /**
  6452. * Returns the dot product (float) of the point coordinates and the plane normal.
  6453. */
  6454. Plane.prototype.dotCoordinate = function (point) {
  6455. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6456. };
  6457. /**
  6458. * Updates the current Plane from the plane defined by the three given points.
  6459. * Returns the updated Plane.
  6460. */
  6461. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6462. var x1 = point2.x - point1.x;
  6463. var y1 = point2.y - point1.y;
  6464. var z1 = point2.z - point1.z;
  6465. var x2 = point3.x - point1.x;
  6466. var y2 = point3.y - point1.y;
  6467. var z2 = point3.z - point1.z;
  6468. var yz = (y1 * z2) - (z1 * y2);
  6469. var xz = (z1 * x2) - (x1 * z2);
  6470. var xy = (x1 * y2) - (y1 * x2);
  6471. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6472. var invPyth;
  6473. if (pyth !== 0) {
  6474. invPyth = 1.0 / pyth;
  6475. }
  6476. else {
  6477. invPyth = 0.0;
  6478. }
  6479. this.normal.x = yz * invPyth;
  6480. this.normal.y = xz * invPyth;
  6481. this.normal.z = xy * invPyth;
  6482. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6483. return this;
  6484. };
  6485. /**
  6486. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6487. */
  6488. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6489. var dot = Vector3.Dot(this.normal, direction);
  6490. return (dot <= epsilon);
  6491. };
  6492. /**
  6493. * Returns the signed distance (float) from the given point to the Plane.
  6494. */
  6495. Plane.prototype.signedDistanceTo = function (point) {
  6496. return Vector3.Dot(point, this.normal) + this.d;
  6497. };
  6498. // Statics
  6499. /**
  6500. * Returns a new Plane from the given array.
  6501. */
  6502. Plane.FromArray = function (array) {
  6503. return new Plane(array[0], array[1], array[2], array[3]);
  6504. };
  6505. /**
  6506. * Returns a new Plane defined by the three given points.
  6507. */
  6508. Plane.FromPoints = function (point1, point2, point3) {
  6509. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6510. result.copyFromPoints(point1, point2, point3);
  6511. return result;
  6512. };
  6513. /**
  6514. * Returns a new Plane the normal vector to this plane at the given origin point.
  6515. * Note : the vector "normal" is updated because normalized.
  6516. */
  6517. Plane.FromPositionAndNormal = function (origin, normal) {
  6518. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6519. normal.normalize();
  6520. result.normal = normal;
  6521. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6522. return result;
  6523. };
  6524. /**
  6525. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6526. */
  6527. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6528. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6529. return Vector3.Dot(point, normal) + d;
  6530. };
  6531. return Plane;
  6532. }());
  6533. BABYLON.Plane = Plane;
  6534. var Viewport = /** @class */ (function () {
  6535. /**
  6536. * Creates a Viewport object located at (x, y) and sized (width, height).
  6537. */
  6538. function Viewport(x, y, width, height) {
  6539. this.x = x;
  6540. this.y = y;
  6541. this.width = width;
  6542. this.height = height;
  6543. }
  6544. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6545. if (renderWidthOrEngine.getRenderWidth) {
  6546. var engine = renderWidthOrEngine;
  6547. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6548. }
  6549. var renderWidth = renderWidthOrEngine;
  6550. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6551. };
  6552. /**
  6553. * Returns a new Viewport copied from the current one.
  6554. */
  6555. Viewport.prototype.clone = function () {
  6556. return new Viewport(this.x, this.y, this.width, this.height);
  6557. };
  6558. return Viewport;
  6559. }());
  6560. BABYLON.Viewport = Viewport;
  6561. var Frustum = /** @class */ (function () {
  6562. function Frustum() {
  6563. }
  6564. /**
  6565. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6566. */
  6567. Frustum.GetPlanes = function (transform) {
  6568. var frustumPlanes = [];
  6569. for (var index = 0; index < 6; index++) {
  6570. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6571. }
  6572. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6573. return frustumPlanes;
  6574. };
  6575. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6576. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6577. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6578. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6579. frustumPlane.d = transform.m[15] + transform.m[14];
  6580. frustumPlane.normalize();
  6581. };
  6582. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6583. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6584. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6585. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6586. frustumPlane.d = transform.m[15] - transform.m[14];
  6587. frustumPlane.normalize();
  6588. };
  6589. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6590. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6591. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6592. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6593. frustumPlane.d = transform.m[15] + transform.m[12];
  6594. frustumPlane.normalize();
  6595. };
  6596. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6597. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6598. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6599. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6600. frustumPlane.d = transform.m[15] - transform.m[12];
  6601. frustumPlane.normalize();
  6602. };
  6603. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6604. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6605. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6606. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6607. frustumPlane.d = transform.m[15] - transform.m[13];
  6608. frustumPlane.normalize();
  6609. };
  6610. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6611. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6612. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6613. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6614. frustumPlane.d = transform.m[15] + transform.m[13];
  6615. frustumPlane.normalize();
  6616. };
  6617. /**
  6618. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6619. */
  6620. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6621. // Near
  6622. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6623. // Far
  6624. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6625. // Left
  6626. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6627. // Right
  6628. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6629. // Top
  6630. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6631. // Bottom
  6632. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6633. };
  6634. return Frustum;
  6635. }());
  6636. BABYLON.Frustum = Frustum;
  6637. /** Defines supported spaces */
  6638. var Space;
  6639. (function (Space) {
  6640. /** Local (object) space */
  6641. Space[Space["LOCAL"] = 0] = "LOCAL";
  6642. /** World space */
  6643. Space[Space["WORLD"] = 1] = "WORLD";
  6644. /** Bone space */
  6645. Space[Space["BONE"] = 2] = "BONE";
  6646. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6647. /** Defines the 3 main axes */
  6648. var Axis = /** @class */ (function () {
  6649. function Axis() {
  6650. }
  6651. /** X axis */
  6652. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6653. /** Y axis */
  6654. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6655. /** Z axis */
  6656. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6657. return Axis;
  6658. }());
  6659. BABYLON.Axis = Axis;
  6660. ;
  6661. var BezierCurve = /** @class */ (function () {
  6662. function BezierCurve() {
  6663. }
  6664. /**
  6665. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6666. */
  6667. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6668. // Extract X (which is equal to time here)
  6669. var f0 = 1 - 3 * x2 + 3 * x1;
  6670. var f1 = 3 * x2 - 6 * x1;
  6671. var f2 = 3 * x1;
  6672. var refinedT = t;
  6673. for (var i = 0; i < 5; i++) {
  6674. var refinedT2 = refinedT * refinedT;
  6675. var refinedT3 = refinedT2 * refinedT;
  6676. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6677. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6678. refinedT -= (x - t) * slope;
  6679. refinedT = Math.min(1, Math.max(0, refinedT));
  6680. }
  6681. // Resolve cubic bezier for the given x
  6682. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6683. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6684. Math.pow(refinedT, 3);
  6685. };
  6686. return BezierCurve;
  6687. }());
  6688. BABYLON.BezierCurve = BezierCurve;
  6689. /**
  6690. * Defines potential orientation for back face culling
  6691. */
  6692. var Orientation;
  6693. (function (Orientation) {
  6694. /**
  6695. * Clockwise
  6696. */
  6697. Orientation[Orientation["CW"] = 0] = "CW";
  6698. /** Counter clockwise */
  6699. Orientation[Orientation["CCW"] = 1] = "CCW";
  6700. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6701. var Angle = /** @class */ (function () {
  6702. /**
  6703. * Creates an Angle object of "radians" radians (float).
  6704. */
  6705. function Angle(radians) {
  6706. var _this = this;
  6707. /**
  6708. * Returns the Angle value in degrees (float).
  6709. */
  6710. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6711. /**
  6712. * Returns the Angle value in radians (float).
  6713. */
  6714. this.radians = function () { return _this._radians; };
  6715. this._radians = radians;
  6716. if (this._radians < 0.0)
  6717. this._radians += (2.0 * Math.PI);
  6718. }
  6719. /**
  6720. * Returns a new Angle object valued with the angle value in radians between the two given vectors.
  6721. */
  6722. Angle.BetweenTwoPoints = function (a, b) {
  6723. var delta = b.subtract(a);
  6724. var theta = Math.atan2(delta.y, delta.x);
  6725. return new Angle(theta);
  6726. };
  6727. /**
  6728. * Returns a new Angle object from the given float in radians.
  6729. */
  6730. Angle.FromRadians = function (radians) {
  6731. return new Angle(radians);
  6732. };
  6733. /**
  6734. * Returns a new Angle object from the given float in degrees.
  6735. */
  6736. Angle.FromDegrees = function (degrees) {
  6737. return new Angle(degrees * Math.PI / 180.0);
  6738. };
  6739. return Angle;
  6740. }());
  6741. BABYLON.Angle = Angle;
  6742. var Arc2 = /** @class */ (function () {
  6743. /**
  6744. * Creates an Arc object from the three given points : start, middle and end.
  6745. */
  6746. function Arc2(startPoint, midPoint, endPoint) {
  6747. this.startPoint = startPoint;
  6748. this.midPoint = midPoint;
  6749. this.endPoint = endPoint;
  6750. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6751. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6752. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6753. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6754. 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);
  6755. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6756. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6757. var a1 = this.startAngle.degrees();
  6758. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6759. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6760. // angles correction
  6761. if (a2 - a1 > +180.0)
  6762. a2 -= 360.0;
  6763. if (a2 - a1 < -180.0)
  6764. a2 += 360.0;
  6765. if (a3 - a2 > +180.0)
  6766. a3 -= 360.0;
  6767. if (a3 - a2 < -180.0)
  6768. a3 += 360.0;
  6769. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6770. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6771. }
  6772. return Arc2;
  6773. }());
  6774. BABYLON.Arc2 = Arc2;
  6775. var Path2 = /** @class */ (function () {
  6776. /**
  6777. * Creates a Path2 object from the starting 2D coordinates x and y.
  6778. */
  6779. function Path2(x, y) {
  6780. this._points = new Array();
  6781. this._length = 0.0;
  6782. this.closed = false;
  6783. this._points.push(new Vector2(x, y));
  6784. }
  6785. /**
  6786. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6787. * Returns the updated Path2.
  6788. */
  6789. Path2.prototype.addLineTo = function (x, y) {
  6790. if (this.closed) {
  6791. return this;
  6792. }
  6793. var newPoint = new Vector2(x, y);
  6794. var previousPoint = this._points[this._points.length - 1];
  6795. this._points.push(newPoint);
  6796. this._length += newPoint.subtract(previousPoint).length();
  6797. return this;
  6798. };
  6799. /**
  6800. * 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.
  6801. * Returns the updated Path2.
  6802. */
  6803. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6804. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6805. if (this.closed) {
  6806. return this;
  6807. }
  6808. var startPoint = this._points[this._points.length - 1];
  6809. var midPoint = new Vector2(midX, midY);
  6810. var endPoint = new Vector2(endX, endY);
  6811. var arc = new Arc2(startPoint, midPoint, endPoint);
  6812. var increment = arc.angle.radians() / numberOfSegments;
  6813. if (arc.orientation === Orientation.CW)
  6814. increment *= -1;
  6815. var currentAngle = arc.startAngle.radians() + increment;
  6816. for (var i = 0; i < numberOfSegments; i++) {
  6817. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6818. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6819. this.addLineTo(x, y);
  6820. currentAngle += increment;
  6821. }
  6822. return this;
  6823. };
  6824. /**
  6825. * Closes the Path2.
  6826. * Returns the Path2.
  6827. */
  6828. Path2.prototype.close = function () {
  6829. this.closed = true;
  6830. return this;
  6831. };
  6832. /**
  6833. * Returns the Path2 total length (float).
  6834. */
  6835. Path2.prototype.length = function () {
  6836. var result = this._length;
  6837. if (!this.closed) {
  6838. var lastPoint = this._points[this._points.length - 1];
  6839. var firstPoint = this._points[0];
  6840. result += (firstPoint.subtract(lastPoint).length());
  6841. }
  6842. return result;
  6843. };
  6844. /**
  6845. * Returns the Path2 internal array of points.
  6846. */
  6847. Path2.prototype.getPoints = function () {
  6848. return this._points;
  6849. };
  6850. /**
  6851. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6852. */
  6853. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6854. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6855. return Vector2.Zero();
  6856. }
  6857. var lengthPosition = normalizedLengthPosition * this.length();
  6858. var previousOffset = 0;
  6859. for (var i = 0; i < this._points.length; i++) {
  6860. var j = (i + 1) % this._points.length;
  6861. var a = this._points[i];
  6862. var b = this._points[j];
  6863. var bToA = b.subtract(a);
  6864. var nextOffset = (bToA.length() + previousOffset);
  6865. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6866. var dir = bToA.normalize();
  6867. var localOffset = lengthPosition - previousOffset;
  6868. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6869. }
  6870. previousOffset = nextOffset;
  6871. }
  6872. return Vector2.Zero();
  6873. };
  6874. /**
  6875. * Returns a new Path2 starting at the coordinates (x, y).
  6876. */
  6877. Path2.StartingAt = function (x, y) {
  6878. return new Path2(x, y);
  6879. };
  6880. return Path2;
  6881. }());
  6882. BABYLON.Path2 = Path2;
  6883. var Path3D = /** @class */ (function () {
  6884. /**
  6885. * new Path3D(path, normal, raw)
  6886. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6887. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6888. * path : an array of Vector3, the curve axis of the Path3D
  6889. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6890. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6891. */
  6892. function Path3D(path, firstNormal, raw) {
  6893. if (firstNormal === void 0) { firstNormal = null; }
  6894. this.path = path;
  6895. this._curve = new Array();
  6896. this._distances = new Array();
  6897. this._tangents = new Array();
  6898. this._normals = new Array();
  6899. this._binormals = new Array();
  6900. for (var p = 0; p < path.length; p++) {
  6901. this._curve[p] = path[p].clone(); // hard copy
  6902. }
  6903. this._raw = raw || false;
  6904. this._compute(firstNormal);
  6905. }
  6906. /**
  6907. * Returns the Path3D array of successive Vector3 designing its curve.
  6908. */
  6909. Path3D.prototype.getCurve = function () {
  6910. return this._curve;
  6911. };
  6912. /**
  6913. * Returns an array populated with tangent vectors on each Path3D curve point.
  6914. */
  6915. Path3D.prototype.getTangents = function () {
  6916. return this._tangents;
  6917. };
  6918. /**
  6919. * Returns an array populated with normal vectors on each Path3D curve point.
  6920. */
  6921. Path3D.prototype.getNormals = function () {
  6922. return this._normals;
  6923. };
  6924. /**
  6925. * Returns an array populated with binormal vectors on each Path3D curve point.
  6926. */
  6927. Path3D.prototype.getBinormals = function () {
  6928. return this._binormals;
  6929. };
  6930. /**
  6931. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6932. */
  6933. Path3D.prototype.getDistances = function () {
  6934. return this._distances;
  6935. };
  6936. /**
  6937. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6938. * Returns the same object updated.
  6939. */
  6940. Path3D.prototype.update = function (path, firstNormal) {
  6941. if (firstNormal === void 0) { firstNormal = null; }
  6942. for (var p = 0; p < path.length; p++) {
  6943. this._curve[p].x = path[p].x;
  6944. this._curve[p].y = path[p].y;
  6945. this._curve[p].z = path[p].z;
  6946. }
  6947. this._compute(firstNormal);
  6948. return this;
  6949. };
  6950. // private function compute() : computes tangents, normals and binormals
  6951. Path3D.prototype._compute = function (firstNormal) {
  6952. var l = this._curve.length;
  6953. // first and last tangents
  6954. this._tangents[0] = this._getFirstNonNullVector(0);
  6955. if (!this._raw) {
  6956. this._tangents[0].normalize();
  6957. }
  6958. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6959. if (!this._raw) {
  6960. this._tangents[l - 1].normalize();
  6961. }
  6962. // normals and binormals at first point : arbitrary vector with _normalVector()
  6963. var tg0 = this._tangents[0];
  6964. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6965. this._normals[0] = pp0;
  6966. if (!this._raw) {
  6967. this._normals[0].normalize();
  6968. }
  6969. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6970. if (!this._raw) {
  6971. this._binormals[0].normalize();
  6972. }
  6973. this._distances[0] = 0.0;
  6974. // normals and binormals : next points
  6975. var prev; // previous vector (segment)
  6976. var cur; // current vector (segment)
  6977. var curTang; // current tangent
  6978. // previous normal
  6979. var prevBinor; // previous binormal
  6980. for (var i = 1; i < l; i++) {
  6981. // tangents
  6982. prev = this._getLastNonNullVector(i);
  6983. if (i < l - 1) {
  6984. cur = this._getFirstNonNullVector(i);
  6985. this._tangents[i] = prev.add(cur);
  6986. this._tangents[i].normalize();
  6987. }
  6988. this._distances[i] = this._distances[i - 1] + prev.length();
  6989. // normals and binormals
  6990. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6991. curTang = this._tangents[i];
  6992. prevBinor = this._binormals[i - 1];
  6993. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6994. if (!this._raw) {
  6995. this._normals[i].normalize();
  6996. }
  6997. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6998. if (!this._raw) {
  6999. this._binormals[i].normalize();
  7000. }
  7001. }
  7002. };
  7003. // private function getFirstNonNullVector(index)
  7004. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7005. Path3D.prototype._getFirstNonNullVector = function (index) {
  7006. var i = 1;
  7007. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7008. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7009. i++;
  7010. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7011. }
  7012. return nNVector;
  7013. };
  7014. // private function getLastNonNullVector(index)
  7015. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7016. Path3D.prototype._getLastNonNullVector = function (index) {
  7017. var i = 1;
  7018. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7019. while (nLVector.length() === 0 && index > i + 1) {
  7020. i++;
  7021. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7022. }
  7023. return nLVector;
  7024. };
  7025. // private function normalVector(v0, vt, va) :
  7026. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7027. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7028. Path3D.prototype._normalVector = function (v0, vt, va) {
  7029. var normal0;
  7030. var tgl = vt.length();
  7031. if (tgl === 0.0) {
  7032. tgl = 1.0;
  7033. }
  7034. if (va === undefined || va === null) {
  7035. var point;
  7036. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7037. point = new Vector3(0.0, -1.0, 0.0);
  7038. }
  7039. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7040. point = new Vector3(1.0, 0.0, 0.0);
  7041. }
  7042. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7043. point = new Vector3(0.0, 0.0, 1.0);
  7044. }
  7045. else {
  7046. point = Vector3.Zero();
  7047. }
  7048. normal0 = Vector3.Cross(vt, point);
  7049. }
  7050. else {
  7051. normal0 = Vector3.Cross(vt, va);
  7052. Vector3.CrossToRef(normal0, vt, normal0);
  7053. }
  7054. normal0.normalize();
  7055. return normal0;
  7056. };
  7057. return Path3D;
  7058. }());
  7059. BABYLON.Path3D = Path3D;
  7060. var Curve3 = /** @class */ (function () {
  7061. /**
  7062. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7063. * A Curve3 is designed from a series of successive Vector3.
  7064. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7065. */
  7066. function Curve3(points) {
  7067. this._length = 0.0;
  7068. this._points = points;
  7069. this._length = this._computeLength(points);
  7070. }
  7071. /**
  7072. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7073. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7074. * @param v1 (Vector3) the control point
  7075. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7076. * @param nbPoints (integer) the wanted number of points in the curve
  7077. */
  7078. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7079. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7080. var bez = new Array();
  7081. var equation = function (t, val0, val1, val2) {
  7082. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7083. return res;
  7084. };
  7085. for (var i = 0; i <= nbPoints; i++) {
  7086. 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)));
  7087. }
  7088. return new Curve3(bez);
  7089. };
  7090. /**
  7091. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7092. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7093. * @param v1 (Vector3) the first control point
  7094. * @param v2 (Vector3) the second control point
  7095. * @param v3 (Vector3) the end point of the Cubic Bezier
  7096. * @param nbPoints (integer) the wanted number of points in the curve
  7097. */
  7098. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7099. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7100. var bez = new Array();
  7101. var equation = function (t, val0, val1, val2, val3) {
  7102. 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;
  7103. return res;
  7104. };
  7105. for (var i = 0; i <= nbPoints; i++) {
  7106. 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)));
  7107. }
  7108. return new Curve3(bez);
  7109. };
  7110. /**
  7111. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7112. * @param p1 (Vector3) the origin point of the Hermite Spline
  7113. * @param t1 (Vector3) the tangent vector at the origin point
  7114. * @param p2 (Vector3) the end point of the Hermite Spline
  7115. * @param t2 (Vector3) the tangent vector at the end point
  7116. * @param nbPoints (integer) the wanted number of points in the curve
  7117. */
  7118. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7119. var hermite = new Array();
  7120. var step = 1.0 / nbPoints;
  7121. for (var i = 0; i <= nbPoints; i++) {
  7122. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7123. }
  7124. return new Curve3(hermite);
  7125. };
  7126. /**
  7127. * Returns a Curve3 object along a CatmullRom Spline curve :
  7128. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7129. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7130. */
  7131. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7132. var totalPoints = new Array();
  7133. totalPoints.push(points[0].clone());
  7134. Array.prototype.push.apply(totalPoints, points);
  7135. totalPoints.push(points[points.length - 1].clone());
  7136. var catmullRom = new Array();
  7137. var step = 1.0 / nbPoints;
  7138. var amount = 0.0;
  7139. for (var i = 0; i < totalPoints.length - 3; i++) {
  7140. amount = 0;
  7141. for (var c = 0; c < nbPoints; c++) {
  7142. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7143. amount += step;
  7144. }
  7145. }
  7146. i--;
  7147. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7148. return new Curve3(catmullRom);
  7149. };
  7150. /**
  7151. * Returns the Curve3 stored array of successive Vector3
  7152. */
  7153. Curve3.prototype.getPoints = function () {
  7154. return this._points;
  7155. };
  7156. /**
  7157. * Returns the computed length (float) of the curve.
  7158. */
  7159. Curve3.prototype.length = function () {
  7160. return this._length;
  7161. };
  7162. /**
  7163. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7164. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7165. * curveA and curveB keep unchanged.
  7166. */
  7167. Curve3.prototype.continue = function (curve) {
  7168. var lastPoint = this._points[this._points.length - 1];
  7169. var continuedPoints = this._points.slice();
  7170. var curvePoints = curve.getPoints();
  7171. for (var i = 1; i < curvePoints.length; i++) {
  7172. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7173. }
  7174. var continuedCurve = new Curve3(continuedPoints);
  7175. return continuedCurve;
  7176. };
  7177. Curve3.prototype._computeLength = function (path) {
  7178. var l = 0;
  7179. for (var i = 1; i < path.length; i++) {
  7180. l += (path[i].subtract(path[i - 1])).length();
  7181. }
  7182. return l;
  7183. };
  7184. return Curve3;
  7185. }());
  7186. BABYLON.Curve3 = Curve3;
  7187. // Vertex formats
  7188. var PositionNormalVertex = /** @class */ (function () {
  7189. function PositionNormalVertex(position, normal) {
  7190. if (position === void 0) { position = Vector3.Zero(); }
  7191. if (normal === void 0) { normal = Vector3.Up(); }
  7192. this.position = position;
  7193. this.normal = normal;
  7194. }
  7195. PositionNormalVertex.prototype.clone = function () {
  7196. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7197. };
  7198. return PositionNormalVertex;
  7199. }());
  7200. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7201. var PositionNormalTextureVertex = /** @class */ (function () {
  7202. function PositionNormalTextureVertex(position, normal, uv) {
  7203. if (position === void 0) { position = Vector3.Zero(); }
  7204. if (normal === void 0) { normal = Vector3.Up(); }
  7205. if (uv === void 0) { uv = Vector2.Zero(); }
  7206. this.position = position;
  7207. this.normal = normal;
  7208. this.uv = uv;
  7209. }
  7210. PositionNormalTextureVertex.prototype.clone = function () {
  7211. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7212. };
  7213. return PositionNormalTextureVertex;
  7214. }());
  7215. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7216. // Temporary pre-allocated objects for engine internal use
  7217. // usage in any internal function :
  7218. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7219. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7220. var Tmp = /** @class */ (function () {
  7221. function Tmp() {
  7222. }
  7223. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7224. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7225. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7226. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7227. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7228. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7229. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7230. Matrix.Zero(), Matrix.Zero(),
  7231. Matrix.Zero(), Matrix.Zero(),
  7232. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7233. return Tmp;
  7234. }());
  7235. BABYLON.Tmp = Tmp;
  7236. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7237. var MathTmp = /** @class */ (function () {
  7238. function MathTmp() {
  7239. }
  7240. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7241. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7242. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7243. return MathTmp;
  7244. }());
  7245. })(BABYLON || (BABYLON = {}));
  7246. //# sourceMappingURL=babylon.math.js.map
  7247. var BABYLON;
  7248. (function (BABYLON) {
  7249. var Scalar = /** @class */ (function () {
  7250. function Scalar() {
  7251. }
  7252. /**
  7253. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7254. */
  7255. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7256. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7257. var num = a - b;
  7258. return -epsilon <= num && num <= epsilon;
  7259. };
  7260. /**
  7261. * Returns a string : the upper case translation of the number i to hexadecimal.
  7262. */
  7263. Scalar.ToHex = function (i) {
  7264. var str = i.toString(16);
  7265. if (i <= 15) {
  7266. return ("0" + str).toUpperCase();
  7267. }
  7268. return str.toUpperCase();
  7269. };
  7270. /**
  7271. * Returns -1 if value is negative and +1 is value is positive.
  7272. * Returns the value itself if it's equal to zero.
  7273. */
  7274. Scalar.Sign = function (value) {
  7275. value = +value; // convert to a number
  7276. if (value === 0 || isNaN(value))
  7277. return value;
  7278. return value > 0 ? 1 : -1;
  7279. };
  7280. /**
  7281. * Returns the value itself if it's between min and max.
  7282. * Returns min if the value is lower than min.
  7283. * Returns max if the value is greater than max.
  7284. */
  7285. Scalar.Clamp = function (value, min, max) {
  7286. if (min === void 0) { min = 0; }
  7287. if (max === void 0) { max = 1; }
  7288. return Math.min(max, Math.max(min, value));
  7289. };
  7290. /**
  7291. * Returns the log2 of value.
  7292. */
  7293. Scalar.Log2 = function (value) {
  7294. return Math.log(value) * Math.LOG2E;
  7295. };
  7296. /**
  7297. * Loops the value, so that it is never larger than length and never smaller than 0.
  7298. *
  7299. * This is similar to the modulo operator but it works with floating point numbers.
  7300. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7301. * With t = 5 and length = 2.5, the result would be 0.0.
  7302. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7303. */
  7304. Scalar.Repeat = function (value, length) {
  7305. return value - Math.floor(value / length) * length;
  7306. };
  7307. /**
  7308. * Normalize the value between 0.0 and 1.0 using min and max values
  7309. */
  7310. Scalar.Normalize = function (value, min, max) {
  7311. return (value - min) / (max - min);
  7312. };
  7313. /**
  7314. * Denormalize the value from 0.0 and 1.0 using min and max values
  7315. */
  7316. Scalar.Denormalize = function (normalized, min, max) {
  7317. return (normalized * (max - min) + min);
  7318. };
  7319. /**
  7320. * Calculates the shortest difference between two given angles given in degrees.
  7321. */
  7322. Scalar.DeltaAngle = function (current, target) {
  7323. var num = Scalar.Repeat(target - current, 360.0);
  7324. if (num > 180.0) {
  7325. num -= 360.0;
  7326. }
  7327. return num;
  7328. };
  7329. /**
  7330. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7331. *
  7332. * The returned value will move back and forth between 0 and length
  7333. */
  7334. Scalar.PingPong = function (tx, length) {
  7335. var t = Scalar.Repeat(tx, length * 2.0);
  7336. return length - Math.abs(t - length);
  7337. };
  7338. /**
  7339. * Interpolates between min and max with smoothing at the limits.
  7340. *
  7341. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7342. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7343. */
  7344. Scalar.SmoothStep = function (from, to, tx) {
  7345. var t = Scalar.Clamp(tx);
  7346. t = -2.0 * t * t * t + 3.0 * t * t;
  7347. return to * t + from * (1.0 - t);
  7348. };
  7349. /**
  7350. * Moves a value current towards target.
  7351. *
  7352. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7353. * Negative values of maxDelta pushes the value away from target.
  7354. */
  7355. Scalar.MoveTowards = function (current, target, maxDelta) {
  7356. var result = 0;
  7357. if (Math.abs(target - current) <= maxDelta) {
  7358. result = target;
  7359. }
  7360. else {
  7361. result = current + Scalar.Sign(target - current) * maxDelta;
  7362. }
  7363. return result;
  7364. };
  7365. /**
  7366. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7367. *
  7368. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7369. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7370. */
  7371. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7372. var num = Scalar.DeltaAngle(current, target);
  7373. var result = 0;
  7374. if (-maxDelta < num && num < maxDelta) {
  7375. result = target;
  7376. }
  7377. else {
  7378. target = current + num;
  7379. result = Scalar.MoveTowards(current, target, maxDelta);
  7380. }
  7381. return result;
  7382. };
  7383. /**
  7384. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7385. */
  7386. Scalar.Lerp = function (start, end, amount) {
  7387. return start + ((end - start) * amount);
  7388. };
  7389. /**
  7390. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7391. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7392. */
  7393. Scalar.LerpAngle = function (start, end, amount) {
  7394. var num = Scalar.Repeat(end - start, 360.0);
  7395. if (num > 180.0) {
  7396. num -= 360.0;
  7397. }
  7398. return start + num * Scalar.Clamp(amount);
  7399. };
  7400. /**
  7401. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7402. */
  7403. Scalar.InverseLerp = function (a, b, value) {
  7404. var result = 0;
  7405. if (a != b) {
  7406. result = Scalar.Clamp((value - a) / (b - a));
  7407. }
  7408. else {
  7409. result = 0.0;
  7410. }
  7411. return result;
  7412. };
  7413. /**
  7414. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7415. */
  7416. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7417. var squared = amount * amount;
  7418. var cubed = amount * squared;
  7419. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7420. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7421. var part3 = (cubed - (2.0 * squared)) + amount;
  7422. var part4 = cubed - squared;
  7423. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7424. };
  7425. /**
  7426. * Returns a random float number between and min and max values
  7427. */
  7428. Scalar.RandomRange = function (min, max) {
  7429. if (min === max)
  7430. return min;
  7431. return ((Math.random() * (max - min)) + min);
  7432. };
  7433. /**
  7434. * This function returns percentage of a number in a given range.
  7435. *
  7436. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7437. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7438. */
  7439. Scalar.RangeToPercent = function (number, min, max) {
  7440. return ((number - min) / (max - min));
  7441. };
  7442. /**
  7443. * This function returns number that corresponds to the percentage in a given range.
  7444. *
  7445. * PercentToRange(0.34,0,100) will return 34.
  7446. */
  7447. Scalar.PercentToRange = function (percent, min, max) {
  7448. return ((max - min) * percent + min);
  7449. };
  7450. /**
  7451. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7452. * @param angle The angle to normalize in radian.
  7453. * @return The converted angle.
  7454. */
  7455. Scalar.NormalizeRadians = function (angle) {
  7456. // More precise but slower version kept for reference.
  7457. // angle = angle % Tools.TwoPi;
  7458. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7459. //if (angle > Math.PI) {
  7460. // angle -= Tools.TwoPi;
  7461. //}
  7462. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7463. return angle;
  7464. };
  7465. /**
  7466. * Two pi constants convenient for computation.
  7467. */
  7468. Scalar.TwoPi = Math.PI * 2;
  7469. return Scalar;
  7470. }());
  7471. BABYLON.Scalar = Scalar;
  7472. })(BABYLON || (BABYLON = {}));
  7473. //# sourceMappingURL=babylon.math.scalar.js.map
  7474. //# sourceMappingURL=babylon.mixins.js.map
  7475. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7476. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7477. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7478. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7479. //# sourceMappingURL=babylon.webgl2.js.map
  7480. var BABYLON;
  7481. (function (BABYLON) {
  7482. var __decoratorInitialStore = {};
  7483. var __mergedStore = {};
  7484. var _copySource = function (creationFunction, source, instanciate) {
  7485. var destination = creationFunction();
  7486. // Tags
  7487. if (BABYLON.Tags) {
  7488. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7489. }
  7490. var classStore = getMergedStore(destination);
  7491. // Properties
  7492. for (var property in classStore) {
  7493. var propertyDescriptor = classStore[property];
  7494. var sourceProperty = source[property];
  7495. var propertyType = propertyDescriptor.type;
  7496. if (sourceProperty !== undefined && sourceProperty !== null) {
  7497. switch (propertyType) {
  7498. case 0: // Value
  7499. case 6: // Mesh reference
  7500. case 11: // Camera reference
  7501. destination[property] = sourceProperty;
  7502. break;
  7503. case 1: // Texture
  7504. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7505. break;
  7506. case 2: // Color3
  7507. case 3: // FresnelParameters
  7508. case 4: // Vector2
  7509. case 5: // Vector3
  7510. case 7: // Color Curves
  7511. case 10: // Quaternion
  7512. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7513. break;
  7514. }
  7515. }
  7516. }
  7517. return destination;
  7518. };
  7519. function getDirectStore(target) {
  7520. var classKey = target.getClassName();
  7521. if (!__decoratorInitialStore[classKey]) {
  7522. __decoratorInitialStore[classKey] = {};
  7523. }
  7524. return __decoratorInitialStore[classKey];
  7525. }
  7526. /**
  7527. * Return the list of properties flagged as serializable
  7528. * @param target: host object
  7529. */
  7530. function getMergedStore(target) {
  7531. var classKey = target.getClassName();
  7532. if (__mergedStore[classKey]) {
  7533. return __mergedStore[classKey];
  7534. }
  7535. __mergedStore[classKey] = {};
  7536. var store = __mergedStore[classKey];
  7537. var currentTarget = target;
  7538. var currentKey = classKey;
  7539. while (currentKey) {
  7540. var initialStore = __decoratorInitialStore[currentKey];
  7541. for (var property in initialStore) {
  7542. store[property] = initialStore[property];
  7543. }
  7544. var parent_1 = void 0;
  7545. var done = false;
  7546. do {
  7547. parent_1 = Object.getPrototypeOf(currentTarget);
  7548. if (!parent_1.getClassName) {
  7549. done = true;
  7550. break;
  7551. }
  7552. if (parent_1.getClassName() !== currentKey) {
  7553. break;
  7554. }
  7555. currentTarget = parent_1;
  7556. } while (parent_1);
  7557. if (done) {
  7558. break;
  7559. }
  7560. currentKey = parent_1.getClassName();
  7561. currentTarget = parent_1;
  7562. }
  7563. return store;
  7564. }
  7565. function generateSerializableMember(type, sourceName) {
  7566. return function (target, propertyKey) {
  7567. var classStore = getDirectStore(target);
  7568. if (!classStore[propertyKey]) {
  7569. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7570. }
  7571. };
  7572. }
  7573. function generateExpandMember(setCallback, targetKey) {
  7574. if (targetKey === void 0) { targetKey = null; }
  7575. return function (target, propertyKey) {
  7576. var key = targetKey || ("_" + propertyKey);
  7577. Object.defineProperty(target, propertyKey, {
  7578. get: function () {
  7579. return this[key];
  7580. },
  7581. set: function (value) {
  7582. if (this[key] === value) {
  7583. return;
  7584. }
  7585. this[key] = value;
  7586. target[setCallback].apply(this);
  7587. },
  7588. enumerable: true,
  7589. configurable: true
  7590. });
  7591. };
  7592. }
  7593. function expandToProperty(callback, targetKey) {
  7594. if (targetKey === void 0) { targetKey = null; }
  7595. return generateExpandMember(callback, targetKey);
  7596. }
  7597. BABYLON.expandToProperty = expandToProperty;
  7598. function serialize(sourceName) {
  7599. return generateSerializableMember(0, sourceName); // value member
  7600. }
  7601. BABYLON.serialize = serialize;
  7602. function serializeAsTexture(sourceName) {
  7603. return generateSerializableMember(1, sourceName); // texture member
  7604. }
  7605. BABYLON.serializeAsTexture = serializeAsTexture;
  7606. function serializeAsColor3(sourceName) {
  7607. return generateSerializableMember(2, sourceName); // color3 member
  7608. }
  7609. BABYLON.serializeAsColor3 = serializeAsColor3;
  7610. function serializeAsFresnelParameters(sourceName) {
  7611. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7612. }
  7613. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7614. function serializeAsVector2(sourceName) {
  7615. return generateSerializableMember(4, sourceName); // vector2 member
  7616. }
  7617. BABYLON.serializeAsVector2 = serializeAsVector2;
  7618. function serializeAsVector3(sourceName) {
  7619. return generateSerializableMember(5, sourceName); // vector3 member
  7620. }
  7621. BABYLON.serializeAsVector3 = serializeAsVector3;
  7622. function serializeAsMeshReference(sourceName) {
  7623. return generateSerializableMember(6, sourceName); // mesh reference member
  7624. }
  7625. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7626. function serializeAsColorCurves(sourceName) {
  7627. return generateSerializableMember(7, sourceName); // color curves
  7628. }
  7629. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7630. function serializeAsColor4(sourceName) {
  7631. return generateSerializableMember(8, sourceName); // color 4
  7632. }
  7633. BABYLON.serializeAsColor4 = serializeAsColor4;
  7634. function serializeAsImageProcessingConfiguration(sourceName) {
  7635. return generateSerializableMember(9, sourceName); // image processing
  7636. }
  7637. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7638. function serializeAsQuaternion(sourceName) {
  7639. return generateSerializableMember(10, sourceName); // quaternion member
  7640. }
  7641. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7642. /**
  7643. * Decorator used to define property that can be serialized as reference to a camera
  7644. * @param sourceName defines the name of the property to decorate
  7645. */
  7646. function serializeAsCameraReference(sourceName) {
  7647. return generateSerializableMember(11, sourceName); // camera reference member
  7648. }
  7649. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7650. var SerializationHelper = /** @class */ (function () {
  7651. function SerializationHelper() {
  7652. }
  7653. SerializationHelper.Serialize = function (entity, serializationObject) {
  7654. if (!serializationObject) {
  7655. serializationObject = {};
  7656. }
  7657. // Tags
  7658. if (BABYLON.Tags) {
  7659. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7660. }
  7661. var serializedProperties = getMergedStore(entity);
  7662. // Properties
  7663. for (var property in serializedProperties) {
  7664. var propertyDescriptor = serializedProperties[property];
  7665. var targetPropertyName = propertyDescriptor.sourceName || property;
  7666. var propertyType = propertyDescriptor.type;
  7667. var sourceProperty = entity[property];
  7668. if (sourceProperty !== undefined && sourceProperty !== null) {
  7669. switch (propertyType) {
  7670. case 0: // Value
  7671. serializationObject[targetPropertyName] = sourceProperty;
  7672. break;
  7673. case 1: // Texture
  7674. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7675. break;
  7676. case 2: // Color3
  7677. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7678. break;
  7679. case 3: // FresnelParameters
  7680. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7681. break;
  7682. case 4: // Vector2
  7683. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7684. break;
  7685. case 5: // Vector3
  7686. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7687. break;
  7688. case 6: // Mesh reference
  7689. serializationObject[targetPropertyName] = sourceProperty.id;
  7690. break;
  7691. case 7: // Color Curves
  7692. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7693. break;
  7694. case 8: // Color 4
  7695. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7696. break;
  7697. case 9: // Image Processing
  7698. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7699. break;
  7700. case 10: // Quaternion
  7701. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7702. break;
  7703. case 11: // Camera reference
  7704. serializationObject[targetPropertyName] = sourceProperty.id;
  7705. break;
  7706. }
  7707. }
  7708. }
  7709. return serializationObject;
  7710. };
  7711. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7712. if (rootUrl === void 0) { rootUrl = null; }
  7713. var destination = creationFunction();
  7714. if (!rootUrl) {
  7715. rootUrl = "";
  7716. }
  7717. // Tags
  7718. if (BABYLON.Tags) {
  7719. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7720. }
  7721. var classStore = getMergedStore(destination);
  7722. // Properties
  7723. for (var property in classStore) {
  7724. var propertyDescriptor = classStore[property];
  7725. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7726. var propertyType = propertyDescriptor.type;
  7727. if (sourceProperty !== undefined && sourceProperty !== null) {
  7728. var dest = destination;
  7729. switch (propertyType) {
  7730. case 0: // Value
  7731. dest[property] = sourceProperty;
  7732. break;
  7733. case 1: // Texture
  7734. if (scene) {
  7735. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7736. }
  7737. break;
  7738. case 2: // Color3
  7739. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7740. break;
  7741. case 3: // FresnelParameters
  7742. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7743. break;
  7744. case 4: // Vector2
  7745. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7746. break;
  7747. case 5: // Vector3
  7748. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7749. break;
  7750. case 6: // Mesh reference
  7751. if (scene) {
  7752. dest[property] = scene.getLastMeshByID(sourceProperty);
  7753. }
  7754. break;
  7755. case 7: // Color Curves
  7756. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7757. break;
  7758. case 8: // Color 4
  7759. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7760. break;
  7761. case 9: // Image Processing
  7762. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7763. break;
  7764. case 10: // Quaternion
  7765. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7766. break;
  7767. case 11: // Camera reference
  7768. if (scene) {
  7769. dest[property] = scene.getCameraByID(sourceProperty);
  7770. }
  7771. break;
  7772. }
  7773. }
  7774. }
  7775. return destination;
  7776. };
  7777. SerializationHelper.Clone = function (creationFunction, source) {
  7778. return _copySource(creationFunction, source, false);
  7779. };
  7780. SerializationHelper.Instanciate = function (creationFunction, source) {
  7781. return _copySource(creationFunction, source, true);
  7782. };
  7783. return SerializationHelper;
  7784. }());
  7785. BABYLON.SerializationHelper = SerializationHelper;
  7786. })(BABYLON || (BABYLON = {}));
  7787. //# sourceMappingURL=babylon.decorators.js.map
  7788. var BABYLON;
  7789. (function (BABYLON) {
  7790. /**
  7791. * Wrapper class for promise with external resolve and reject.
  7792. */
  7793. var Deferred = /** @class */ (function () {
  7794. /**
  7795. * Constructor for this deferred object.
  7796. */
  7797. function Deferred() {
  7798. var _this = this;
  7799. this.promise = new Promise(function (resolve, reject) {
  7800. _this._resolve = resolve;
  7801. _this._reject = reject;
  7802. });
  7803. }
  7804. Object.defineProperty(Deferred.prototype, "resolve", {
  7805. /**
  7806. * The resolve method of the promise associated with this deferred object.
  7807. */
  7808. get: function () {
  7809. return this._resolve;
  7810. },
  7811. enumerable: true,
  7812. configurable: true
  7813. });
  7814. Object.defineProperty(Deferred.prototype, "reject", {
  7815. /**
  7816. * The reject method of the promise associated with this deferred object.
  7817. */
  7818. get: function () {
  7819. return this._reject;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. return Deferred;
  7825. }());
  7826. BABYLON.Deferred = Deferred;
  7827. })(BABYLON || (BABYLON = {}));
  7828. //# sourceMappingURL=babylon.deferred.js.map
  7829. var BABYLON;
  7830. (function (BABYLON) {
  7831. /**
  7832. * A class serves as a medium between the observable and its observers
  7833. */
  7834. var EventState = /** @class */ (function () {
  7835. /**
  7836. * Create a new EventState
  7837. * @param mask defines the mask associated with this state
  7838. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7839. * @param target defines the original target of the state
  7840. * @param currentTarget defines the current target of the state
  7841. */
  7842. function EventState(mask, skipNextObservers, target, currentTarget) {
  7843. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7844. this.initalize(mask, skipNextObservers, target, currentTarget);
  7845. }
  7846. /**
  7847. * Initialize the current event state
  7848. * @param mask defines the mask associated with this state
  7849. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7850. * @param target defines the original target of the state
  7851. * @param currentTarget defines the current target of the state
  7852. * @returns the current event state
  7853. */
  7854. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7855. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7856. this.mask = mask;
  7857. this.skipNextObservers = skipNextObservers;
  7858. this.target = target;
  7859. this.currentTarget = currentTarget;
  7860. return this;
  7861. };
  7862. return EventState;
  7863. }());
  7864. BABYLON.EventState = EventState;
  7865. /**
  7866. * Represent an Observer registered to a given Observable object.
  7867. */
  7868. var Observer = /** @class */ (function () {
  7869. /**
  7870. * Creates a new observer
  7871. * @param callback defines the callback to call when the observer is notified
  7872. * @param mask defines the mask of the observer (used to filter notifications)
  7873. * @param scope defines the current scope used to restore the JS context
  7874. */
  7875. function Observer(
  7876. /**
  7877. * Defines the callback to call when the observer is notified
  7878. */
  7879. callback,
  7880. /**
  7881. * Defines the mask of the observer (used to filter notifications)
  7882. */
  7883. mask,
  7884. /**
  7885. * Defines the current scope used to restore the JS context
  7886. */
  7887. scope) {
  7888. if (scope === void 0) { scope = null; }
  7889. this.callback = callback;
  7890. this.mask = mask;
  7891. this.scope = scope;
  7892. /** @ignore */
  7893. this._willBeUnregistered = false;
  7894. /**
  7895. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7896. */
  7897. this.unregisterOnNextCall = false;
  7898. }
  7899. return Observer;
  7900. }());
  7901. BABYLON.Observer = Observer;
  7902. /**
  7903. * Represent a list of observers registered to multiple Observables object.
  7904. */
  7905. var MultiObserver = /** @class */ (function () {
  7906. function MultiObserver() {
  7907. }
  7908. /**
  7909. * Release associated resources
  7910. */
  7911. MultiObserver.prototype.dispose = function () {
  7912. if (this._observers && this._observables) {
  7913. for (var index = 0; index < this._observers.length; index++) {
  7914. this._observables[index].remove(this._observers[index]);
  7915. }
  7916. }
  7917. this._observers = null;
  7918. this._observables = null;
  7919. };
  7920. /**
  7921. * Raise a callback when one of the observable will notify
  7922. * @param observables defines a list of observables to watch
  7923. * @param callback defines the callback to call on notification
  7924. * @param mask defines the mask used to filter notifications
  7925. * @param scope defines the current scope used to restore the JS context
  7926. * @returns the new MultiObserver
  7927. */
  7928. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7929. if (mask === void 0) { mask = -1; }
  7930. if (scope === void 0) { scope = null; }
  7931. var result = new MultiObserver();
  7932. result._observers = new Array();
  7933. result._observables = observables;
  7934. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7935. var observable = observables_1[_i];
  7936. var observer = observable.add(callback, mask, false, scope);
  7937. if (observer) {
  7938. result._observers.push(observer);
  7939. }
  7940. }
  7941. return result;
  7942. };
  7943. return MultiObserver;
  7944. }());
  7945. BABYLON.MultiObserver = MultiObserver;
  7946. /**
  7947. * The Observable class is a simple implementation of the Observable pattern.
  7948. *
  7949. * 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.
  7950. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7951. * 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).
  7952. * 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.
  7953. */
  7954. var Observable = /** @class */ (function () {
  7955. /**
  7956. * Creates a new observable
  7957. * @param onObserverAdded defines a callback to call when a new observer is added
  7958. */
  7959. function Observable(onObserverAdded) {
  7960. this._observers = new Array();
  7961. this._eventState = new EventState(0);
  7962. if (onObserverAdded) {
  7963. this._onObserverAdded = onObserverAdded;
  7964. }
  7965. }
  7966. /**
  7967. * Create a new Observer with the specified callback
  7968. * @param callback the callback that will be executed for that Observer
  7969. * @param mask the mask used to filter observers
  7970. * @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.
  7971. * @param scope optional scope for the callback to be called from
  7972. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7973. * @returns the new observer created for the callback
  7974. */
  7975. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7976. if (mask === void 0) { mask = -1; }
  7977. if (insertFirst === void 0) { insertFirst = false; }
  7978. if (scope === void 0) { scope = null; }
  7979. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7980. if (!callback) {
  7981. return null;
  7982. }
  7983. var observer = new Observer(callback, mask, scope);
  7984. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7985. if (insertFirst) {
  7986. this._observers.unshift(observer);
  7987. }
  7988. else {
  7989. this._observers.push(observer);
  7990. }
  7991. if (this._onObserverAdded) {
  7992. this._onObserverAdded(observer);
  7993. }
  7994. return observer;
  7995. };
  7996. /**
  7997. * Remove an Observer from the Observable object
  7998. * @param observer the instance of the Observer to remove
  7999. * @returns false if it doesn't belong to this Observable
  8000. */
  8001. Observable.prototype.remove = function (observer) {
  8002. if (!observer) {
  8003. return false;
  8004. }
  8005. var index = this._observers.indexOf(observer);
  8006. if (index !== -1) {
  8007. this._observers.splice(index, 1);
  8008. return true;
  8009. }
  8010. return false;
  8011. };
  8012. /**
  8013. * Remove a callback from the Observable object
  8014. * @param callback the callback to remove
  8015. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8016. * @returns false if it doesn't belong to this Observable
  8017. */
  8018. Observable.prototype.removeCallback = function (callback, scope) {
  8019. for (var index = 0; index < this._observers.length; index++) {
  8020. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8021. this._observers.splice(index, 1);
  8022. return true;
  8023. }
  8024. }
  8025. return false;
  8026. };
  8027. Observable.prototype._deferUnregister = function (observer) {
  8028. var _this = this;
  8029. observer.unregisterOnNextCall = false;
  8030. observer._willBeUnregistered = true;
  8031. BABYLON.Tools.SetImmediate(function () {
  8032. _this.remove(observer);
  8033. });
  8034. };
  8035. /**
  8036. * Notify all Observers by calling their respective callback with the given data
  8037. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8038. * @param eventData defines the data to send to all observers
  8039. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8040. * @param target defines the original target of the state
  8041. * @param currentTarget defines the current target of the state
  8042. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8043. */
  8044. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8045. if (mask === void 0) { mask = -1; }
  8046. if (!this._observers.length) {
  8047. return true;
  8048. }
  8049. var state = this._eventState;
  8050. state.mask = mask;
  8051. state.target = target;
  8052. state.currentTarget = currentTarget;
  8053. state.skipNextObservers = false;
  8054. state.lastReturnValue = eventData;
  8055. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8056. var obs = _a[_i];
  8057. if (obs._willBeUnregistered) {
  8058. continue;
  8059. }
  8060. if (obs.mask & mask) {
  8061. if (obs.scope) {
  8062. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8063. }
  8064. else {
  8065. state.lastReturnValue = obs.callback(eventData, state);
  8066. }
  8067. if (obs.unregisterOnNextCall) {
  8068. this._deferUnregister(obs);
  8069. }
  8070. }
  8071. if (state.skipNextObservers) {
  8072. return false;
  8073. }
  8074. }
  8075. return true;
  8076. };
  8077. /**
  8078. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8079. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8080. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8081. * and it is crucial that all callbacks will be executed.
  8082. * The order of the callbacks is kept, callbacks are not executed parallel.
  8083. *
  8084. * @param eventData The data to be sent to each callback
  8085. * @param mask is used to filter observers defaults to -1
  8086. * @param target defines the callback target (see EventState)
  8087. * @param currentTarget defines he current object in the bubbling phase
  8088. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8089. */
  8090. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8091. var _this = this;
  8092. if (mask === void 0) { mask = -1; }
  8093. // create an empty promise
  8094. var p = Promise.resolve(eventData);
  8095. // no observers? return this promise.
  8096. if (!this._observers.length) {
  8097. return p;
  8098. }
  8099. var state = this._eventState;
  8100. state.mask = mask;
  8101. state.target = target;
  8102. state.currentTarget = currentTarget;
  8103. state.skipNextObservers = false;
  8104. // execute one callback after another (not using Promise.all, the order is important)
  8105. this._observers.forEach(function (obs) {
  8106. if (state.skipNextObservers) {
  8107. return;
  8108. }
  8109. if (obs._willBeUnregistered) {
  8110. return;
  8111. }
  8112. if (obs.mask & mask) {
  8113. if (obs.scope) {
  8114. p = p.then(function (lastReturnedValue) {
  8115. state.lastReturnValue = lastReturnedValue;
  8116. return obs.callback.apply(obs.scope, [eventData, state]);
  8117. });
  8118. }
  8119. else {
  8120. p = p.then(function (lastReturnedValue) {
  8121. state.lastReturnValue = lastReturnedValue;
  8122. return obs.callback(eventData, state);
  8123. });
  8124. }
  8125. if (obs.unregisterOnNextCall) {
  8126. _this._deferUnregister(obs);
  8127. }
  8128. }
  8129. });
  8130. // return the eventData
  8131. return p.then(function () { return eventData; });
  8132. };
  8133. /**
  8134. * Notify a specific observer
  8135. * @param observer defines the observer to notify
  8136. * @param eventData defines the data to be sent to each callback
  8137. * @param mask is used to filter observers defaults to -1
  8138. */
  8139. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8140. if (mask === void 0) { mask = -1; }
  8141. var state = this._eventState;
  8142. state.mask = mask;
  8143. state.skipNextObservers = false;
  8144. observer.callback(eventData, state);
  8145. };
  8146. /**
  8147. * Gets a boolean indicating if the observable has at least one observer
  8148. * @returns true is the Observable has at least one Observer registered
  8149. */
  8150. Observable.prototype.hasObservers = function () {
  8151. return this._observers.length > 0;
  8152. };
  8153. /**
  8154. * Clear the list of observers
  8155. */
  8156. Observable.prototype.clear = function () {
  8157. this._observers = new Array();
  8158. this._onObserverAdded = null;
  8159. };
  8160. /**
  8161. * Clone the current observable
  8162. * @returns a new observable
  8163. */
  8164. Observable.prototype.clone = function () {
  8165. var result = new Observable();
  8166. result._observers = this._observers.slice(0);
  8167. return result;
  8168. };
  8169. /**
  8170. * Does this observable handles observer registered with a given mask
  8171. * @param mask defines the mask to be tested
  8172. * @return whether or not one observer registered with the given mask is handeled
  8173. **/
  8174. Observable.prototype.hasSpecificMask = function (mask) {
  8175. if (mask === void 0) { mask = -1; }
  8176. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8177. var obs = _a[_i];
  8178. if (obs.mask & mask || obs.mask === mask) {
  8179. return true;
  8180. }
  8181. }
  8182. return false;
  8183. };
  8184. return Observable;
  8185. }());
  8186. BABYLON.Observable = Observable;
  8187. })(BABYLON || (BABYLON = {}));
  8188. //# sourceMappingURL=babylon.observable.js.map
  8189. var BABYLON;
  8190. (function (BABYLON) {
  8191. var SmartArray = /** @class */ (function () {
  8192. function SmartArray(capacity) {
  8193. this.length = 0;
  8194. this.data = new Array(capacity);
  8195. this._id = SmartArray._GlobalId++;
  8196. }
  8197. SmartArray.prototype.push = function (value) {
  8198. this.data[this.length++] = value;
  8199. if (this.length > this.data.length) {
  8200. this.data.length *= 2;
  8201. }
  8202. };
  8203. SmartArray.prototype.forEach = function (func) {
  8204. for (var index = 0; index < this.length; index++) {
  8205. func(this.data[index]);
  8206. }
  8207. };
  8208. SmartArray.prototype.sort = function (compareFn) {
  8209. this.data.sort(compareFn);
  8210. };
  8211. SmartArray.prototype.reset = function () {
  8212. this.length = 0;
  8213. };
  8214. SmartArray.prototype.dispose = function () {
  8215. this.reset();
  8216. if (this.data) {
  8217. this.data.length = 0;
  8218. this.data = [];
  8219. }
  8220. };
  8221. SmartArray.prototype.concat = function (array) {
  8222. if (array.length === 0) {
  8223. return;
  8224. }
  8225. if (this.length + array.length > this.data.length) {
  8226. this.data.length = (this.length + array.length) * 2;
  8227. }
  8228. for (var index = 0; index < array.length; index++) {
  8229. this.data[this.length++] = (array.data || array)[index];
  8230. }
  8231. };
  8232. SmartArray.prototype.indexOf = function (value) {
  8233. var position = this.data.indexOf(value);
  8234. if (position >= this.length) {
  8235. return -1;
  8236. }
  8237. return position;
  8238. };
  8239. SmartArray.prototype.contains = function (value) {
  8240. return this.data.indexOf(value) !== -1;
  8241. };
  8242. // Statics
  8243. SmartArray._GlobalId = 0;
  8244. return SmartArray;
  8245. }());
  8246. BABYLON.SmartArray = SmartArray;
  8247. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8248. __extends(SmartArrayNoDuplicate, _super);
  8249. function SmartArrayNoDuplicate() {
  8250. var _this = _super !== null && _super.apply(this, arguments) || this;
  8251. _this._duplicateId = 0;
  8252. return _this;
  8253. }
  8254. SmartArrayNoDuplicate.prototype.push = function (value) {
  8255. _super.prototype.push.call(this, value);
  8256. if (!value.__smartArrayFlags) {
  8257. value.__smartArrayFlags = {};
  8258. }
  8259. value.__smartArrayFlags[this._id] = this._duplicateId;
  8260. };
  8261. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8262. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8263. return false;
  8264. }
  8265. this.push(value);
  8266. return true;
  8267. };
  8268. SmartArrayNoDuplicate.prototype.reset = function () {
  8269. _super.prototype.reset.call(this);
  8270. this._duplicateId++;
  8271. };
  8272. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8273. if (array.length === 0) {
  8274. return;
  8275. }
  8276. if (this.length + array.length > this.data.length) {
  8277. this.data.length = (this.length + array.length) * 2;
  8278. }
  8279. for (var index = 0; index < array.length; index++) {
  8280. var item = (array.data || array)[index];
  8281. this.pushNoDuplicate(item);
  8282. }
  8283. };
  8284. return SmartArrayNoDuplicate;
  8285. }(SmartArray));
  8286. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8287. })(BABYLON || (BABYLON = {}));
  8288. //# sourceMappingURL=babylon.smartArray.js.map
  8289. var BABYLON;
  8290. (function (BABYLON) {
  8291. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8292. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8293. var LoadFileError = /** @class */ (function (_super) {
  8294. __extends(LoadFileError, _super);
  8295. function LoadFileError(message, request) {
  8296. var _this = _super.call(this, message) || this;
  8297. _this.request = request;
  8298. _this.name = "LoadFileError";
  8299. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8300. return _this;
  8301. }
  8302. // Polyfill for Object.setPrototypeOf if necessary.
  8303. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8304. return LoadFileError;
  8305. }(Error));
  8306. BABYLON.LoadFileError = LoadFileError;
  8307. var RetryStrategy = /** @class */ (function () {
  8308. function RetryStrategy() {
  8309. }
  8310. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8311. if (maxRetries === void 0) { maxRetries = 3; }
  8312. if (baseInterval === void 0) { baseInterval = 500; }
  8313. return function (url, request, retryIndex) {
  8314. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8315. return -1;
  8316. }
  8317. return Math.pow(2, retryIndex) * baseInterval;
  8318. };
  8319. };
  8320. return RetryStrategy;
  8321. }());
  8322. BABYLON.RetryStrategy = RetryStrategy;
  8323. // Screenshots
  8324. var screenshotCanvas;
  8325. var cloneValue = function (source, destinationObject) {
  8326. if (!source)
  8327. return null;
  8328. if (source instanceof BABYLON.Mesh) {
  8329. return null;
  8330. }
  8331. if (source instanceof BABYLON.SubMesh) {
  8332. return source.clone(destinationObject);
  8333. }
  8334. else if (source.clone) {
  8335. return source.clone();
  8336. }
  8337. return null;
  8338. };
  8339. var Tools = /** @class */ (function () {
  8340. function Tools() {
  8341. }
  8342. /**
  8343. * Interpolates between a and b via alpha
  8344. * @param a The lower value (returned when alpha = 0)
  8345. * @param b The upper value (returned when alpha = 1)
  8346. * @param alpha The interpolation-factor
  8347. * @return The mixed value
  8348. */
  8349. Tools.Mix = function (a, b, alpha) {
  8350. return a * (1 - alpha) + b * alpha;
  8351. };
  8352. Tools.Instantiate = function (className) {
  8353. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8354. return Tools.RegisteredExternalClasses[className];
  8355. }
  8356. var arr = className.split(".");
  8357. var fn = (window || this);
  8358. for (var i = 0, len = arr.length; i < len; i++) {
  8359. fn = fn[arr[i]];
  8360. }
  8361. if (typeof fn !== "function") {
  8362. return null;
  8363. }
  8364. return fn;
  8365. };
  8366. /**
  8367. * Provides a slice function that will work even on IE
  8368. * @param data defines the array to slice
  8369. * @param start defines the start of the data (optional)
  8370. * @param end defines the end of the data (optional)
  8371. * @returns the new sliced array
  8372. */
  8373. Tools.Slice = function (data, start, end) {
  8374. if (data.slice) {
  8375. return data.slice(start, end);
  8376. }
  8377. return Array.prototype.slice.call(data, start, end);
  8378. };
  8379. Tools.SetImmediate = function (action) {
  8380. if (window.setImmediate) {
  8381. window.setImmediate(action);
  8382. }
  8383. else {
  8384. setTimeout(action, 1);
  8385. }
  8386. };
  8387. Tools.IsExponentOfTwo = function (value) {
  8388. var count = 1;
  8389. do {
  8390. count *= 2;
  8391. } while (count < value);
  8392. return count === value;
  8393. };
  8394. /**
  8395. * Find the next highest power of two.
  8396. * @param x Number to start search from.
  8397. * @return Next highest power of two.
  8398. */
  8399. Tools.CeilingPOT = function (x) {
  8400. x--;
  8401. x |= x >> 1;
  8402. x |= x >> 2;
  8403. x |= x >> 4;
  8404. x |= x >> 8;
  8405. x |= x >> 16;
  8406. x++;
  8407. return x;
  8408. };
  8409. /**
  8410. * Find the next lowest power of two.
  8411. * @param x Number to start search from.
  8412. * @return Next lowest power of two.
  8413. */
  8414. Tools.FloorPOT = function (x) {
  8415. x = x | (x >> 1);
  8416. x = x | (x >> 2);
  8417. x = x | (x >> 4);
  8418. x = x | (x >> 8);
  8419. x = x | (x >> 16);
  8420. return x - (x >> 1);
  8421. };
  8422. /**
  8423. * Find the nearest power of two.
  8424. * @param x Number to start search from.
  8425. * @return Next nearest power of two.
  8426. */
  8427. Tools.NearestPOT = function (x) {
  8428. var c = Tools.CeilingPOT(x);
  8429. var f = Tools.FloorPOT(x);
  8430. return (c - x) > (x - f) ? f : c;
  8431. };
  8432. Tools.GetExponentOfTwo = function (value, max, mode) {
  8433. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8434. var pot;
  8435. switch (mode) {
  8436. case BABYLON.Engine.SCALEMODE_FLOOR:
  8437. pot = Tools.FloorPOT(value);
  8438. break;
  8439. case BABYLON.Engine.SCALEMODE_NEAREST:
  8440. pot = Tools.NearestPOT(value);
  8441. break;
  8442. case BABYLON.Engine.SCALEMODE_CEILING:
  8443. default:
  8444. pot = Tools.CeilingPOT(value);
  8445. break;
  8446. }
  8447. return Math.min(pot, max);
  8448. };
  8449. Tools.GetFilename = function (path) {
  8450. var index = path.lastIndexOf("/");
  8451. if (index < 0)
  8452. return path;
  8453. return path.substring(index + 1);
  8454. };
  8455. /**
  8456. * Extracts the "folder" part of a path (everything before the filename).
  8457. * @param uri The URI to extract the info from
  8458. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8459. * @returns The "folder" part of the path
  8460. */
  8461. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8462. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8463. var index = uri.lastIndexOf("/");
  8464. if (index < 0) {
  8465. if (returnUnchangedIfNoSlash) {
  8466. return uri;
  8467. }
  8468. return "";
  8469. }
  8470. return uri.substring(0, index + 1);
  8471. };
  8472. Tools.GetDOMTextContent = function (element) {
  8473. var result = "";
  8474. var child = element.firstChild;
  8475. while (child) {
  8476. if (child.nodeType === 3) {
  8477. result += child.textContent;
  8478. }
  8479. child = child.nextSibling;
  8480. }
  8481. return result;
  8482. };
  8483. Tools.ToDegrees = function (angle) {
  8484. return angle * 180 / Math.PI;
  8485. };
  8486. Tools.ToRadians = function (angle) {
  8487. return angle * Math.PI / 180;
  8488. };
  8489. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8490. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8491. var output = "";
  8492. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8493. var i = 0;
  8494. var bytes = new Uint8Array(buffer);
  8495. while (i < bytes.length) {
  8496. chr1 = bytes[i++];
  8497. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8498. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8499. enc1 = chr1 >> 2;
  8500. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8501. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8502. enc4 = chr3 & 63;
  8503. if (isNaN(chr2)) {
  8504. enc3 = enc4 = 64;
  8505. }
  8506. else if (isNaN(chr3)) {
  8507. enc4 = 64;
  8508. }
  8509. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8510. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8511. }
  8512. return "data:image/png;base64," + output;
  8513. };
  8514. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8515. if (bias === void 0) { bias = null; }
  8516. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8517. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8518. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8519. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8520. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8521. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8522. }
  8523. if (bias) {
  8524. minimum.x -= minimum.x * bias.x + bias.y;
  8525. minimum.y -= minimum.y * bias.x + bias.y;
  8526. minimum.z -= minimum.z * bias.x + bias.y;
  8527. maximum.x += maximum.x * bias.x + bias.y;
  8528. maximum.y += maximum.y * bias.x + bias.y;
  8529. maximum.z += maximum.z * bias.x + bias.y;
  8530. }
  8531. return {
  8532. minimum: minimum,
  8533. maximum: maximum
  8534. };
  8535. };
  8536. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8537. if (bias === void 0) { bias = null; }
  8538. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8539. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8540. if (!stride) {
  8541. stride = 3;
  8542. }
  8543. for (var index = start; index < start + count; index++) {
  8544. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8545. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8546. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8547. }
  8548. if (bias) {
  8549. minimum.x -= minimum.x * bias.x + bias.y;
  8550. minimum.y -= minimum.y * bias.x + bias.y;
  8551. minimum.z -= minimum.z * bias.x + bias.y;
  8552. maximum.x += maximum.x * bias.x + bias.y;
  8553. maximum.y += maximum.y * bias.x + bias.y;
  8554. maximum.z += maximum.z * bias.x + bias.y;
  8555. }
  8556. return {
  8557. minimum: minimum,
  8558. maximum: maximum
  8559. };
  8560. };
  8561. Tools.Vector2ArrayFeeder = function (array) {
  8562. return function (index) {
  8563. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8564. var length = isFloatArray ? array.length / 2 : array.length;
  8565. if (index >= length) {
  8566. return null;
  8567. }
  8568. if (isFloatArray) {
  8569. var fa = array;
  8570. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8571. }
  8572. var a = array;
  8573. return a[index];
  8574. };
  8575. };
  8576. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8577. if (bias === void 0) { bias = null; }
  8578. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8579. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8580. var i = 0;
  8581. var cur = feeder(i++);
  8582. while (cur) {
  8583. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8584. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8585. cur = feeder(i++);
  8586. }
  8587. if (bias) {
  8588. minimum.x -= minimum.x * bias.x + bias.y;
  8589. minimum.y -= minimum.y * bias.x + bias.y;
  8590. maximum.x += maximum.x * bias.x + bias.y;
  8591. maximum.y += maximum.y * bias.x + bias.y;
  8592. }
  8593. return {
  8594. minimum: minimum,
  8595. maximum: maximum
  8596. };
  8597. };
  8598. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8599. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8600. return null;
  8601. return Array.isArray(obj) ? obj : [obj];
  8602. };
  8603. // Misc.
  8604. Tools.GetPointerPrefix = function () {
  8605. var eventPrefix = "pointer";
  8606. // Check if pointer events are supported
  8607. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8608. eventPrefix = "mouse";
  8609. }
  8610. return eventPrefix;
  8611. };
  8612. /**
  8613. * @param func - the function to be called
  8614. * @param requester - the object that will request the next frame. Falls back to window.
  8615. */
  8616. Tools.QueueNewFrame = function (func, requester) {
  8617. if (!Tools.IsWindowObjectExist()) {
  8618. return setTimeout(func, 16);
  8619. }
  8620. if (!requester) {
  8621. requester = window;
  8622. }
  8623. if (requester.requestAnimationFrame) {
  8624. return requester.requestAnimationFrame(func);
  8625. }
  8626. else if (requester.msRequestAnimationFrame) {
  8627. return requester.msRequestAnimationFrame(func);
  8628. }
  8629. else if (requester.webkitRequestAnimationFrame) {
  8630. return requester.webkitRequestAnimationFrame(func);
  8631. }
  8632. else if (requester.mozRequestAnimationFrame) {
  8633. return requester.mozRequestAnimationFrame(func);
  8634. }
  8635. else if (requester.oRequestAnimationFrame) {
  8636. return requester.oRequestAnimationFrame(func);
  8637. }
  8638. else {
  8639. return window.setTimeout(func, 16);
  8640. }
  8641. };
  8642. Tools.RequestFullscreen = function (element) {
  8643. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8644. if (!requestFunction)
  8645. return;
  8646. requestFunction.call(element);
  8647. };
  8648. Tools.ExitFullscreen = function () {
  8649. if (document.exitFullscreen) {
  8650. document.exitFullscreen();
  8651. }
  8652. else if (document.mozCancelFullScreen) {
  8653. document.mozCancelFullScreen();
  8654. }
  8655. else if (document.webkitCancelFullScreen) {
  8656. document.webkitCancelFullScreen();
  8657. }
  8658. else if (document.msCancelFullScreen) {
  8659. document.msCancelFullScreen();
  8660. }
  8661. };
  8662. Tools.SetCorsBehavior = function (url, element) {
  8663. if (url && url.indexOf("data:") === 0) {
  8664. return;
  8665. }
  8666. if (Tools.CorsBehavior) {
  8667. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8668. element.crossOrigin = Tools.CorsBehavior;
  8669. }
  8670. else {
  8671. var result = Tools.CorsBehavior(url);
  8672. if (result) {
  8673. element.crossOrigin = result;
  8674. }
  8675. }
  8676. }
  8677. };
  8678. // External files
  8679. Tools.CleanUrl = function (url) {
  8680. url = url.replace(/#/mg, "%23");
  8681. return url;
  8682. };
  8683. Tools.LoadImage = function (url, onLoad, onError, database) {
  8684. if (url instanceof ArrayBuffer) {
  8685. url = Tools.EncodeArrayBufferTobase64(url);
  8686. }
  8687. url = Tools.CleanUrl(url);
  8688. url = Tools.PreprocessUrl(url);
  8689. var img = new Image();
  8690. Tools.SetCorsBehavior(url, img);
  8691. var loadHandler = function () {
  8692. img.removeEventListener("load", loadHandler);
  8693. img.removeEventListener("error", errorHandler);
  8694. onLoad(img);
  8695. };
  8696. var errorHandler = function (err) {
  8697. img.removeEventListener("load", loadHandler);
  8698. img.removeEventListener("error", errorHandler);
  8699. Tools.Error("Error while trying to load image: " + url);
  8700. if (onError) {
  8701. onError("Error while trying to load image: " + url, err);
  8702. }
  8703. };
  8704. img.addEventListener("load", loadHandler);
  8705. img.addEventListener("error", errorHandler);
  8706. var noIndexedDB = function () {
  8707. img.src = url;
  8708. };
  8709. var loadFromIndexedDB = function () {
  8710. if (database) {
  8711. database.loadImageFromDB(url, img);
  8712. }
  8713. };
  8714. //ANY database to do!
  8715. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8716. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8717. }
  8718. else {
  8719. if (url.indexOf("file:") !== -1) {
  8720. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8721. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8722. try {
  8723. var blobURL;
  8724. try {
  8725. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8726. }
  8727. catch (ex) {
  8728. // Chrome doesn't support oneTimeOnly parameter
  8729. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8730. }
  8731. img.src = blobURL;
  8732. }
  8733. catch (e) {
  8734. img.src = "";
  8735. }
  8736. return img;
  8737. }
  8738. }
  8739. noIndexedDB();
  8740. }
  8741. return img;
  8742. };
  8743. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8744. url = Tools.CleanUrl(url);
  8745. url = Tools.PreprocessUrl(url);
  8746. // If file and file input are set
  8747. if (url.indexOf("file:") !== -1) {
  8748. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8749. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8750. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8751. }
  8752. }
  8753. var loadUrl = Tools.BaseUrl + url;
  8754. var aborted = false;
  8755. var fileRequest = {
  8756. onCompleteObservable: new BABYLON.Observable(),
  8757. abort: function () { return aborted = true; },
  8758. };
  8759. var requestFile = function () {
  8760. var request = new XMLHttpRequest();
  8761. var retryHandle = null;
  8762. fileRequest.abort = function () {
  8763. aborted = true;
  8764. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8765. request.abort();
  8766. }
  8767. if (retryHandle !== null) {
  8768. clearTimeout(retryHandle);
  8769. retryHandle = null;
  8770. }
  8771. };
  8772. var retryLoop = function (retryIndex) {
  8773. request.open('GET', loadUrl, true);
  8774. if (useArrayBuffer) {
  8775. request.responseType = "arraybuffer";
  8776. }
  8777. if (onProgress) {
  8778. request.addEventListener("progress", onProgress);
  8779. }
  8780. var onLoadEnd = function () {
  8781. request.removeEventListener("loadend", onLoadEnd);
  8782. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8783. fileRequest.onCompleteObservable.clear();
  8784. };
  8785. request.addEventListener("loadend", onLoadEnd);
  8786. var onReadyStateChange = function () {
  8787. if (aborted) {
  8788. return;
  8789. }
  8790. // In case of undefined state in some browsers.
  8791. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8792. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8793. request.removeEventListener("readystatechange", onReadyStateChange);
  8794. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8795. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8796. return;
  8797. }
  8798. var retryStrategy = Tools.DefaultRetryStrategy;
  8799. if (retryStrategy) {
  8800. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8801. if (waitTime !== -1) {
  8802. // Prevent the request from completing for retry.
  8803. request.removeEventListener("loadend", onLoadEnd);
  8804. request = new XMLHttpRequest();
  8805. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8806. return;
  8807. }
  8808. }
  8809. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8810. if (onError) {
  8811. onError(request, e);
  8812. }
  8813. else {
  8814. throw e;
  8815. }
  8816. }
  8817. };
  8818. request.addEventListener("readystatechange", onReadyStateChange);
  8819. request.send();
  8820. };
  8821. retryLoop(0);
  8822. };
  8823. // Caching all files
  8824. if (database && database.enableSceneOffline) {
  8825. var noIndexedDB_1 = function () {
  8826. if (!aborted) {
  8827. requestFile();
  8828. }
  8829. };
  8830. var loadFromIndexedDB = function () {
  8831. // TODO: database needs to support aborting and should return a IFileRequest
  8832. if (aborted) {
  8833. return;
  8834. }
  8835. if (database) {
  8836. database.loadFileFromDB(url, function (data) {
  8837. if (!aborted) {
  8838. onSuccess(data);
  8839. }
  8840. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8841. }, onProgress ? function (event) {
  8842. if (!aborted) {
  8843. onProgress(event);
  8844. }
  8845. } : undefined, noIndexedDB_1, useArrayBuffer);
  8846. }
  8847. };
  8848. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8849. }
  8850. else {
  8851. requestFile();
  8852. }
  8853. return fileRequest;
  8854. };
  8855. /**
  8856. * Load a script (identified by an url). When the url returns, the
  8857. * content of this file is added into a new script element, attached to the DOM (body element)
  8858. */
  8859. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8860. var head = document.getElementsByTagName('head')[0];
  8861. var script = document.createElement('script');
  8862. script.type = 'text/javascript';
  8863. script.src = scriptUrl;
  8864. script.onload = function () {
  8865. if (onSuccess) {
  8866. onSuccess();
  8867. }
  8868. };
  8869. script.onerror = function (e) {
  8870. if (onError) {
  8871. onError("Unable to load script '" + scriptUrl + "'", e);
  8872. }
  8873. };
  8874. head.appendChild(script);
  8875. };
  8876. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8877. var reader = new FileReader();
  8878. var request = {
  8879. onCompleteObservable: new BABYLON.Observable(),
  8880. abort: function () { return reader.abort(); },
  8881. };
  8882. reader.onloadend = function (e) {
  8883. request.onCompleteObservable.notifyObservers(request);
  8884. };
  8885. reader.onload = function (e) {
  8886. //target doesn't have result from ts 1.3
  8887. callback(e.target['result']);
  8888. };
  8889. reader.onprogress = progressCallback;
  8890. reader.readAsDataURL(fileToLoad);
  8891. return request;
  8892. };
  8893. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8894. var reader = new FileReader();
  8895. var request = {
  8896. onCompleteObservable: new BABYLON.Observable(),
  8897. abort: function () { return reader.abort(); },
  8898. };
  8899. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8900. reader.onerror = function (e) {
  8901. Tools.Log("Error while reading file: " + fileToLoad.name);
  8902. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8903. };
  8904. reader.onload = function (e) {
  8905. //target doesn't have result from ts 1.3
  8906. callback(e.target['result']);
  8907. };
  8908. if (progressCallBack) {
  8909. reader.onprogress = progressCallBack;
  8910. }
  8911. if (!useArrayBuffer) {
  8912. // Asynchronous read
  8913. reader.readAsText(fileToLoad);
  8914. }
  8915. else {
  8916. reader.readAsArrayBuffer(fileToLoad);
  8917. }
  8918. return request;
  8919. };
  8920. //returns a downloadable url to a file content.
  8921. Tools.FileAsURL = function (content) {
  8922. var fileBlob = new Blob([content]);
  8923. var url = window.URL || window.webkitURL;
  8924. var link = url.createObjectURL(fileBlob);
  8925. return link;
  8926. };
  8927. // Misc.
  8928. Tools.Format = function (value, decimals) {
  8929. if (decimals === void 0) { decimals = 2; }
  8930. return value.toFixed(decimals);
  8931. };
  8932. Tools.CheckExtends = function (v, min, max) {
  8933. if (v.x < min.x)
  8934. min.x = v.x;
  8935. if (v.y < min.y)
  8936. min.y = v.y;
  8937. if (v.z < min.z)
  8938. min.z = v.z;
  8939. if (v.x > max.x)
  8940. max.x = v.x;
  8941. if (v.y > max.y)
  8942. max.y = v.y;
  8943. if (v.z > max.z)
  8944. max.z = v.z;
  8945. };
  8946. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8947. for (var prop in source) {
  8948. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8949. continue;
  8950. }
  8951. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8952. continue;
  8953. }
  8954. var sourceValue = source[prop];
  8955. var typeOfSourceValue = typeof sourceValue;
  8956. if (typeOfSourceValue === "function") {
  8957. continue;
  8958. }
  8959. try {
  8960. if (typeOfSourceValue === "object") {
  8961. if (sourceValue instanceof Array) {
  8962. destination[prop] = [];
  8963. if (sourceValue.length > 0) {
  8964. if (typeof sourceValue[0] == "object") {
  8965. for (var index = 0; index < sourceValue.length; index++) {
  8966. var clonedValue = cloneValue(sourceValue[index], destination);
  8967. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  8968. destination[prop].push(clonedValue);
  8969. }
  8970. }
  8971. }
  8972. else {
  8973. destination[prop] = sourceValue.slice(0);
  8974. }
  8975. }
  8976. }
  8977. else {
  8978. destination[prop] = cloneValue(sourceValue, destination);
  8979. }
  8980. }
  8981. else {
  8982. destination[prop] = sourceValue;
  8983. }
  8984. }
  8985. catch (e) {
  8986. // Just ignore error (it could be because of a read-only property)
  8987. }
  8988. }
  8989. };
  8990. Tools.IsEmpty = function (obj) {
  8991. for (var i in obj) {
  8992. if (obj.hasOwnProperty(i)) {
  8993. return false;
  8994. }
  8995. }
  8996. return true;
  8997. };
  8998. Tools.RegisterTopRootEvents = function (events) {
  8999. for (var index = 0; index < events.length; index++) {
  9000. var event = events[index];
  9001. window.addEventListener(event.name, event.handler, false);
  9002. try {
  9003. if (window.parent) {
  9004. window.parent.addEventListener(event.name, event.handler, false);
  9005. }
  9006. }
  9007. catch (e) {
  9008. // Silently fails...
  9009. }
  9010. }
  9011. };
  9012. Tools.UnregisterTopRootEvents = function (events) {
  9013. for (var index = 0; index < events.length; index++) {
  9014. var event = events[index];
  9015. window.removeEventListener(event.name, event.handler);
  9016. try {
  9017. if (window.parent) {
  9018. window.parent.removeEventListener(event.name, event.handler);
  9019. }
  9020. }
  9021. catch (e) {
  9022. // Silently fails...
  9023. }
  9024. }
  9025. };
  9026. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9027. if (mimeType === void 0) { mimeType = "image/png"; }
  9028. // Read the contents of the framebuffer
  9029. var numberOfChannelsByLine = width * 4;
  9030. var halfHeight = height / 2;
  9031. //Reading datas from WebGL
  9032. var data = engine.readPixels(0, 0, width, height);
  9033. //To flip image on Y axis.
  9034. for (var i = 0; i < halfHeight; i++) {
  9035. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9036. var currentCell = j + i * numberOfChannelsByLine;
  9037. var targetLine = height - i - 1;
  9038. var targetCell = j + targetLine * numberOfChannelsByLine;
  9039. var temp = data[currentCell];
  9040. data[currentCell] = data[targetCell];
  9041. data[targetCell] = temp;
  9042. }
  9043. }
  9044. // Create a 2D canvas to store the result
  9045. if (!screenshotCanvas) {
  9046. screenshotCanvas = document.createElement('canvas');
  9047. }
  9048. screenshotCanvas.width = width;
  9049. screenshotCanvas.height = height;
  9050. var context = screenshotCanvas.getContext('2d');
  9051. if (context) {
  9052. // Copy the pixels to a 2D canvas
  9053. var imageData = context.createImageData(width, height);
  9054. var castData = (imageData.data);
  9055. castData.set(data);
  9056. context.putImageData(imageData, 0, 0);
  9057. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9058. }
  9059. };
  9060. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9061. if (mimeType === void 0) { mimeType = "image/png"; }
  9062. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9063. if (successCallback) {
  9064. successCallback(base64Image);
  9065. }
  9066. else {
  9067. // We need HTMLCanvasElement.toBlob for HD screenshots
  9068. if (!screenshotCanvas.toBlob) {
  9069. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9070. screenshotCanvas.toBlob = function (callback, type, quality) {
  9071. var _this = this;
  9072. setTimeout(function () {
  9073. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9074. for (var i = 0; i < len; i++) {
  9075. arr[i] = binStr.charCodeAt(i);
  9076. }
  9077. callback(new Blob([arr], { type: type || 'image/png' }));
  9078. });
  9079. };
  9080. }
  9081. screenshotCanvas.toBlob(function (blob) {
  9082. var url = URL.createObjectURL(blob);
  9083. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9084. if (("download" in document.createElement("a"))) {
  9085. var a = window.document.createElement("a");
  9086. a.href = url;
  9087. if (fileName) {
  9088. a.setAttribute("download", fileName);
  9089. }
  9090. else {
  9091. var date = new Date();
  9092. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9093. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9094. }
  9095. window.document.body.appendChild(a);
  9096. a.addEventListener("click", function () {
  9097. if (a.parentElement) {
  9098. a.parentElement.removeChild(a);
  9099. }
  9100. });
  9101. a.click();
  9102. }
  9103. else {
  9104. var newWindow = window.open("");
  9105. if (!newWindow)
  9106. return;
  9107. var img = newWindow.document.createElement("img");
  9108. img.onload = function () {
  9109. // no longer need to read the blob so it's revoked
  9110. URL.revokeObjectURL(url);
  9111. };
  9112. img.src = url;
  9113. newWindow.document.body.appendChild(img);
  9114. }
  9115. });
  9116. }
  9117. };
  9118. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9119. if (mimeType === void 0) { mimeType = "image/png"; }
  9120. var width;
  9121. var height;
  9122. // If a precision value is specified
  9123. if (size.precision) {
  9124. width = Math.round(engine.getRenderWidth() * size.precision);
  9125. height = Math.round(width / engine.getAspectRatio(camera));
  9126. }
  9127. else if (size.width && size.height) {
  9128. width = size.width;
  9129. height = size.height;
  9130. }
  9131. //If passing only width, computing height to keep display canvas ratio.
  9132. else if (size.width && !size.height) {
  9133. width = size.width;
  9134. height = Math.round(width / engine.getAspectRatio(camera));
  9135. }
  9136. //If passing only height, computing width to keep display canvas ratio.
  9137. else if (size.height && !size.width) {
  9138. height = size.height;
  9139. width = Math.round(height * engine.getAspectRatio(camera));
  9140. }
  9141. //Assuming here that "size" parameter is a number
  9142. else if (!isNaN(size)) {
  9143. height = size;
  9144. width = size;
  9145. }
  9146. else {
  9147. Tools.Error("Invalid 'size' parameter !");
  9148. return;
  9149. }
  9150. if (!screenshotCanvas) {
  9151. screenshotCanvas = document.createElement('canvas');
  9152. }
  9153. screenshotCanvas.width = width;
  9154. screenshotCanvas.height = height;
  9155. var renderContext = screenshotCanvas.getContext("2d");
  9156. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9157. var newWidth = width;
  9158. var newHeight = newWidth / ratio;
  9159. if (newHeight > height) {
  9160. newHeight = height;
  9161. newWidth = newHeight * ratio;
  9162. }
  9163. var offsetX = Math.max(0, width - newWidth) / 2;
  9164. var offsetY = Math.max(0, height - newHeight) / 2;
  9165. var renderingCanvas = engine.getRenderingCanvas();
  9166. if (renderContext && renderingCanvas) {
  9167. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9168. }
  9169. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9170. };
  9171. /**
  9172. * Generates an image screenshot from the specified camera.
  9173. *
  9174. * @param engine The engine to use for rendering
  9175. * @param camera The camera to use for rendering
  9176. * @param size This parameter can be set to a single number or to an object with the
  9177. * following (optional) properties: precision, width, height. If a single number is passed,
  9178. * it will be used for both width and height. If an object is passed, the screenshot size
  9179. * will be derived from the parameters. The precision property is a multiplier allowing
  9180. * rendering at a higher or lower resolution.
  9181. * @param successCallback The callback receives a single parameter which contains the
  9182. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9183. * src parameter of an <img> to display it.
  9184. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9185. * Check your browser for supported MIME types.
  9186. * @param samples Texture samples (default: 1)
  9187. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9188. * @param fileName A name for for the downloaded file.
  9189. * @constructor
  9190. */
  9191. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9192. if (mimeType === void 0) { mimeType = "image/png"; }
  9193. if (samples === void 0) { samples = 1; }
  9194. if (antialiasing === void 0) { antialiasing = false; }
  9195. var width;
  9196. var height;
  9197. //If a precision value is specified
  9198. if (size.precision) {
  9199. width = Math.round(engine.getRenderWidth() * size.precision);
  9200. height = Math.round(width / engine.getAspectRatio(camera));
  9201. size = { width: width, height: height };
  9202. }
  9203. else if (size.width && size.height) {
  9204. width = size.width;
  9205. height = size.height;
  9206. }
  9207. //If passing only width, computing height to keep display canvas ratio.
  9208. else if (size.width && !size.height) {
  9209. width = size.width;
  9210. height = Math.round(width / engine.getAspectRatio(camera));
  9211. size = { width: width, height: height };
  9212. }
  9213. //If passing only height, computing width to keep display canvas ratio.
  9214. else if (size.height && !size.width) {
  9215. height = size.height;
  9216. width = Math.round(height * engine.getAspectRatio(camera));
  9217. size = { width: width, height: height };
  9218. }
  9219. //Assuming here that "size" parameter is a number
  9220. else if (!isNaN(size)) {
  9221. height = size;
  9222. width = size;
  9223. }
  9224. else {
  9225. Tools.Error("Invalid 'size' parameter !");
  9226. return;
  9227. }
  9228. var scene = camera.getScene();
  9229. var previousCamera = null;
  9230. if (scene.activeCamera !== camera) {
  9231. previousCamera = scene.activeCamera;
  9232. scene.activeCamera = camera;
  9233. }
  9234. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9235. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9236. texture.renderList = null;
  9237. texture.samples = samples;
  9238. if (antialiasing) {
  9239. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9240. }
  9241. texture.onAfterRenderObservable.add(function () {
  9242. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9243. });
  9244. scene.incrementRenderId();
  9245. scene.resetCachedMaterial();
  9246. texture.render(true);
  9247. texture.dispose();
  9248. if (previousCamera) {
  9249. scene.activeCamera = previousCamera;
  9250. }
  9251. camera.getProjectionMatrix(true); // Force cache refresh;
  9252. };
  9253. // XHR response validator for local file scenario
  9254. Tools.ValidateXHRData = function (xhr, dataType) {
  9255. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9256. if (dataType === void 0) { dataType = 7; }
  9257. try {
  9258. if (dataType & 1) {
  9259. if (xhr.responseText && xhr.responseText.length > 0) {
  9260. return true;
  9261. }
  9262. else if (dataType === 1) {
  9263. return false;
  9264. }
  9265. }
  9266. if (dataType & 2) {
  9267. // Check header width and height since there is no "TGA" magic number
  9268. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9269. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9270. return true;
  9271. }
  9272. else if (dataType === 2) {
  9273. return false;
  9274. }
  9275. }
  9276. if (dataType & 4) {
  9277. // Check for the "DDS" magic number
  9278. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9279. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9280. return true;
  9281. }
  9282. else {
  9283. return false;
  9284. }
  9285. }
  9286. }
  9287. catch (e) {
  9288. // Global protection
  9289. }
  9290. return false;
  9291. };
  9292. /**
  9293. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9294. * Be aware Math.random() could cause collisions, but:
  9295. * "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"
  9296. */
  9297. Tools.RandomId = function () {
  9298. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9299. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9300. return v.toString(16);
  9301. });
  9302. };
  9303. /**
  9304. * Test if the given uri is a base64 string.
  9305. * @param uri The uri to test
  9306. * @return True if the uri is a base64 string or false otherwise.
  9307. */
  9308. Tools.IsBase64 = function (uri) {
  9309. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9310. };
  9311. /**
  9312. * Decode the given base64 uri.
  9313. * @param uri The uri to decode
  9314. * @return The decoded base64 data.
  9315. */
  9316. Tools.DecodeBase64 = function (uri) {
  9317. var decodedString = atob(uri.split(",")[1]);
  9318. var bufferLength = decodedString.length;
  9319. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9320. for (var i = 0; i < bufferLength; i++) {
  9321. bufferView[i] = decodedString.charCodeAt(i);
  9322. }
  9323. return bufferView.buffer;
  9324. };
  9325. Object.defineProperty(Tools, "NoneLogLevel", {
  9326. get: function () {
  9327. return Tools._NoneLogLevel;
  9328. },
  9329. enumerable: true,
  9330. configurable: true
  9331. });
  9332. Object.defineProperty(Tools, "MessageLogLevel", {
  9333. get: function () {
  9334. return Tools._MessageLogLevel;
  9335. },
  9336. enumerable: true,
  9337. configurable: true
  9338. });
  9339. Object.defineProperty(Tools, "WarningLogLevel", {
  9340. get: function () {
  9341. return Tools._WarningLogLevel;
  9342. },
  9343. enumerable: true,
  9344. configurable: true
  9345. });
  9346. Object.defineProperty(Tools, "ErrorLogLevel", {
  9347. get: function () {
  9348. return Tools._ErrorLogLevel;
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(Tools, "AllLogLevel", {
  9354. get: function () {
  9355. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. Tools._AddLogEntry = function (entry) {
  9361. Tools._LogCache = entry + Tools._LogCache;
  9362. if (Tools.OnNewCacheEntry) {
  9363. Tools.OnNewCacheEntry(entry);
  9364. }
  9365. };
  9366. Tools._FormatMessage = function (message) {
  9367. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9368. var date = new Date();
  9369. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9370. };
  9371. Tools._LogDisabled = function (message) {
  9372. // nothing to do
  9373. };
  9374. Tools._LogEnabled = function (message) {
  9375. var formattedMessage = Tools._FormatMessage(message);
  9376. console.log("BJS - " + formattedMessage);
  9377. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9378. Tools._AddLogEntry(entry);
  9379. };
  9380. Tools._WarnDisabled = function (message) {
  9381. // nothing to do
  9382. };
  9383. Tools._WarnEnabled = function (message) {
  9384. var formattedMessage = Tools._FormatMessage(message);
  9385. console.warn("BJS - " + formattedMessage);
  9386. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9387. Tools._AddLogEntry(entry);
  9388. };
  9389. Tools._ErrorDisabled = function (message) {
  9390. // nothing to do
  9391. };
  9392. Tools._ErrorEnabled = function (message) {
  9393. Tools.errorsCount++;
  9394. var formattedMessage = Tools._FormatMessage(message);
  9395. console.error("BJS - " + formattedMessage);
  9396. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9397. Tools._AddLogEntry(entry);
  9398. };
  9399. Object.defineProperty(Tools, "LogCache", {
  9400. get: function () {
  9401. return Tools._LogCache;
  9402. },
  9403. enumerable: true,
  9404. configurable: true
  9405. });
  9406. Tools.ClearLogCache = function () {
  9407. Tools._LogCache = "";
  9408. Tools.errorsCount = 0;
  9409. };
  9410. Object.defineProperty(Tools, "LogLevels", {
  9411. set: function (level) {
  9412. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9413. Tools.Log = Tools._LogEnabled;
  9414. }
  9415. else {
  9416. Tools.Log = Tools._LogDisabled;
  9417. }
  9418. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9419. Tools.Warn = Tools._WarnEnabled;
  9420. }
  9421. else {
  9422. Tools.Warn = Tools._WarnDisabled;
  9423. }
  9424. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9425. Tools.Error = Tools._ErrorEnabled;
  9426. }
  9427. else {
  9428. Tools.Error = Tools._ErrorDisabled;
  9429. }
  9430. },
  9431. enumerable: true,
  9432. configurable: true
  9433. });
  9434. Tools.IsWindowObjectExist = function () {
  9435. return (typeof window) !== "undefined";
  9436. };
  9437. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9438. get: function () {
  9439. return Tools._PerformanceNoneLogLevel;
  9440. },
  9441. enumerable: true,
  9442. configurable: true
  9443. });
  9444. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9445. get: function () {
  9446. return Tools._PerformanceUserMarkLogLevel;
  9447. },
  9448. enumerable: true,
  9449. configurable: true
  9450. });
  9451. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9452. get: function () {
  9453. return Tools._PerformanceConsoleLogLevel;
  9454. },
  9455. enumerable: true,
  9456. configurable: true
  9457. });
  9458. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9459. set: function (level) {
  9460. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9461. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9462. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9463. return;
  9464. }
  9465. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9466. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9467. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9468. return;
  9469. }
  9470. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9471. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9472. },
  9473. enumerable: true,
  9474. configurable: true
  9475. });
  9476. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9477. };
  9478. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9479. };
  9480. Tools._StartUserMark = function (counterName, condition) {
  9481. if (condition === void 0) { condition = true; }
  9482. if (!Tools._performance) {
  9483. if (!Tools.IsWindowObjectExist()) {
  9484. return;
  9485. }
  9486. Tools._performance = window.performance;
  9487. }
  9488. if (!condition || !Tools._performance.mark) {
  9489. return;
  9490. }
  9491. Tools._performance.mark(counterName + "-Begin");
  9492. };
  9493. Tools._EndUserMark = function (counterName, condition) {
  9494. if (condition === void 0) { condition = true; }
  9495. if (!condition || !Tools._performance.mark) {
  9496. return;
  9497. }
  9498. Tools._performance.mark(counterName + "-End");
  9499. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9500. };
  9501. Tools._StartPerformanceConsole = function (counterName, condition) {
  9502. if (condition === void 0) { condition = true; }
  9503. if (!condition) {
  9504. return;
  9505. }
  9506. Tools._StartUserMark(counterName, condition);
  9507. if (console.time) {
  9508. console.time(counterName);
  9509. }
  9510. };
  9511. Tools._EndPerformanceConsole = function (counterName, condition) {
  9512. if (condition === void 0) { condition = true; }
  9513. if (!condition) {
  9514. return;
  9515. }
  9516. Tools._EndUserMark(counterName, condition);
  9517. if (console.time) {
  9518. console.timeEnd(counterName);
  9519. }
  9520. };
  9521. Object.defineProperty(Tools, "Now", {
  9522. get: function () {
  9523. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9524. return window.performance.now();
  9525. }
  9526. return Date.now();
  9527. },
  9528. enumerable: true,
  9529. configurable: true
  9530. });
  9531. /**
  9532. * This method will return the name of the class used to create the instance of the given object.
  9533. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9534. * @param object the object to get the class name from
  9535. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9536. */
  9537. Tools.GetClassName = function (object, isType) {
  9538. if (isType === void 0) { isType = false; }
  9539. var name = null;
  9540. if (!isType && object.getClassName) {
  9541. name = object.getClassName();
  9542. }
  9543. else {
  9544. if (object instanceof Object) {
  9545. var classObj = isType ? object : Object.getPrototypeOf(object);
  9546. name = classObj.constructor["__bjsclassName__"];
  9547. }
  9548. if (!name) {
  9549. name = typeof object;
  9550. }
  9551. }
  9552. return name;
  9553. };
  9554. Tools.First = function (array, predicate) {
  9555. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9556. var el = array_1[_i];
  9557. if (predicate(el)) {
  9558. return el;
  9559. }
  9560. }
  9561. return null;
  9562. };
  9563. /**
  9564. * This method will return the name of the full name of the class, including its owning module (if any).
  9565. * 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).
  9566. * @param object the object to get the class name from
  9567. * @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.
  9568. */
  9569. Tools.getFullClassName = function (object, isType) {
  9570. if (isType === void 0) { isType = false; }
  9571. var className = null;
  9572. var moduleName = null;
  9573. if (!isType && object.getClassName) {
  9574. className = object.getClassName();
  9575. }
  9576. else {
  9577. if (object instanceof Object) {
  9578. var classObj = isType ? object : Object.getPrototypeOf(object);
  9579. className = classObj.constructor["__bjsclassName__"];
  9580. moduleName = classObj.constructor["__bjsmoduleName__"];
  9581. }
  9582. if (!className) {
  9583. className = typeof object;
  9584. }
  9585. }
  9586. if (!className) {
  9587. return null;
  9588. }
  9589. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9590. };
  9591. /**
  9592. * 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.
  9593. * @param array
  9594. */
  9595. Tools.arrayOrStringFeeder = function (array) {
  9596. return function (index) {
  9597. if (index >= array.length) {
  9598. return null;
  9599. }
  9600. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9601. if (val && val.getHashCode) {
  9602. val = val.getHashCode();
  9603. }
  9604. if (typeof val === "string") {
  9605. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9606. }
  9607. return val;
  9608. };
  9609. };
  9610. /**
  9611. * Compute the hashCode of a stream of number
  9612. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9613. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9614. * @return the hash code computed
  9615. */
  9616. Tools.hashCodeFromStream = function (feeder) {
  9617. // Based from here: http://stackoverflow.com/a/7616484/802124
  9618. var hash = 0;
  9619. var index = 0;
  9620. var chr = feeder(index++);
  9621. while (chr != null) {
  9622. hash = ((hash << 5) - hash) + chr;
  9623. hash |= 0; // Convert to 32bit integer
  9624. chr = feeder(index++);
  9625. }
  9626. return hash;
  9627. };
  9628. /**
  9629. * Returns a promise that resolves after the given amount of time.
  9630. * @param delay Number of milliseconds to delay
  9631. * @returns Promise that resolves after the given amount of time
  9632. */
  9633. Tools.DelayAsync = function (delay) {
  9634. return new Promise(function (resolve) {
  9635. setTimeout(function () {
  9636. resolve();
  9637. }, delay);
  9638. });
  9639. };
  9640. Tools.BaseUrl = "";
  9641. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9642. /**
  9643. * Default behaviour for cors in the application.
  9644. * It can be a string if the expected behavior is identical in the entire app.
  9645. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9646. */
  9647. Tools.CorsBehavior = "anonymous";
  9648. Tools.UseFallbackTexture = true;
  9649. /**
  9650. * Use this object to register external classes like custom textures or material
  9651. * to allow the laoders to instantiate them
  9652. */
  9653. Tools.RegisteredExternalClasses = {};
  9654. // Used in case of a texture loading problem
  9655. 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";
  9656. Tools.PreprocessUrl = function (url) {
  9657. return url;
  9658. };
  9659. // Logs
  9660. Tools._NoneLogLevel = 0;
  9661. Tools._MessageLogLevel = 1;
  9662. Tools._WarningLogLevel = 2;
  9663. Tools._ErrorLogLevel = 4;
  9664. Tools._LogCache = "";
  9665. Tools.errorsCount = 0;
  9666. Tools.Log = Tools._LogEnabled;
  9667. Tools.Warn = Tools._WarnEnabled;
  9668. Tools.Error = Tools._ErrorEnabled;
  9669. // Performances
  9670. Tools._PerformanceNoneLogLevel = 0;
  9671. Tools._PerformanceUserMarkLogLevel = 1;
  9672. Tools._PerformanceConsoleLogLevel = 2;
  9673. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9674. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9675. return Tools;
  9676. }());
  9677. BABYLON.Tools = Tools;
  9678. /**
  9679. * This class is used to track a performance counter which is number based.
  9680. * The user has access to many properties which give statistics of different nature
  9681. *
  9682. * The implementer can track two kinds of Performance Counter: time and count
  9683. * 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.
  9684. * 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.
  9685. */
  9686. var PerfCounter = /** @class */ (function () {
  9687. function PerfCounter() {
  9688. this._startMonitoringTime = 0;
  9689. this._min = 0;
  9690. this._max = 0;
  9691. this._average = 0;
  9692. this._lastSecAverage = 0;
  9693. this._current = 0;
  9694. this._totalValueCount = 0;
  9695. this._totalAccumulated = 0;
  9696. this._lastSecAccumulated = 0;
  9697. this._lastSecTime = 0;
  9698. this._lastSecValueCount = 0;
  9699. }
  9700. Object.defineProperty(PerfCounter.prototype, "min", {
  9701. /**
  9702. * Returns the smallest value ever
  9703. */
  9704. get: function () {
  9705. return this._min;
  9706. },
  9707. enumerable: true,
  9708. configurable: true
  9709. });
  9710. Object.defineProperty(PerfCounter.prototype, "max", {
  9711. /**
  9712. * Returns the biggest value ever
  9713. */
  9714. get: function () {
  9715. return this._max;
  9716. },
  9717. enumerable: true,
  9718. configurable: true
  9719. });
  9720. Object.defineProperty(PerfCounter.prototype, "average", {
  9721. /**
  9722. * Returns the average value since the performance counter is running
  9723. */
  9724. get: function () {
  9725. return this._average;
  9726. },
  9727. enumerable: true,
  9728. configurable: true
  9729. });
  9730. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9731. /**
  9732. * Returns the average value of the last second the counter was monitored
  9733. */
  9734. get: function () {
  9735. return this._lastSecAverage;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Object.defineProperty(PerfCounter.prototype, "current", {
  9741. /**
  9742. * Returns the current value
  9743. */
  9744. get: function () {
  9745. return this._current;
  9746. },
  9747. enumerable: true,
  9748. configurable: true
  9749. });
  9750. Object.defineProperty(PerfCounter.prototype, "total", {
  9751. get: function () {
  9752. return this._totalAccumulated;
  9753. },
  9754. enumerable: true,
  9755. configurable: true
  9756. });
  9757. Object.defineProperty(PerfCounter.prototype, "count", {
  9758. get: function () {
  9759. return this._totalValueCount;
  9760. },
  9761. enumerable: true,
  9762. configurable: true
  9763. });
  9764. /**
  9765. * Call this method to start monitoring a new frame.
  9766. * 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.
  9767. */
  9768. PerfCounter.prototype.fetchNewFrame = function () {
  9769. this._totalValueCount++;
  9770. this._current = 0;
  9771. this._lastSecValueCount++;
  9772. };
  9773. /**
  9774. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9775. * @param newCount the count value to add to the monitored count
  9776. * @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.
  9777. */
  9778. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9779. if (!PerfCounter.Enabled) {
  9780. return;
  9781. }
  9782. this._current += newCount;
  9783. if (fetchResult) {
  9784. this._fetchResult();
  9785. }
  9786. };
  9787. /**
  9788. * Start monitoring this performance counter
  9789. */
  9790. PerfCounter.prototype.beginMonitoring = function () {
  9791. if (!PerfCounter.Enabled) {
  9792. return;
  9793. }
  9794. this._startMonitoringTime = Tools.Now;
  9795. };
  9796. /**
  9797. * Compute the time lapsed since the previous beginMonitoring() call.
  9798. * @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
  9799. */
  9800. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9801. if (newFrame === void 0) { newFrame = true; }
  9802. if (!PerfCounter.Enabled) {
  9803. return;
  9804. }
  9805. if (newFrame) {
  9806. this.fetchNewFrame();
  9807. }
  9808. var currentTime = Tools.Now;
  9809. this._current = currentTime - this._startMonitoringTime;
  9810. if (newFrame) {
  9811. this._fetchResult();
  9812. }
  9813. };
  9814. PerfCounter.prototype._fetchResult = function () {
  9815. this._totalAccumulated += this._current;
  9816. this._lastSecAccumulated += this._current;
  9817. // Min/Max update
  9818. this._min = Math.min(this._min, this._current);
  9819. this._max = Math.max(this._max, this._current);
  9820. this._average = this._totalAccumulated / this._totalValueCount;
  9821. // Reset last sec?
  9822. var now = Tools.Now;
  9823. if ((now - this._lastSecTime) > 1000) {
  9824. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9825. this._lastSecTime = now;
  9826. this._lastSecAccumulated = 0;
  9827. this._lastSecValueCount = 0;
  9828. }
  9829. };
  9830. PerfCounter.Enabled = true;
  9831. return PerfCounter;
  9832. }());
  9833. BABYLON.PerfCounter = PerfCounter;
  9834. /**
  9835. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9836. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9837. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9838. * @param name The name of the class, case should be preserved
  9839. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9840. */
  9841. function className(name, module) {
  9842. return function (target) {
  9843. target["__bjsclassName__"] = name;
  9844. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9845. };
  9846. }
  9847. BABYLON.className = className;
  9848. /**
  9849. * An implementation of a loop for asynchronous functions.
  9850. */
  9851. var AsyncLoop = /** @class */ (function () {
  9852. /**
  9853. * Constroctor.
  9854. * @param iterations the number of iterations.
  9855. * @param _fn the function to run each iteration
  9856. * @param _successCallback the callback that will be called upon succesful execution
  9857. * @param offset starting offset.
  9858. */
  9859. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9860. if (offset === void 0) { offset = 0; }
  9861. this.iterations = iterations;
  9862. this._fn = _fn;
  9863. this._successCallback = _successCallback;
  9864. this.index = offset - 1;
  9865. this._done = false;
  9866. }
  9867. /**
  9868. * Execute the next iteration. Must be called after the last iteration was finished.
  9869. */
  9870. AsyncLoop.prototype.executeNext = function () {
  9871. if (!this._done) {
  9872. if (this.index + 1 < this.iterations) {
  9873. ++this.index;
  9874. this._fn(this);
  9875. }
  9876. else {
  9877. this.breakLoop();
  9878. }
  9879. }
  9880. };
  9881. /**
  9882. * Break the loop and run the success callback.
  9883. */
  9884. AsyncLoop.prototype.breakLoop = function () {
  9885. this._done = true;
  9886. this._successCallback();
  9887. };
  9888. /**
  9889. * Helper function
  9890. */
  9891. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9892. if (offset === void 0) { offset = 0; }
  9893. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9894. loop.executeNext();
  9895. return loop;
  9896. };
  9897. /**
  9898. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9899. * @param iterations total number of iterations
  9900. * @param syncedIterations number of synchronous iterations in each async iteration.
  9901. * @param fn the function to call each iteration.
  9902. * @param callback a success call back that will be called when iterating stops.
  9903. * @param breakFunction a break condition (optional)
  9904. * @param timeout timeout settings for the setTimeout function. default - 0.
  9905. * @constructor
  9906. */
  9907. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9908. if (timeout === void 0) { timeout = 0; }
  9909. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9910. if (breakFunction && breakFunction())
  9911. loop.breakLoop();
  9912. else {
  9913. setTimeout(function () {
  9914. for (var i = 0; i < syncedIterations; ++i) {
  9915. var iteration = (loop.index * syncedIterations) + i;
  9916. if (iteration >= iterations)
  9917. break;
  9918. fn(iteration);
  9919. if (breakFunction && breakFunction()) {
  9920. loop.breakLoop();
  9921. break;
  9922. }
  9923. }
  9924. loop.executeNext();
  9925. }, timeout);
  9926. }
  9927. }, callback);
  9928. };
  9929. return AsyncLoop;
  9930. }());
  9931. BABYLON.AsyncLoop = AsyncLoop;
  9932. })(BABYLON || (BABYLON = {}));
  9933. //# sourceMappingURL=babylon.tools.js.map
  9934. var BABYLON;
  9935. (function (BABYLON) {
  9936. var PromiseStates;
  9937. (function (PromiseStates) {
  9938. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9939. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9940. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9941. })(PromiseStates || (PromiseStates = {}));
  9942. var FulFillmentAgregator = /** @class */ (function () {
  9943. function FulFillmentAgregator() {
  9944. this.count = 0;
  9945. this.target = 0;
  9946. this.results = [];
  9947. }
  9948. return FulFillmentAgregator;
  9949. }());
  9950. var InternalPromise = /** @class */ (function () {
  9951. function InternalPromise(resolver) {
  9952. var _this = this;
  9953. this._state = PromiseStates.Pending;
  9954. this._children = new Array();
  9955. this._rejectWasConsumed = false;
  9956. if (!resolver) {
  9957. return;
  9958. }
  9959. try {
  9960. resolver(function (value) {
  9961. _this._resolve(value);
  9962. }, function (reason) {
  9963. _this._reject(reason);
  9964. });
  9965. }
  9966. catch (e) {
  9967. this._reject(e);
  9968. }
  9969. }
  9970. InternalPromise.prototype.catch = function (onRejected) {
  9971. return this.then(undefined, onRejected);
  9972. };
  9973. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9974. var _this = this;
  9975. var newPromise = new InternalPromise();
  9976. newPromise._onFulfilled = onFulfilled;
  9977. newPromise._onRejected = onRejected;
  9978. // Composition
  9979. this._children.push(newPromise);
  9980. if (this._state !== PromiseStates.Pending) {
  9981. BABYLON.Tools.SetImmediate(function () {
  9982. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9983. var returnedValue = newPromise._resolve(_this._result);
  9984. if (returnedValue !== undefined && returnedValue !== null) {
  9985. if (returnedValue._state !== undefined) {
  9986. var returnedPromise = returnedValue;
  9987. newPromise._children.push(returnedPromise);
  9988. newPromise = returnedPromise;
  9989. }
  9990. else {
  9991. newPromise._result = returnedValue;
  9992. }
  9993. }
  9994. }
  9995. else {
  9996. newPromise._reject(_this._reason);
  9997. }
  9998. });
  9999. }
  10000. return newPromise;
  10001. };
  10002. InternalPromise.prototype._moveChildren = function (children) {
  10003. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10004. if (this._state === PromiseStates.Fulfilled) {
  10005. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10006. var child = _b[_i];
  10007. child._resolve(this._result);
  10008. }
  10009. }
  10010. else if (this._state === PromiseStates.Rejected) {
  10011. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10012. var child = _d[_c];
  10013. child._reject(this._reason);
  10014. }
  10015. }
  10016. var _a;
  10017. };
  10018. InternalPromise.prototype._resolve = function (value) {
  10019. try {
  10020. this._state = PromiseStates.Fulfilled;
  10021. var returnedValue = null;
  10022. if (this._onFulfilled) {
  10023. returnedValue = this._onFulfilled(value);
  10024. }
  10025. if (returnedValue !== undefined && returnedValue !== null) {
  10026. if (returnedValue._state !== undefined) {
  10027. // Transmit children
  10028. var returnedPromise = returnedValue;
  10029. returnedPromise._moveChildren(this._children);
  10030. value = returnedPromise._result;
  10031. }
  10032. else {
  10033. value = returnedValue;
  10034. }
  10035. }
  10036. this._result = value;
  10037. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10038. var child = _a[_i];
  10039. child._resolve(value);
  10040. }
  10041. this._children.length = 0;
  10042. delete this._onFulfilled;
  10043. delete this._onRejected;
  10044. }
  10045. catch (e) {
  10046. this._reject(e, true);
  10047. }
  10048. };
  10049. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10050. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10051. this._state = PromiseStates.Rejected;
  10052. this._reason = reason;
  10053. if (this._onRejected && !onLocalThrow) {
  10054. try {
  10055. this._onRejected(reason);
  10056. this._rejectWasConsumed = true;
  10057. }
  10058. catch (e) {
  10059. reason = e;
  10060. }
  10061. }
  10062. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10063. var child = _a[_i];
  10064. if (this._rejectWasConsumed) {
  10065. child._resolve(null);
  10066. }
  10067. else {
  10068. child._reject(reason);
  10069. }
  10070. }
  10071. this._children.length = 0;
  10072. delete this._onFulfilled;
  10073. delete this._onRejected;
  10074. };
  10075. InternalPromise.resolve = function (value) {
  10076. var newPromise = new InternalPromise();
  10077. newPromise._resolve(value);
  10078. return newPromise;
  10079. };
  10080. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10081. promise.then(function (value) {
  10082. agregator.results[index] = value;
  10083. agregator.count++;
  10084. if (agregator.count === agregator.target) {
  10085. agregator.rootPromise._resolve(agregator.results);
  10086. }
  10087. return null;
  10088. }, function (reason) {
  10089. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10090. agregator.rootPromise._reject(reason);
  10091. }
  10092. });
  10093. };
  10094. InternalPromise.all = function (promises) {
  10095. var newPromise = new InternalPromise();
  10096. var agregator = new FulFillmentAgregator();
  10097. agregator.target = promises.length;
  10098. agregator.rootPromise = newPromise;
  10099. if (promises.length) {
  10100. for (var index = 0; index < promises.length; index++) {
  10101. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10102. }
  10103. }
  10104. else {
  10105. newPromise._resolve([]);
  10106. }
  10107. return newPromise;
  10108. };
  10109. InternalPromise.race = function (promises) {
  10110. var newPromise = new InternalPromise();
  10111. if (promises.length) {
  10112. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10113. var promise = promises_1[_i];
  10114. promise.then(function (value) {
  10115. if (newPromise) {
  10116. newPromise._resolve(value);
  10117. newPromise = null;
  10118. }
  10119. return null;
  10120. }, function (reason) {
  10121. if (newPromise) {
  10122. newPromise._reject(reason);
  10123. newPromise = null;
  10124. }
  10125. });
  10126. }
  10127. }
  10128. return newPromise;
  10129. };
  10130. return InternalPromise;
  10131. }());
  10132. /**
  10133. * Helper class that provides a small promise polyfill
  10134. */
  10135. var PromisePolyfill = /** @class */ (function () {
  10136. function PromisePolyfill() {
  10137. }
  10138. /**
  10139. * Static function used to check if the polyfill is required
  10140. * If this is the case then the function will inject the polyfill to window.Promise
  10141. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10142. */
  10143. PromisePolyfill.Apply = function (force) {
  10144. if (force === void 0) { force = false; }
  10145. if (force || typeof Promise === 'undefined') {
  10146. var root = window;
  10147. root.Promise = InternalPromise;
  10148. }
  10149. };
  10150. return PromisePolyfill;
  10151. }());
  10152. BABYLON.PromisePolyfill = PromisePolyfill;
  10153. })(BABYLON || (BABYLON = {}));
  10154. //# sourceMappingURL=babylon.promise.js.map
  10155. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10156. var BABYLON;
  10157. (function (BABYLON) {
  10158. /**
  10159. * Helper class to push actions to a pool of workers.
  10160. */
  10161. var WorkerPool = /** @class */ (function () {
  10162. /**
  10163. * Constructor
  10164. * @param workers Array of workers to use for actions
  10165. */
  10166. function WorkerPool(workers) {
  10167. this._pendingActions = new Array();
  10168. this._workerInfos = workers.map(function (worker) { return ({
  10169. worker: worker,
  10170. active: false
  10171. }); });
  10172. }
  10173. /**
  10174. * Terminates all workers and clears any pending actions.
  10175. */
  10176. WorkerPool.prototype.dispose = function () {
  10177. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10178. var workerInfo = _a[_i];
  10179. workerInfo.worker.terminate();
  10180. }
  10181. delete this._workerInfos;
  10182. delete this._pendingActions;
  10183. };
  10184. /**
  10185. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10186. * pended until a worker has completed its action.
  10187. * @param action The action to perform. Call onComplete when the action is complete.
  10188. */
  10189. WorkerPool.prototype.push = function (action) {
  10190. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10191. var workerInfo = _a[_i];
  10192. if (!workerInfo.active) {
  10193. this._execute(workerInfo, action);
  10194. return;
  10195. }
  10196. }
  10197. this._pendingActions.push(action);
  10198. };
  10199. WorkerPool.prototype._execute = function (workerInfo, action) {
  10200. var _this = this;
  10201. workerInfo.active = true;
  10202. action(workerInfo.worker, function () {
  10203. workerInfo.active = false;
  10204. var nextAction = _this._pendingActions.shift();
  10205. if (nextAction) {
  10206. _this._execute(workerInfo, nextAction);
  10207. }
  10208. });
  10209. };
  10210. return WorkerPool;
  10211. }());
  10212. BABYLON.WorkerPool = WorkerPool;
  10213. })(BABYLON || (BABYLON = {}));
  10214. //# sourceMappingURL=babylon.workerPool.js.map
  10215. var BABYLON;
  10216. (function (BABYLON) {
  10217. var _AlphaState = /** @class */ (function () {
  10218. /**
  10219. * Initializes the state.
  10220. */
  10221. function _AlphaState() {
  10222. this._isAlphaBlendDirty = false;
  10223. this._isBlendFunctionParametersDirty = false;
  10224. this._isBlendEquationParametersDirty = false;
  10225. this._isBlendConstantsDirty = false;
  10226. this._alphaBlend = false;
  10227. this._blendFunctionParameters = new Array(4);
  10228. this._blendEquationParameters = new Array(2);
  10229. this._blendConstants = new Array(4);
  10230. this.reset();
  10231. }
  10232. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10233. get: function () {
  10234. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10235. },
  10236. enumerable: true,
  10237. configurable: true
  10238. });
  10239. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10240. get: function () {
  10241. return this._alphaBlend;
  10242. },
  10243. set: function (value) {
  10244. if (this._alphaBlend === value) {
  10245. return;
  10246. }
  10247. this._alphaBlend = value;
  10248. this._isAlphaBlendDirty = true;
  10249. },
  10250. enumerable: true,
  10251. configurable: true
  10252. });
  10253. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10254. if (this._blendConstants[0] === r &&
  10255. this._blendConstants[1] === g &&
  10256. this._blendConstants[2] === b &&
  10257. this._blendConstants[3] === a) {
  10258. return;
  10259. }
  10260. this._blendConstants[0] = r;
  10261. this._blendConstants[1] = g;
  10262. this._blendConstants[2] = b;
  10263. this._blendConstants[3] = a;
  10264. this._isBlendConstantsDirty = true;
  10265. };
  10266. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10267. if (this._blendFunctionParameters[0] === value0 &&
  10268. this._blendFunctionParameters[1] === value1 &&
  10269. this._blendFunctionParameters[2] === value2 &&
  10270. this._blendFunctionParameters[3] === value3) {
  10271. return;
  10272. }
  10273. this._blendFunctionParameters[0] = value0;
  10274. this._blendFunctionParameters[1] = value1;
  10275. this._blendFunctionParameters[2] = value2;
  10276. this._blendFunctionParameters[3] = value3;
  10277. this._isBlendFunctionParametersDirty = true;
  10278. };
  10279. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10280. if (this._blendEquationParameters[0] === rgb &&
  10281. this._blendEquationParameters[1] === alpha) {
  10282. return;
  10283. }
  10284. this._blendEquationParameters[0] = rgb;
  10285. this._blendEquationParameters[1] = alpha;
  10286. this._isBlendEquationParametersDirty = true;
  10287. };
  10288. _AlphaState.prototype.reset = function () {
  10289. this._alphaBlend = false;
  10290. this._blendFunctionParameters[0] = null;
  10291. this._blendFunctionParameters[1] = null;
  10292. this._blendFunctionParameters[2] = null;
  10293. this._blendFunctionParameters[3] = null;
  10294. this._blendEquationParameters[0] = null;
  10295. this._blendEquationParameters[1] = null;
  10296. this._blendConstants[0] = null;
  10297. this._blendConstants[1] = null;
  10298. this._blendConstants[2] = null;
  10299. this._blendConstants[3] = null;
  10300. this._isAlphaBlendDirty = true;
  10301. this._isBlendFunctionParametersDirty = false;
  10302. this._isBlendEquationParametersDirty = false;
  10303. this._isBlendConstantsDirty = false;
  10304. };
  10305. _AlphaState.prototype.apply = function (gl) {
  10306. if (!this.isDirty) {
  10307. return;
  10308. }
  10309. // Alpha blend
  10310. if (this._isAlphaBlendDirty) {
  10311. if (this._alphaBlend) {
  10312. gl.enable(gl.BLEND);
  10313. }
  10314. else {
  10315. gl.disable(gl.BLEND);
  10316. }
  10317. this._isAlphaBlendDirty = false;
  10318. }
  10319. // Alpha function
  10320. if (this._isBlendFunctionParametersDirty) {
  10321. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10322. this._isBlendFunctionParametersDirty = false;
  10323. }
  10324. // Alpha equation
  10325. if (this._isBlendEquationParametersDirty) {
  10326. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10327. this._isBlendEquationParametersDirty = false;
  10328. }
  10329. // Constants
  10330. if (this._isBlendConstantsDirty) {
  10331. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10332. this._isBlendConstantsDirty = false;
  10333. }
  10334. };
  10335. return _AlphaState;
  10336. }());
  10337. BABYLON._AlphaState = _AlphaState;
  10338. })(BABYLON || (BABYLON = {}));
  10339. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10340. var BABYLON;
  10341. (function (BABYLON) {
  10342. var _DepthCullingState = /** @class */ (function () {
  10343. /**
  10344. * Initializes the state.
  10345. */
  10346. function _DepthCullingState() {
  10347. this._isDepthTestDirty = false;
  10348. this._isDepthMaskDirty = false;
  10349. this._isDepthFuncDirty = false;
  10350. this._isCullFaceDirty = false;
  10351. this._isCullDirty = false;
  10352. this._isZOffsetDirty = false;
  10353. this._isFrontFaceDirty = false;
  10354. this.reset();
  10355. }
  10356. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10357. get: function () {
  10358. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10359. },
  10360. enumerable: true,
  10361. configurable: true
  10362. });
  10363. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10364. get: function () {
  10365. return this._zOffset;
  10366. },
  10367. set: function (value) {
  10368. if (this._zOffset === value) {
  10369. return;
  10370. }
  10371. this._zOffset = value;
  10372. this._isZOffsetDirty = true;
  10373. },
  10374. enumerable: true,
  10375. configurable: true
  10376. });
  10377. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10378. get: function () {
  10379. return this._cullFace;
  10380. },
  10381. set: function (value) {
  10382. if (this._cullFace === value) {
  10383. return;
  10384. }
  10385. this._cullFace = value;
  10386. this._isCullFaceDirty = true;
  10387. },
  10388. enumerable: true,
  10389. configurable: true
  10390. });
  10391. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10392. get: function () {
  10393. return this._cull;
  10394. },
  10395. set: function (value) {
  10396. if (this._cull === value) {
  10397. return;
  10398. }
  10399. this._cull = value;
  10400. this._isCullDirty = true;
  10401. },
  10402. enumerable: true,
  10403. configurable: true
  10404. });
  10405. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10406. get: function () {
  10407. return this._depthFunc;
  10408. },
  10409. set: function (value) {
  10410. if (this._depthFunc === value) {
  10411. return;
  10412. }
  10413. this._depthFunc = value;
  10414. this._isDepthFuncDirty = true;
  10415. },
  10416. enumerable: true,
  10417. configurable: true
  10418. });
  10419. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10420. get: function () {
  10421. return this._depthMask;
  10422. },
  10423. set: function (value) {
  10424. if (this._depthMask === value) {
  10425. return;
  10426. }
  10427. this._depthMask = value;
  10428. this._isDepthMaskDirty = true;
  10429. },
  10430. enumerable: true,
  10431. configurable: true
  10432. });
  10433. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10434. get: function () {
  10435. return this._depthTest;
  10436. },
  10437. set: function (value) {
  10438. if (this._depthTest === value) {
  10439. return;
  10440. }
  10441. this._depthTest = value;
  10442. this._isDepthTestDirty = true;
  10443. },
  10444. enumerable: true,
  10445. configurable: true
  10446. });
  10447. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10448. get: function () {
  10449. return this._frontFace;
  10450. },
  10451. set: function (value) {
  10452. if (this._frontFace === value) {
  10453. return;
  10454. }
  10455. this._frontFace = value;
  10456. this._isFrontFaceDirty = true;
  10457. },
  10458. enumerable: true,
  10459. configurable: true
  10460. });
  10461. _DepthCullingState.prototype.reset = function () {
  10462. this._depthMask = true;
  10463. this._depthTest = true;
  10464. this._depthFunc = null;
  10465. this._cullFace = null;
  10466. this._cull = null;
  10467. this._zOffset = 0;
  10468. this._frontFace = null;
  10469. this._isDepthTestDirty = true;
  10470. this._isDepthMaskDirty = true;
  10471. this._isDepthFuncDirty = false;
  10472. this._isCullFaceDirty = false;
  10473. this._isCullDirty = false;
  10474. this._isZOffsetDirty = false;
  10475. this._isFrontFaceDirty = false;
  10476. };
  10477. _DepthCullingState.prototype.apply = function (gl) {
  10478. if (!this.isDirty) {
  10479. return;
  10480. }
  10481. // Cull
  10482. if (this._isCullDirty) {
  10483. if (this.cull) {
  10484. gl.enable(gl.CULL_FACE);
  10485. }
  10486. else {
  10487. gl.disable(gl.CULL_FACE);
  10488. }
  10489. this._isCullDirty = false;
  10490. }
  10491. // Cull face
  10492. if (this._isCullFaceDirty) {
  10493. gl.cullFace(this.cullFace);
  10494. this._isCullFaceDirty = false;
  10495. }
  10496. // Depth mask
  10497. if (this._isDepthMaskDirty) {
  10498. gl.depthMask(this.depthMask);
  10499. this._isDepthMaskDirty = false;
  10500. }
  10501. // Depth test
  10502. if (this._isDepthTestDirty) {
  10503. if (this.depthTest) {
  10504. gl.enable(gl.DEPTH_TEST);
  10505. }
  10506. else {
  10507. gl.disable(gl.DEPTH_TEST);
  10508. }
  10509. this._isDepthTestDirty = false;
  10510. }
  10511. // Depth func
  10512. if (this._isDepthFuncDirty) {
  10513. gl.depthFunc(this.depthFunc);
  10514. this._isDepthFuncDirty = false;
  10515. }
  10516. // zOffset
  10517. if (this._isZOffsetDirty) {
  10518. if (this.zOffset) {
  10519. gl.enable(gl.POLYGON_OFFSET_FILL);
  10520. gl.polygonOffset(this.zOffset, 0);
  10521. }
  10522. else {
  10523. gl.disable(gl.POLYGON_OFFSET_FILL);
  10524. }
  10525. this._isZOffsetDirty = false;
  10526. }
  10527. // Front face
  10528. if (this._isFrontFaceDirty) {
  10529. gl.frontFace(this.frontFace);
  10530. this._isFrontFaceDirty = false;
  10531. }
  10532. };
  10533. return _DepthCullingState;
  10534. }());
  10535. BABYLON._DepthCullingState = _DepthCullingState;
  10536. })(BABYLON || (BABYLON = {}));
  10537. //# sourceMappingURL=babylon.depthCullingState.js.map
  10538. var BABYLON;
  10539. (function (BABYLON) {
  10540. var _StencilState = /** @class */ (function () {
  10541. function _StencilState() {
  10542. this._isStencilTestDirty = false;
  10543. this._isStencilMaskDirty = false;
  10544. this._isStencilFuncDirty = false;
  10545. this._isStencilOpDirty = false;
  10546. this.reset();
  10547. }
  10548. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10549. get: function () {
  10550. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10551. },
  10552. enumerable: true,
  10553. configurable: true
  10554. });
  10555. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10556. get: function () {
  10557. return this._stencilFunc;
  10558. },
  10559. set: function (value) {
  10560. if (this._stencilFunc === value) {
  10561. return;
  10562. }
  10563. this._stencilFunc = value;
  10564. this._isStencilFuncDirty = true;
  10565. },
  10566. enumerable: true,
  10567. configurable: true
  10568. });
  10569. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10570. get: function () {
  10571. return this._stencilFuncRef;
  10572. },
  10573. set: function (value) {
  10574. if (this._stencilFuncRef === value) {
  10575. return;
  10576. }
  10577. this._stencilFuncRef = value;
  10578. this._isStencilFuncDirty = true;
  10579. },
  10580. enumerable: true,
  10581. configurable: true
  10582. });
  10583. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10584. get: function () {
  10585. return this._stencilFuncMask;
  10586. },
  10587. set: function (value) {
  10588. if (this._stencilFuncMask === value) {
  10589. return;
  10590. }
  10591. this._stencilFuncMask = value;
  10592. this._isStencilFuncDirty = true;
  10593. },
  10594. enumerable: true,
  10595. configurable: true
  10596. });
  10597. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10598. get: function () {
  10599. return this._stencilOpStencilFail;
  10600. },
  10601. set: function (value) {
  10602. if (this._stencilOpStencilFail === value) {
  10603. return;
  10604. }
  10605. this._stencilOpStencilFail = value;
  10606. this._isStencilOpDirty = true;
  10607. },
  10608. enumerable: true,
  10609. configurable: true
  10610. });
  10611. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10612. get: function () {
  10613. return this._stencilOpDepthFail;
  10614. },
  10615. set: function (value) {
  10616. if (this._stencilOpDepthFail === value) {
  10617. return;
  10618. }
  10619. this._stencilOpDepthFail = value;
  10620. this._isStencilOpDirty = true;
  10621. },
  10622. enumerable: true,
  10623. configurable: true
  10624. });
  10625. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10626. get: function () {
  10627. return this._stencilOpStencilDepthPass;
  10628. },
  10629. set: function (value) {
  10630. if (this._stencilOpStencilDepthPass === value) {
  10631. return;
  10632. }
  10633. this._stencilOpStencilDepthPass = value;
  10634. this._isStencilOpDirty = true;
  10635. },
  10636. enumerable: true,
  10637. configurable: true
  10638. });
  10639. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10640. get: function () {
  10641. return this._stencilMask;
  10642. },
  10643. set: function (value) {
  10644. if (this._stencilMask === value) {
  10645. return;
  10646. }
  10647. this._stencilMask = value;
  10648. this._isStencilMaskDirty = true;
  10649. },
  10650. enumerable: true,
  10651. configurable: true
  10652. });
  10653. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10654. get: function () {
  10655. return this._stencilTest;
  10656. },
  10657. set: function (value) {
  10658. if (this._stencilTest === value) {
  10659. return;
  10660. }
  10661. this._stencilTest = value;
  10662. this._isStencilTestDirty = true;
  10663. },
  10664. enumerable: true,
  10665. configurable: true
  10666. });
  10667. _StencilState.prototype.reset = function () {
  10668. this._stencilTest = false;
  10669. this._stencilMask = 0xFF;
  10670. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10671. this._stencilFuncRef = 1;
  10672. this._stencilFuncMask = 0xFF;
  10673. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10674. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10675. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10676. this._isStencilTestDirty = true;
  10677. this._isStencilMaskDirty = true;
  10678. this._isStencilFuncDirty = true;
  10679. this._isStencilOpDirty = true;
  10680. };
  10681. _StencilState.prototype.apply = function (gl) {
  10682. if (!this.isDirty) {
  10683. return;
  10684. }
  10685. // Stencil test
  10686. if (this._isStencilTestDirty) {
  10687. if (this.stencilTest) {
  10688. gl.enable(gl.STENCIL_TEST);
  10689. }
  10690. else {
  10691. gl.disable(gl.STENCIL_TEST);
  10692. }
  10693. this._isStencilTestDirty = false;
  10694. }
  10695. // Stencil mask
  10696. if (this._isStencilMaskDirty) {
  10697. gl.stencilMask(this.stencilMask);
  10698. this._isStencilMaskDirty = false;
  10699. }
  10700. // Stencil func
  10701. if (this._isStencilFuncDirty) {
  10702. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10703. this._isStencilFuncDirty = false;
  10704. }
  10705. // Stencil op
  10706. if (this._isStencilOpDirty) {
  10707. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10708. this._isStencilOpDirty = false;
  10709. }
  10710. };
  10711. return _StencilState;
  10712. }());
  10713. BABYLON._StencilState = _StencilState;
  10714. })(BABYLON || (BABYLON = {}));
  10715. //# sourceMappingURL=babylon.stencilState.js.map
  10716. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10717. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10718. s = arguments[i];
  10719. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10720. t[p] = s[p];
  10721. }
  10722. return t;
  10723. };
  10724. var BABYLON;
  10725. (function (BABYLON) {
  10726. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10727. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10728. };
  10729. var compileRawShader = function (gl, source, type) {
  10730. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10731. gl.shaderSource(shader, source);
  10732. gl.compileShader(shader);
  10733. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10734. var log = gl.getShaderInfoLog(shader);
  10735. if (log) {
  10736. throw new Error(log);
  10737. }
  10738. }
  10739. if (!shader) {
  10740. throw new Error("Something went wrong while compile the shader.");
  10741. }
  10742. return shader;
  10743. };
  10744. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10745. var magFilter = gl.NEAREST;
  10746. var minFilter = gl.NEAREST;
  10747. switch (samplingMode) {
  10748. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10749. magFilter = gl.LINEAR;
  10750. if (generateMipMaps) {
  10751. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10752. }
  10753. else {
  10754. minFilter = gl.LINEAR;
  10755. }
  10756. break;
  10757. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10758. magFilter = gl.LINEAR;
  10759. if (generateMipMaps) {
  10760. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10761. }
  10762. else {
  10763. minFilter = gl.LINEAR;
  10764. }
  10765. break;
  10766. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10767. magFilter = gl.NEAREST;
  10768. if (generateMipMaps) {
  10769. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10770. }
  10771. else {
  10772. minFilter = gl.NEAREST;
  10773. }
  10774. break;
  10775. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10776. magFilter = gl.NEAREST;
  10777. if (generateMipMaps) {
  10778. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10779. }
  10780. else {
  10781. minFilter = gl.NEAREST;
  10782. }
  10783. break;
  10784. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10785. magFilter = gl.NEAREST;
  10786. if (generateMipMaps) {
  10787. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10788. }
  10789. else {
  10790. minFilter = gl.LINEAR;
  10791. }
  10792. break;
  10793. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10794. magFilter = gl.NEAREST;
  10795. if (generateMipMaps) {
  10796. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10797. }
  10798. else {
  10799. minFilter = gl.LINEAR;
  10800. }
  10801. break;
  10802. case BABYLON.Texture.NEAREST_LINEAR:
  10803. magFilter = gl.NEAREST;
  10804. minFilter = gl.LINEAR;
  10805. break;
  10806. case BABYLON.Texture.NEAREST_NEAREST:
  10807. magFilter = gl.NEAREST;
  10808. minFilter = gl.NEAREST;
  10809. break;
  10810. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10811. magFilter = gl.LINEAR;
  10812. if (generateMipMaps) {
  10813. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10814. }
  10815. else {
  10816. minFilter = gl.NEAREST;
  10817. }
  10818. break;
  10819. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10820. magFilter = gl.LINEAR;
  10821. if (generateMipMaps) {
  10822. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10823. }
  10824. else {
  10825. minFilter = gl.NEAREST;
  10826. }
  10827. break;
  10828. case BABYLON.Texture.LINEAR_LINEAR:
  10829. magFilter = gl.LINEAR;
  10830. minFilter = gl.LINEAR;
  10831. break;
  10832. case BABYLON.Texture.LINEAR_NEAREST:
  10833. magFilter = gl.LINEAR;
  10834. minFilter = gl.NEAREST;
  10835. break;
  10836. }
  10837. return {
  10838. min: minFilter,
  10839. mag: magFilter
  10840. };
  10841. };
  10842. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10843. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10844. var img;
  10845. var onload = function () {
  10846. loadedImages[index] = img;
  10847. loadedImages._internalCount++;
  10848. if (scene) {
  10849. scene._removePendingData(img);
  10850. }
  10851. if (loadedImages._internalCount === 6) {
  10852. onfinish(loadedImages);
  10853. }
  10854. };
  10855. var onerror = function (message, exception) {
  10856. if (scene) {
  10857. scene._removePendingData(img);
  10858. }
  10859. if (onErrorCallBack) {
  10860. onErrorCallBack(message, exception);
  10861. }
  10862. };
  10863. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10864. if (scene) {
  10865. scene._addPendingData(img);
  10866. }
  10867. };
  10868. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10869. if (onError === void 0) { onError = null; }
  10870. var loadedImages = [];
  10871. loadedImages._internalCount = 0;
  10872. for (var index = 0; index < 6; index++) {
  10873. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10874. }
  10875. };
  10876. var BufferPointer = /** @class */ (function () {
  10877. function BufferPointer() {
  10878. }
  10879. return BufferPointer;
  10880. }());
  10881. /**
  10882. * Interface for attribute information associated with buffer instanciation
  10883. */
  10884. var InstancingAttributeInfo = /** @class */ (function () {
  10885. function InstancingAttributeInfo() {
  10886. }
  10887. return InstancingAttributeInfo;
  10888. }());
  10889. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10890. /**
  10891. * Define options used to create a render target texture
  10892. */
  10893. var RenderTargetCreationOptions = /** @class */ (function () {
  10894. function RenderTargetCreationOptions() {
  10895. }
  10896. return RenderTargetCreationOptions;
  10897. }());
  10898. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10899. /**
  10900. * Define options used to create a depth texture
  10901. */
  10902. var DepthTextureCreationOptions = /** @class */ (function () {
  10903. function DepthTextureCreationOptions() {
  10904. }
  10905. return DepthTextureCreationOptions;
  10906. }());
  10907. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10908. /**
  10909. * Class used to describe the capabilities of the engine relatively to the current browser
  10910. */
  10911. var EngineCapabilities = /** @class */ (function () {
  10912. function EngineCapabilities() {
  10913. }
  10914. return EngineCapabilities;
  10915. }());
  10916. BABYLON.EngineCapabilities = EngineCapabilities;
  10917. /**
  10918. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  10919. */
  10920. var Engine = /** @class */ (function () {
  10921. /**
  10922. * Creates a new engine
  10923. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10924. * @param antialias defines enable antialiasing (default: false)
  10925. * @param options defines further options to be sent to the getContext() function
  10926. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10927. */
  10928. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10929. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10930. var _this = this;
  10931. // Public members
  10932. /**
  10933. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  10934. */
  10935. this.forcePOTTextures = false;
  10936. /**
  10937. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  10938. */
  10939. this.isFullscreen = false;
  10940. /**
  10941. * Gets a boolean indicating if the pointer is currently locked
  10942. */
  10943. this.isPointerLock = false;
  10944. /**
  10945. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  10946. */
  10947. this.cullBackFaces = true;
  10948. /**
  10949. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  10950. */
  10951. this.renderEvenInBackground = true;
  10952. /**
  10953. * Gets or sets a boolean indicating that cache can be kept between frames
  10954. */
  10955. this.preventCacheWipeBetweenFrames = false;
  10956. /**
  10957. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  10958. **/
  10959. this.enableOfflineSupport = false;
  10960. /**
  10961. * Gets the list of created scenes
  10962. */
  10963. this.scenes = new Array();
  10964. /**
  10965. * Gets the list of created postprocesses
  10966. */
  10967. this.postProcesses = new Array();
  10968. // Observables
  10969. /**
  10970. * Observable event triggered each time the rendering canvas is resized
  10971. */
  10972. this.onResizeObservable = new BABYLON.Observable();
  10973. /**
  10974. * Observable event triggered each time the canvas loses focus
  10975. */
  10976. this.onCanvasBlurObservable = new BABYLON.Observable();
  10977. /**
  10978. * Observable event triggered each time the canvas gains focus
  10979. */
  10980. this.onCanvasFocusObservable = new BABYLON.Observable();
  10981. /**
  10982. * Observable event triggered each time the canvas receives pointerout event
  10983. */
  10984. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10985. /**
  10986. * Observable event triggered before each texture is initialized
  10987. */
  10988. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10989. //WebVR
  10990. this._vrDisplay = undefined;
  10991. this._vrSupported = false;
  10992. this._vrExclusivePointerMode = false;
  10993. // Uniform buffers list
  10994. /**
  10995. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  10996. */
  10997. this.disableUniformBuffers = false;
  10998. /** @ignore */
  10999. this._uniformBuffers = new Array();
  11000. // Observables
  11001. /**
  11002. * Observable raised when the engine begins a new frame
  11003. */
  11004. this.onBeginFrameObservable = new BABYLON.Observable();
  11005. /**
  11006. * Observable raised when the engine ends the current frame
  11007. */
  11008. this.onEndFrameObservable = new BABYLON.Observable();
  11009. /**
  11010. * Observable raised when the engine is about to compile a shader
  11011. */
  11012. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11013. /**
  11014. * Observable raised when the engine has jsut compiled a shader
  11015. */
  11016. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11017. this._windowIsBackground = false;
  11018. this._webGLVersion = 1.0;
  11019. /** @ignore */
  11020. this._badOS = false;
  11021. /** @ignore */
  11022. this._badDesktopOS = false;
  11023. /**
  11024. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11025. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11026. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11027. */
  11028. this.disableTextureBindingOptimization = false;
  11029. /**
  11030. * Observable signaled when VR display mode changes
  11031. */
  11032. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11033. /**
  11034. * Observable signaled when VR request present is complete
  11035. */
  11036. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11037. /**
  11038. * Observable signaled when VR request present starts
  11039. */
  11040. this.onVRRequestPresentStart = new BABYLON.Observable();
  11041. this._colorWrite = true;
  11042. /** @ignore */
  11043. this._drawCalls = new BABYLON.PerfCounter();
  11044. /** @ignore */
  11045. this._textureCollisions = new BABYLON.PerfCounter();
  11046. this._renderingQueueLaunched = false;
  11047. this._activeRenderLoops = new Array();
  11048. // Deterministic lockstepMaxSteps
  11049. this._deterministicLockstep = false;
  11050. this._lockstepMaxSteps = 4;
  11051. // Lost context
  11052. /**
  11053. * Observable signaled when a context lost event is raised
  11054. */
  11055. this.onContextLostObservable = new BABYLON.Observable();
  11056. /**
  11057. * Observable signaled when a context restored event is raised
  11058. */
  11059. this.onContextRestoredObservable = new BABYLON.Observable();
  11060. this._contextWasLost = false;
  11061. this._doNotHandleContextLost = false;
  11062. // FPS
  11063. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11064. this._fps = 60;
  11065. this._deltaTime = 0;
  11066. /**
  11067. * Turn this value on if you want to pause FPS computation when in background
  11068. */
  11069. this.disablePerformanceMonitorInBackground = false;
  11070. // States
  11071. /** @ignore */
  11072. this._depthCullingState = new BABYLON._DepthCullingState();
  11073. /** @ignore */
  11074. this._stencilState = new BABYLON._StencilState();
  11075. /** @ignore */
  11076. this._alphaState = new BABYLON._AlphaState();
  11077. /** @ignore */
  11078. this._alphaMode = Engine.ALPHA_DISABLE;
  11079. // Cache
  11080. this._internalTexturesCache = new Array();
  11081. /** @ignore */
  11082. this._activeChannel = 0;
  11083. this._currentTextureChannel = -1;
  11084. /** @ignore */
  11085. this._boundTexturesCache = {};
  11086. this._compiledEffects = {};
  11087. this._vertexAttribArraysEnabled = [];
  11088. this._uintIndicesCurrentlySet = false;
  11089. this._currentBoundBuffer = new Array();
  11090. this._currentBufferPointers = new Array();
  11091. this._currentInstanceLocations = new Array();
  11092. this._currentInstanceBuffers = new Array();
  11093. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11094. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11095. this._vaoRecordInProgress = false;
  11096. this._mustWipeVertexAttributes = false;
  11097. this._nextFreeTextureSlots = new Array();
  11098. this._maxSimultaneousTextures = 0;
  11099. this._activeRequests = new Array();
  11100. // Hardware supported Compressed Textures
  11101. this._texturesSupported = new Array();
  11102. this._onVRFullScreenTriggered = function () {
  11103. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11104. //get the old size before we change
  11105. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11106. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11107. //get the width and height, change the render size
  11108. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11109. _this.setHardwareScalingLevel(1);
  11110. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11111. }
  11112. else {
  11113. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11114. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11115. }
  11116. };
  11117. this._boundUniforms = {};
  11118. // Register promises
  11119. BABYLON.PromisePolyfill.Apply();
  11120. var canvas = null;
  11121. Engine.Instances.push(this);
  11122. if (!canvasOrContext) {
  11123. return;
  11124. }
  11125. options = options || {};
  11126. if (canvasOrContext.getContext) {
  11127. canvas = canvasOrContext;
  11128. this._renderingCanvas = canvas;
  11129. if (antialias != null) {
  11130. options.antialias = antialias;
  11131. }
  11132. if (options.deterministicLockstep === undefined) {
  11133. options.deterministicLockstep = false;
  11134. }
  11135. if (options.lockstepMaxSteps === undefined) {
  11136. options.lockstepMaxSteps = 4;
  11137. }
  11138. if (options.preserveDrawingBuffer === undefined) {
  11139. options.preserveDrawingBuffer = false;
  11140. }
  11141. if (options.audioEngine === undefined) {
  11142. options.audioEngine = true;
  11143. }
  11144. if (options.stencil === undefined) {
  11145. options.stencil = true;
  11146. }
  11147. this._deterministicLockstep = options.deterministicLockstep;
  11148. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11149. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11150. // Exceptions
  11151. if (navigator && navigator.userAgent) {
  11152. var ua = navigator.userAgent;
  11153. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11154. var exception = _a[_i];
  11155. var key = exception.key;
  11156. var targets = exception.targets;
  11157. if (ua.indexOf(key) > -1) {
  11158. if (exception.capture && exception.captureConstraint) {
  11159. var capture = exception.capture;
  11160. var constraint = exception.captureConstraint;
  11161. var regex = new RegExp(capture);
  11162. var matches = regex.exec(ua);
  11163. if (matches && matches.length > 0) {
  11164. var capturedValue = parseInt(matches[matches.length - 1]);
  11165. if (capturedValue >= constraint) {
  11166. continue;
  11167. }
  11168. }
  11169. }
  11170. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11171. var target = targets_1[_b];
  11172. switch (target) {
  11173. case "uniformBuffer":
  11174. this.disableUniformBuffers = true;
  11175. break;
  11176. case "textureBindingOptimization":
  11177. this.disableTextureBindingOptimization = true;
  11178. break;
  11179. }
  11180. }
  11181. }
  11182. }
  11183. }
  11184. // GL
  11185. if (!options.disableWebGL2Support) {
  11186. try {
  11187. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11188. if (this._gl) {
  11189. this._webGLVersion = 2.0;
  11190. }
  11191. }
  11192. catch (e) {
  11193. // Do nothing
  11194. }
  11195. }
  11196. if (!this._gl) {
  11197. if (!canvas) {
  11198. throw new Error("The provided canvas is null or undefined.");
  11199. }
  11200. try {
  11201. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11202. }
  11203. catch (e) {
  11204. throw new Error("WebGL not supported");
  11205. }
  11206. }
  11207. if (!this._gl) {
  11208. throw new Error("WebGL not supported");
  11209. }
  11210. this._onCanvasFocus = function () {
  11211. _this.onCanvasFocusObservable.notifyObservers(_this);
  11212. };
  11213. this._onCanvasBlur = function () {
  11214. _this.onCanvasBlurObservable.notifyObservers(_this);
  11215. };
  11216. canvas.addEventListener("focus", this._onCanvasFocus);
  11217. canvas.addEventListener("blur", this._onCanvasBlur);
  11218. this._onBlur = function () {
  11219. if (_this.disablePerformanceMonitorInBackground) {
  11220. _this._performanceMonitor.disable();
  11221. }
  11222. _this._windowIsBackground = true;
  11223. };
  11224. this._onFocus = function () {
  11225. if (_this.disablePerformanceMonitorInBackground) {
  11226. _this._performanceMonitor.enable();
  11227. }
  11228. _this._windowIsBackground = false;
  11229. };
  11230. this._onCanvasPointerOut = function (ev) {
  11231. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11232. };
  11233. window.addEventListener("blur", this._onBlur);
  11234. window.addEventListener("focus", this._onFocus);
  11235. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11236. // Context lost
  11237. if (!this._doNotHandleContextLost) {
  11238. this._onContextLost = function (evt) {
  11239. evt.preventDefault();
  11240. _this._contextWasLost = true;
  11241. BABYLON.Tools.Warn("WebGL context lost.");
  11242. _this.onContextLostObservable.notifyObservers(_this);
  11243. };
  11244. this._onContextRestored = function (evt) {
  11245. // Adding a timeout to avoid race condition at browser level
  11246. setTimeout(function () {
  11247. // Rebuild gl context
  11248. _this._initGLContext();
  11249. // Rebuild effects
  11250. _this._rebuildEffects();
  11251. // Rebuild textures
  11252. _this._rebuildInternalTextures();
  11253. // Rebuild buffers
  11254. _this._rebuildBuffers();
  11255. // Cache
  11256. _this.wipeCaches(true);
  11257. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11258. _this.onContextRestoredObservable.notifyObservers(_this);
  11259. _this._contextWasLost = false;
  11260. }, 0);
  11261. };
  11262. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11263. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11264. }
  11265. }
  11266. else {
  11267. this._gl = canvasOrContext;
  11268. this._renderingCanvas = this._gl.canvas;
  11269. if (this._gl.renderbufferStorageMultisample) {
  11270. this._webGLVersion = 2.0;
  11271. }
  11272. options.stencil = this._gl.getContextAttributes().stencil;
  11273. }
  11274. // Viewport
  11275. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11276. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11277. this.resize();
  11278. this._isStencilEnable = options.stencil ? true : false;
  11279. this._initGLContext();
  11280. if (canvas) {
  11281. // Fullscreen
  11282. this._onFullscreenChange = function () {
  11283. if (document.fullscreen !== undefined) {
  11284. _this.isFullscreen = document.fullscreen;
  11285. }
  11286. else if (document.mozFullScreen !== undefined) {
  11287. _this.isFullscreen = document.mozFullScreen;
  11288. }
  11289. else if (document.webkitIsFullScreen !== undefined) {
  11290. _this.isFullscreen = document.webkitIsFullScreen;
  11291. }
  11292. else if (document.msIsFullScreen !== undefined) {
  11293. _this.isFullscreen = document.msIsFullScreen;
  11294. }
  11295. // Pointer lock
  11296. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11297. canvas.requestPointerLock = canvas.requestPointerLock ||
  11298. canvas.msRequestPointerLock ||
  11299. canvas.mozRequestPointerLock ||
  11300. canvas.webkitRequestPointerLock;
  11301. if (canvas.requestPointerLock) {
  11302. canvas.requestPointerLock();
  11303. }
  11304. }
  11305. };
  11306. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11307. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11308. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11309. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11310. // Pointer lock
  11311. this._onPointerLockChange = function () {
  11312. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11313. document.webkitPointerLockElement === canvas ||
  11314. document.msPointerLockElement === canvas ||
  11315. document.pointerLockElement === canvas);
  11316. };
  11317. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11318. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11319. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11320. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11321. this._onVRDisplayPointerRestricted = function () {
  11322. if (canvas) {
  11323. canvas.requestPointerLock();
  11324. }
  11325. };
  11326. this._onVRDisplayPointerUnrestricted = function () {
  11327. document.exitPointerLock();
  11328. };
  11329. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11330. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11331. }
  11332. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11333. Engine.audioEngine = new BABYLON.AudioEngine();
  11334. }
  11335. // Prepare buffer pointers
  11336. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11337. this._currentBufferPointers[i] = new BufferPointer();
  11338. }
  11339. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11340. // Load WebVR Devices
  11341. if (options.autoEnableWebVR) {
  11342. this.initWebVR();
  11343. }
  11344. // Detect if we are running on a faulty buggy OS.
  11345. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11346. // Detect if we are running on a faulty buggy desktop OS.
  11347. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11348. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11349. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11350. }
  11351. Object.defineProperty(Engine, "LastCreatedEngine", {
  11352. /**
  11353. * Gets the latest created engine
  11354. */
  11355. get: function () {
  11356. if (Engine.Instances.length === 0) {
  11357. return null;
  11358. }
  11359. return Engine.Instances[Engine.Instances.length - 1];
  11360. },
  11361. enumerable: true,
  11362. configurable: true
  11363. });
  11364. Object.defineProperty(Engine, "LastCreatedScene", {
  11365. /**
  11366. * Gets the latest created scene
  11367. */
  11368. get: function () {
  11369. var lastCreatedEngine = Engine.LastCreatedEngine;
  11370. if (!lastCreatedEngine) {
  11371. return null;
  11372. }
  11373. if (lastCreatedEngine.scenes.length === 0) {
  11374. return null;
  11375. }
  11376. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11377. },
  11378. enumerable: true,
  11379. configurable: true
  11380. });
  11381. /**
  11382. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11383. * @param flag defines which part of the materials must be marked as dirty
  11384. * @param predicate defines a predicate used to filter which materials should be affected
  11385. */
  11386. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11387. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11388. var engine = Engine.Instances[engineIndex];
  11389. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11390. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11391. }
  11392. }
  11393. };
  11394. Object.defineProperty(Engine, "NEVER", {
  11395. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11396. get: function () {
  11397. return Engine._NEVER;
  11398. },
  11399. enumerable: true,
  11400. configurable: true
  11401. });
  11402. Object.defineProperty(Engine, "ALWAYS", {
  11403. /** 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 */
  11404. get: function () {
  11405. return Engine._ALWAYS;
  11406. },
  11407. enumerable: true,
  11408. configurable: true
  11409. });
  11410. Object.defineProperty(Engine, "LESS", {
  11411. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11412. get: function () {
  11413. return Engine._LESS;
  11414. },
  11415. enumerable: true,
  11416. configurable: true
  11417. });
  11418. Object.defineProperty(Engine, "EQUAL", {
  11419. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11420. get: function () {
  11421. return Engine._EQUAL;
  11422. },
  11423. enumerable: true,
  11424. configurable: true
  11425. });
  11426. Object.defineProperty(Engine, "LEQUAL", {
  11427. /** 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 */
  11428. get: function () {
  11429. return Engine._LEQUAL;
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. Object.defineProperty(Engine, "GREATER", {
  11435. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11436. get: function () {
  11437. return Engine._GREATER;
  11438. },
  11439. enumerable: true,
  11440. configurable: true
  11441. });
  11442. Object.defineProperty(Engine, "GEQUAL", {
  11443. /** 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 */
  11444. get: function () {
  11445. return Engine._GEQUAL;
  11446. },
  11447. enumerable: true,
  11448. configurable: true
  11449. });
  11450. Object.defineProperty(Engine, "NOTEQUAL", {
  11451. /** 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 */
  11452. get: function () {
  11453. return Engine._NOTEQUAL;
  11454. },
  11455. enumerable: true,
  11456. configurable: true
  11457. });
  11458. Object.defineProperty(Engine, "KEEP", {
  11459. /** Passed to stencilOperation to specify that stencil value must be kept */
  11460. get: function () {
  11461. return Engine._KEEP;
  11462. },
  11463. enumerable: true,
  11464. configurable: true
  11465. });
  11466. Object.defineProperty(Engine, "REPLACE", {
  11467. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11468. get: function () {
  11469. return Engine._REPLACE;
  11470. },
  11471. enumerable: true,
  11472. configurable: true
  11473. });
  11474. Object.defineProperty(Engine, "INCR", {
  11475. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11476. get: function () {
  11477. return Engine._INCR;
  11478. },
  11479. enumerable: true,
  11480. configurable: true
  11481. });
  11482. Object.defineProperty(Engine, "DECR", {
  11483. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11484. get: function () {
  11485. return Engine._DECR;
  11486. },
  11487. enumerable: true,
  11488. configurable: true
  11489. });
  11490. Object.defineProperty(Engine, "INVERT", {
  11491. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11492. get: function () {
  11493. return Engine._INVERT;
  11494. },
  11495. enumerable: true,
  11496. configurable: true
  11497. });
  11498. Object.defineProperty(Engine, "INCR_WRAP", {
  11499. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11500. get: function () {
  11501. return Engine._INCR_WRAP;
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Object.defineProperty(Engine, "DECR_WRAP", {
  11507. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11508. get: function () {
  11509. return Engine._DECR_WRAP;
  11510. },
  11511. enumerable: true,
  11512. configurable: true
  11513. });
  11514. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11515. // Alpha
  11516. /** Defines that alpha blending is disabled */
  11517. get: function () {
  11518. return Engine._ALPHA_DISABLE;
  11519. },
  11520. enumerable: true,
  11521. configurable: true
  11522. });
  11523. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11524. /** Defines that alpha blending to SRC + DEST */
  11525. get: function () {
  11526. return Engine._ALPHA_ONEONE;
  11527. },
  11528. enumerable: true,
  11529. configurable: true
  11530. });
  11531. Object.defineProperty(Engine, "ALPHA_ADD", {
  11532. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11533. get: function () {
  11534. return Engine._ALPHA_ADD;
  11535. },
  11536. enumerable: true,
  11537. configurable: true
  11538. });
  11539. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11540. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11541. get: function () {
  11542. return Engine._ALPHA_COMBINE;
  11543. },
  11544. enumerable: true,
  11545. configurable: true
  11546. });
  11547. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11548. /** Defines that alpha blending to DEST - SRC * DEST */
  11549. get: function () {
  11550. return Engine._ALPHA_SUBTRACT;
  11551. },
  11552. enumerable: true,
  11553. configurable: true
  11554. });
  11555. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11556. /** Defines that alpha blending to SRC * DEST */
  11557. get: function () {
  11558. return Engine._ALPHA_MULTIPLY;
  11559. },
  11560. enumerable: true,
  11561. configurable: true
  11562. });
  11563. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11564. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11565. get: function () {
  11566. return Engine._ALPHA_MAXIMIZED;
  11567. },
  11568. enumerable: true,
  11569. configurable: true
  11570. });
  11571. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11572. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11573. get: function () {
  11574. return Engine._ALPHA_PREMULTIPLIED;
  11575. },
  11576. enumerable: true,
  11577. configurable: true
  11578. });
  11579. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11580. /**
  11581. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11582. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11583. */
  11584. get: function () {
  11585. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11586. },
  11587. enumerable: true,
  11588. configurable: true
  11589. });
  11590. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11591. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11592. get: function () {
  11593. return Engine._ALPHA_INTERPOLATE;
  11594. },
  11595. enumerable: true,
  11596. configurable: true
  11597. });
  11598. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11599. /**
  11600. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11601. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11602. */
  11603. get: function () {
  11604. return Engine._ALPHA_SCREENMODE;
  11605. },
  11606. enumerable: true,
  11607. configurable: true
  11608. });
  11609. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11610. // Delays
  11611. /** Defines that the ressource is not delayed*/
  11612. get: function () {
  11613. return Engine._DELAYLOADSTATE_NONE;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11619. /** Defines that the ressource was successfully delay loaded */
  11620. get: function () {
  11621. return Engine._DELAYLOADSTATE_LOADED;
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11627. /** Defines that the ressource is currently delay loading */
  11628. get: function () {
  11629. return Engine._DELAYLOADSTATE_LOADING;
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11635. /** Defines that the ressource is delayed and has not started loading */
  11636. get: function () {
  11637. return Engine._DELAYLOADSTATE_NOTLOADED;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11643. /** ALPHA */
  11644. get: function () {
  11645. return Engine._TEXTUREFORMAT_ALPHA;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11651. /** LUMINANCE */
  11652. get: function () {
  11653. return Engine._TEXTUREFORMAT_LUMINANCE;
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11659. /**
  11660. * R32F
  11661. */
  11662. get: function () {
  11663. return Engine._TEXTUREFORMAT_R32F;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11669. /**
  11670. * RG32F
  11671. */
  11672. get: function () {
  11673. return Engine._TEXTUREFORMAT_RG32F;
  11674. },
  11675. enumerable: true,
  11676. configurable: true
  11677. });
  11678. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11679. /**
  11680. * RGB32F
  11681. */
  11682. get: function () {
  11683. return Engine._TEXTUREFORMAT_RGB32F;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11689. /**
  11690. * RGBA32F
  11691. */
  11692. get: function () {
  11693. return Engine._TEXTUREFORMAT_RGBA32F;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11699. /** LUMINANCE_ALPHA */
  11700. get: function () {
  11701. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11707. /** RGB */
  11708. get: function () {
  11709. return Engine._TEXTUREFORMAT_RGB;
  11710. },
  11711. enumerable: true,
  11712. configurable: true
  11713. });
  11714. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11715. /** RGBA */
  11716. get: function () {
  11717. return Engine._TEXTUREFORMAT_RGBA;
  11718. },
  11719. enumerable: true,
  11720. configurable: true
  11721. });
  11722. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11723. /** UNSIGNED_INT */
  11724. get: function () {
  11725. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11731. /** FLOAT */
  11732. get: function () {
  11733. return Engine._TEXTURETYPE_FLOAT;
  11734. },
  11735. enumerable: true,
  11736. configurable: true
  11737. });
  11738. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11739. /** HALF_FLOAT */
  11740. get: function () {
  11741. return Engine._TEXTURETYPE_HALF_FLOAT;
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11747. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11748. get: function () {
  11749. return Engine._SCALEMODE_FLOOR;
  11750. },
  11751. enumerable: true,
  11752. configurable: true
  11753. });
  11754. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11755. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11756. get: function () {
  11757. return Engine._SCALEMODE_NEAREST;
  11758. },
  11759. enumerable: true,
  11760. configurable: true
  11761. });
  11762. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11763. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11764. get: function () {
  11765. return Engine._SCALEMODE_CEILING;
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(Engine, "Version", {
  11771. /**
  11772. * Returns the current version of the framework
  11773. */
  11774. get: function () {
  11775. return "3.2.0-beta.5";
  11776. },
  11777. enumerable: true,
  11778. configurable: true
  11779. });
  11780. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11781. /**
  11782. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11783. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11784. */
  11785. get: function () {
  11786. return this._vrExclusivePointerMode;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11792. /**
  11793. * Gets a boolean indicating that the engine supports uniform buffers
  11794. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11795. */
  11796. get: function () {
  11797. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11798. },
  11799. enumerable: true,
  11800. configurable: true
  11801. });
  11802. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11803. /**
  11804. * Gets a boolean indicating that only power of 2 textures are supported
  11805. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11806. */
  11807. get: function () {
  11808. return this._webGLVersion < 2 || this.forcePOTTextures;
  11809. },
  11810. enumerable: true,
  11811. configurable: true
  11812. });
  11813. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11814. /**
  11815. * Gets the performance monitor attached to this engine
  11816. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11817. */
  11818. get: function () {
  11819. return this._performanceMonitor;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11825. /**
  11826. * Gets the list of texture formats supported
  11827. */
  11828. get: function () {
  11829. return this._texturesSupported;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11835. /**
  11836. * Gets the list of texture formats in use
  11837. */
  11838. get: function () {
  11839. return this._textureFormatInUse;
  11840. },
  11841. enumerable: true,
  11842. configurable: true
  11843. });
  11844. Object.defineProperty(Engine.prototype, "currentViewport", {
  11845. /**
  11846. * Gets the current viewport
  11847. */
  11848. get: function () {
  11849. return this._cachedViewport;
  11850. },
  11851. enumerable: true,
  11852. configurable: true
  11853. });
  11854. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11855. /**
  11856. * Gets the default empty texture
  11857. */
  11858. get: function () {
  11859. if (!this._emptyTexture) {
  11860. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11861. }
  11862. return this._emptyTexture;
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11868. /**
  11869. * Gets the default empty 3D texture
  11870. */
  11871. get: function () {
  11872. if (!this._emptyTexture3D) {
  11873. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11874. }
  11875. return this._emptyTexture3D;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11881. /**
  11882. * Gets the default empty cube texture
  11883. */
  11884. get: function () {
  11885. if (!this._emptyCubeTexture) {
  11886. var faceData = new Uint8Array(4);
  11887. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11888. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11889. }
  11890. return this._emptyCubeTexture;
  11891. },
  11892. enumerable: true,
  11893. configurable: true
  11894. });
  11895. Engine.prototype._rebuildInternalTextures = function () {
  11896. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11897. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11898. var internalTexture = currentState_1[_i];
  11899. internalTexture._rebuild();
  11900. }
  11901. };
  11902. Engine.prototype._rebuildEffects = function () {
  11903. for (var key in this._compiledEffects) {
  11904. var effect = this._compiledEffects[key];
  11905. effect._prepareEffect();
  11906. }
  11907. BABYLON.Effect.ResetCache();
  11908. };
  11909. Engine.prototype._rebuildBuffers = function () {
  11910. // Index / Vertex
  11911. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11912. var scene = _a[_i];
  11913. scene.resetCachedMaterial();
  11914. scene._rebuildGeometries();
  11915. scene._rebuildTextures();
  11916. }
  11917. // Uniforms
  11918. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11919. var uniformBuffer = _c[_b];
  11920. uniformBuffer._rebuild();
  11921. }
  11922. };
  11923. Engine.prototype._initGLContext = function () {
  11924. // Caps
  11925. this._caps = new EngineCapabilities();
  11926. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11927. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11928. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11929. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11930. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11931. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11932. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11933. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11934. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11935. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11936. // Infos
  11937. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11938. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11939. if (rendererInfo != null) {
  11940. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11941. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11942. }
  11943. if (!this._glVendor) {
  11944. this._glVendor = "Unknown vendor";
  11945. }
  11946. if (!this._glRenderer) {
  11947. this._glRenderer = "Unknown renderer";
  11948. }
  11949. // Constants
  11950. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11951. if (this._gl.RGBA16F !== 0x881A) {
  11952. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11953. }
  11954. if (this._gl.RGBA32F !== 0x8814) {
  11955. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11956. }
  11957. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11958. this._gl.DEPTH24_STENCIL8 = 35056;
  11959. }
  11960. // Extensions
  11961. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11962. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11963. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11964. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11965. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11966. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11967. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11968. 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');
  11969. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11970. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11971. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11972. this._caps.highPrecisionShaderSupported = true;
  11973. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11974. if (this._caps.timerQuery) {
  11975. if (this._webGLVersion === 1) {
  11976. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11977. }
  11978. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11979. }
  11980. // Checks if some of the format renders first to allow the use of webgl inspector.
  11981. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11982. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11983. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11984. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11985. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11986. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11987. if (this._webGLVersion > 1) {
  11988. this._gl.HALF_FLOAT_OES = 0x140B;
  11989. }
  11990. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11991. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11992. // Draw buffers
  11993. if (this._webGLVersion > 1) {
  11994. this._caps.drawBuffersExtension = true;
  11995. }
  11996. else {
  11997. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11998. if (drawBuffersExtension !== null) {
  11999. this._caps.drawBuffersExtension = true;
  12000. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12001. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12002. for (var i = 0; i < 16; i++) {
  12003. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12004. }
  12005. }
  12006. else {
  12007. this._caps.drawBuffersExtension = false;
  12008. }
  12009. }
  12010. // Depth Texture
  12011. if (this._webGLVersion > 1) {
  12012. this._caps.depthTextureExtension = true;
  12013. }
  12014. else {
  12015. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12016. if (depthTextureExtension != null) {
  12017. this._caps.depthTextureExtension = true;
  12018. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12019. }
  12020. }
  12021. // Vertex array object
  12022. if (this._webGLVersion > 1) {
  12023. this._caps.vertexArrayObject = true;
  12024. }
  12025. else {
  12026. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12027. if (vertexArrayObjectExtension != null) {
  12028. this._caps.vertexArrayObject = true;
  12029. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12030. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12031. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12032. }
  12033. else {
  12034. this._caps.vertexArrayObject = false;
  12035. }
  12036. }
  12037. // Instances count
  12038. if (this._webGLVersion > 1) {
  12039. this._caps.instancedArrays = true;
  12040. }
  12041. else {
  12042. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12043. if (instanceExtension != null) {
  12044. this._caps.instancedArrays = true;
  12045. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12046. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12047. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12048. }
  12049. else {
  12050. this._caps.instancedArrays = false;
  12051. }
  12052. }
  12053. // Intelligently add supported compressed formats in order to check for.
  12054. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12055. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12056. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12057. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12058. if (this._caps.astc)
  12059. this.texturesSupported.push('-astc.ktx');
  12060. if (this._caps.s3tc)
  12061. this.texturesSupported.push('-dxt.ktx');
  12062. if (this._caps.pvrtc)
  12063. this.texturesSupported.push('-pvrtc.ktx');
  12064. if (this._caps.etc2)
  12065. this.texturesSupported.push('-etc2.ktx');
  12066. if (this._caps.etc1)
  12067. this.texturesSupported.push('-etc1.ktx');
  12068. if (this._gl.getShaderPrecisionFormat) {
  12069. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12070. if (highp) {
  12071. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12072. }
  12073. }
  12074. // Depth buffer
  12075. this.setDepthBuffer(true);
  12076. this.setDepthFunctionToLessOrEqual();
  12077. this.setDepthWrite(true);
  12078. // Texture maps
  12079. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12080. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12081. this._nextFreeTextureSlots.push(slot);
  12082. }
  12083. };
  12084. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12085. /**
  12086. * Gets version of the current webGL context
  12087. */
  12088. get: function () {
  12089. return this._webGLVersion;
  12090. },
  12091. enumerable: true,
  12092. configurable: true
  12093. });
  12094. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12095. /**
  12096. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12097. */
  12098. get: function () {
  12099. return this._isStencilEnable;
  12100. },
  12101. enumerable: true,
  12102. configurable: true
  12103. });
  12104. Engine.prototype._prepareWorkingCanvas = function () {
  12105. if (this._workingCanvas) {
  12106. return;
  12107. }
  12108. this._workingCanvas = document.createElement("canvas");
  12109. var context = this._workingCanvas.getContext("2d");
  12110. if (context) {
  12111. this._workingContext = context;
  12112. }
  12113. };
  12114. /**
  12115. * Reset the texture cache to empty state
  12116. */
  12117. Engine.prototype.resetTextureCache = function () {
  12118. for (var key in this._boundTexturesCache) {
  12119. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12120. continue;
  12121. }
  12122. var boundTexture = this._boundTexturesCache[key];
  12123. if (boundTexture) {
  12124. this._removeDesignatedSlot(boundTexture);
  12125. }
  12126. this._boundTexturesCache[key] = null;
  12127. }
  12128. if (!this.disableTextureBindingOptimization) {
  12129. this._nextFreeTextureSlots = [];
  12130. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12131. this._nextFreeTextureSlots.push(slot);
  12132. }
  12133. }
  12134. this._currentTextureChannel = -1;
  12135. };
  12136. /**
  12137. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12138. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12139. * @returns true if engine is in deterministic lock step mode
  12140. */
  12141. Engine.prototype.isDeterministicLockStep = function () {
  12142. return this._deterministicLockstep;
  12143. };
  12144. /**
  12145. * Gets the max steps when engine is running in deterministic lock step
  12146. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12147. * @returns the max steps
  12148. */
  12149. Engine.prototype.getLockstepMaxSteps = function () {
  12150. return this._lockstepMaxSteps;
  12151. };
  12152. /**
  12153. * Gets an object containing information about the current webGL context
  12154. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12155. */
  12156. Engine.prototype.getGlInfo = function () {
  12157. return {
  12158. vendor: this._glVendor,
  12159. renderer: this._glRenderer,
  12160. version: this._glVersion
  12161. };
  12162. };
  12163. /**
  12164. * Gets current aspect ratio
  12165. * @param camera defines the camera to use to get the aspect ratio
  12166. * @param useScreen defines if screen size must be used (or the current render target if any)
  12167. * @returns a number defining the aspect ratio
  12168. */
  12169. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12170. if (useScreen === void 0) { useScreen = false; }
  12171. var viewport = camera.viewport;
  12172. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12173. };
  12174. /**
  12175. * Gets the current render width
  12176. * @param useScreen defines if screen size must be used (or the current render target if any)
  12177. * @returns a number defining the current render width
  12178. */
  12179. Engine.prototype.getRenderWidth = function (useScreen) {
  12180. if (useScreen === void 0) { useScreen = false; }
  12181. if (!useScreen && this._currentRenderTarget) {
  12182. return this._currentRenderTarget.width;
  12183. }
  12184. return this._gl.drawingBufferWidth;
  12185. };
  12186. /**
  12187. * Gets the current render height
  12188. * @param useScreen defines if screen size must be used (or the current render target if any)
  12189. * @returns a number defining the current render height
  12190. */
  12191. Engine.prototype.getRenderHeight = function (useScreen) {
  12192. if (useScreen === void 0) { useScreen = false; }
  12193. if (!useScreen && this._currentRenderTarget) {
  12194. return this._currentRenderTarget.height;
  12195. }
  12196. return this._gl.drawingBufferHeight;
  12197. };
  12198. /**
  12199. * Gets the HTML canvas attached with the current webGL context
  12200. * @returns a HTML canvas
  12201. */
  12202. Engine.prototype.getRenderingCanvas = function () {
  12203. return this._renderingCanvas;
  12204. };
  12205. /**
  12206. * Gets the client rect of the HTML canvas attached with the current webGL context
  12207. * @returns a client rectanglee
  12208. */
  12209. Engine.prototype.getRenderingCanvasClientRect = function () {
  12210. if (!this._renderingCanvas) {
  12211. return null;
  12212. }
  12213. return this._renderingCanvas.getBoundingClientRect();
  12214. };
  12215. /**
  12216. * Defines the hardware scaling level.
  12217. * By default the hardware scaling level is computed from the window device ratio.
  12218. * 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.
  12219. * @param level defines the level to use
  12220. */
  12221. Engine.prototype.setHardwareScalingLevel = function (level) {
  12222. this._hardwareScalingLevel = level;
  12223. this.resize();
  12224. };
  12225. /**
  12226. * Gets the current hardware scaling level.
  12227. * By default the hardware scaling level is computed from the window device ratio.
  12228. * 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.
  12229. * @returns a number indicating the current hardware scaling level
  12230. */
  12231. Engine.prototype.getHardwareScalingLevel = function () {
  12232. return this._hardwareScalingLevel;
  12233. };
  12234. /**
  12235. * Gets the list of loaded textures
  12236. * @returns an array containing all loaded textures
  12237. */
  12238. Engine.prototype.getLoadedTexturesCache = function () {
  12239. return this._internalTexturesCache;
  12240. };
  12241. /**
  12242. * Gets the object containing all engine capabilities
  12243. * @returns the EngineCapabilities object
  12244. */
  12245. Engine.prototype.getCaps = function () {
  12246. return this._caps;
  12247. };
  12248. Object.defineProperty(Engine.prototype, "drawCalls", {
  12249. /** @ignore */
  12250. get: function () {
  12251. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12252. return 0;
  12253. },
  12254. enumerable: true,
  12255. configurable: true
  12256. });
  12257. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12258. /** @ignore */
  12259. get: function () {
  12260. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12261. return null;
  12262. },
  12263. enumerable: true,
  12264. configurable: true
  12265. });
  12266. /**
  12267. * Gets the current depth function
  12268. * @returns a number defining the depth function
  12269. */
  12270. Engine.prototype.getDepthFunction = function () {
  12271. return this._depthCullingState.depthFunc;
  12272. };
  12273. /**
  12274. * Sets the current depth function
  12275. * @param depthFunc defines the function to use
  12276. */
  12277. Engine.prototype.setDepthFunction = function (depthFunc) {
  12278. this._depthCullingState.depthFunc = depthFunc;
  12279. };
  12280. /**
  12281. * Sets the current depth function to GREATER
  12282. */
  12283. Engine.prototype.setDepthFunctionToGreater = function () {
  12284. this._depthCullingState.depthFunc = this._gl.GREATER;
  12285. };
  12286. /**
  12287. * Sets the current depth function to GEQUAL
  12288. */
  12289. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12290. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12291. };
  12292. /**
  12293. * Sets the current depth function to LESS
  12294. */
  12295. Engine.prototype.setDepthFunctionToLess = function () {
  12296. this._depthCullingState.depthFunc = this._gl.LESS;
  12297. };
  12298. /**
  12299. * Sets the current depth function to LEQUAL
  12300. */
  12301. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12302. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12303. };
  12304. /**
  12305. * Gets a boolean indicating if stencil buffer is enabled
  12306. * @returns the current stencil buffer state
  12307. */
  12308. Engine.prototype.getStencilBuffer = function () {
  12309. return this._stencilState.stencilTest;
  12310. };
  12311. /**
  12312. * Enable or disable the stencil buffer
  12313. * @param enable defines if the stencil buffer must be enabled or disabled
  12314. */
  12315. Engine.prototype.setStencilBuffer = function (enable) {
  12316. this._stencilState.stencilTest = enable;
  12317. };
  12318. /**
  12319. * Gets the current stencil mask
  12320. * @returns a number defining the new stencil mask to use
  12321. */
  12322. Engine.prototype.getStencilMask = function () {
  12323. return this._stencilState.stencilMask;
  12324. };
  12325. /**
  12326. * Sets the current stencil mask
  12327. * @param mask defines the new stencil mask to use
  12328. */
  12329. Engine.prototype.setStencilMask = function (mask) {
  12330. this._stencilState.stencilMask = mask;
  12331. };
  12332. /**
  12333. * Gets the current stencil function
  12334. * @returns a number defining the stencil function to use
  12335. */
  12336. Engine.prototype.getStencilFunction = function () {
  12337. return this._stencilState.stencilFunc;
  12338. };
  12339. /**
  12340. * Gets the current stencil reference value
  12341. * @returns a number defining the stencil reference value to use
  12342. */
  12343. Engine.prototype.getStencilFunctionReference = function () {
  12344. return this._stencilState.stencilFuncRef;
  12345. };
  12346. /**
  12347. * Gets the current stencil mask
  12348. * @returns a number defining the stencil mask to use
  12349. */
  12350. Engine.prototype.getStencilFunctionMask = function () {
  12351. return this._stencilState.stencilFuncMask;
  12352. };
  12353. /**
  12354. * Sets the current stencil function
  12355. * @param stencilFunc defines the new stencil function to use
  12356. */
  12357. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12358. this._stencilState.stencilFunc = stencilFunc;
  12359. };
  12360. /**
  12361. * Sets the current stencil reference
  12362. * @param reference defines the new stencil reference to use
  12363. */
  12364. Engine.prototype.setStencilFunctionReference = function (reference) {
  12365. this._stencilState.stencilFuncRef = reference;
  12366. };
  12367. /**
  12368. * Sets the current stencil mask
  12369. * @param mask defines the new stencil mask to use
  12370. */
  12371. Engine.prototype.setStencilFunctionMask = function (mask) {
  12372. this._stencilState.stencilFuncMask = mask;
  12373. };
  12374. /**
  12375. * Gets the current stencil operation when stencil fails
  12376. * @returns a number defining stencil operation to use when stencil fails
  12377. */
  12378. Engine.prototype.getStencilOperationFail = function () {
  12379. return this._stencilState.stencilOpStencilFail;
  12380. };
  12381. /**
  12382. * Gets the current stencil operation when depth fails
  12383. * @returns a number defining stencil operation to use when depth fails
  12384. */
  12385. Engine.prototype.getStencilOperationDepthFail = function () {
  12386. return this._stencilState.stencilOpDepthFail;
  12387. };
  12388. /**
  12389. * Gets the current stencil operation when stencil passes
  12390. * @returns a number defining stencil operation to use when stencil passes
  12391. */
  12392. Engine.prototype.getStencilOperationPass = function () {
  12393. return this._stencilState.stencilOpStencilDepthPass;
  12394. };
  12395. /**
  12396. * Sets the stencil operation to use when stencil fails
  12397. * @param operation defines the stencil operation to use when stencil fails
  12398. */
  12399. Engine.prototype.setStencilOperationFail = function (operation) {
  12400. this._stencilState.stencilOpStencilFail = operation;
  12401. };
  12402. /**
  12403. * Sets the stencil operation to use when depth fails
  12404. * @param operation defines the stencil operation to use when depth fails
  12405. */
  12406. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12407. this._stencilState.stencilOpDepthFail = operation;
  12408. };
  12409. /**
  12410. * Sets the stencil operation to use when stencil passes
  12411. * @param operation defines the stencil operation to use when stencil passes
  12412. */
  12413. Engine.prototype.setStencilOperationPass = function (operation) {
  12414. this._stencilState.stencilOpStencilDepthPass = operation;
  12415. };
  12416. /**
  12417. * Sets a boolean indicating if the dithering state is enabled or disabled
  12418. * @param value defines the dithering state
  12419. */
  12420. Engine.prototype.setDitheringState = function (value) {
  12421. if (value) {
  12422. this._gl.enable(this._gl.DITHER);
  12423. }
  12424. else {
  12425. this._gl.disable(this._gl.DITHER);
  12426. }
  12427. };
  12428. /**
  12429. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12430. * @param value defines the rasterizer state
  12431. */
  12432. Engine.prototype.setRasterizerState = function (value) {
  12433. if (value) {
  12434. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12435. }
  12436. else {
  12437. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12438. }
  12439. };
  12440. /**
  12441. * stop executing a render loop function and remove it from the execution array
  12442. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12443. */
  12444. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12445. if (!renderFunction) {
  12446. this._activeRenderLoops = [];
  12447. return;
  12448. }
  12449. var index = this._activeRenderLoops.indexOf(renderFunction);
  12450. if (index >= 0) {
  12451. this._activeRenderLoops.splice(index, 1);
  12452. }
  12453. };
  12454. /** @ignore */
  12455. Engine.prototype._renderLoop = function () {
  12456. if (!this._contextWasLost) {
  12457. var shouldRender = true;
  12458. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12459. shouldRender = false;
  12460. }
  12461. if (shouldRender) {
  12462. // Start new frame
  12463. this.beginFrame();
  12464. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12465. var renderFunction = this._activeRenderLoops[index];
  12466. renderFunction();
  12467. }
  12468. // Present
  12469. this.endFrame();
  12470. }
  12471. }
  12472. if (this._activeRenderLoops.length > 0) {
  12473. // Register new frame
  12474. var requester = null;
  12475. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12476. requester = this._vrDisplay;
  12477. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12478. }
  12479. else {
  12480. this._renderingQueueLaunched = false;
  12481. }
  12482. };
  12483. /**
  12484. * Register and execute a render loop. The engine can have more than one render function
  12485. * @param renderFunction defines the function to continuously execute
  12486. */
  12487. Engine.prototype.runRenderLoop = function (renderFunction) {
  12488. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12489. return;
  12490. }
  12491. this._activeRenderLoops.push(renderFunction);
  12492. if (!this._renderingQueueLaunched) {
  12493. this._renderingQueueLaunched = true;
  12494. this._bindedRenderFunction = this._renderLoop.bind(this);
  12495. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12496. }
  12497. };
  12498. /**
  12499. * Toggle full screen mode
  12500. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12501. * @param options defines an option object to be sent to the requestFullscreen function
  12502. */
  12503. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12504. if (this.isFullscreen) {
  12505. BABYLON.Tools.ExitFullscreen();
  12506. }
  12507. else {
  12508. this._pointerLockRequested = requestPointerLock;
  12509. if (this._renderingCanvas) {
  12510. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12511. }
  12512. }
  12513. };
  12514. /**
  12515. * Clear the current render buffer or the current render target (if any is set up)
  12516. * @param color defines the color to use
  12517. * @param backBuffer defines if the back buffer must be cleared
  12518. * @param depth defines if the depth buffer must be cleared
  12519. * @param stencil defines if the stencil buffer must be cleared
  12520. */
  12521. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12522. if (stencil === void 0) { stencil = false; }
  12523. this.applyStates();
  12524. var mode = 0;
  12525. if (backBuffer && color) {
  12526. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12527. mode |= this._gl.COLOR_BUFFER_BIT;
  12528. }
  12529. if (depth) {
  12530. this._gl.clearDepth(1.0);
  12531. mode |= this._gl.DEPTH_BUFFER_BIT;
  12532. }
  12533. if (stencil) {
  12534. this._gl.clearStencil(0);
  12535. mode |= this._gl.STENCIL_BUFFER_BIT;
  12536. }
  12537. this._gl.clear(mode);
  12538. };
  12539. /**
  12540. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12541. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12542. * @param y defines the y-coordinate of the corner of the clear rectangle
  12543. * @param width defines the width of the clear rectangle
  12544. * @param height defines the height of the clear rectangle
  12545. * @param clearColor defines the clear color
  12546. */
  12547. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12548. var gl = this._gl;
  12549. // Save state
  12550. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12551. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12552. // Change state
  12553. gl.enable(gl.SCISSOR_TEST);
  12554. gl.scissor(x, y, width, height);
  12555. // Clear
  12556. this.clear(clearColor, true, true, true);
  12557. // Restore state
  12558. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12559. if (curScissor === true) {
  12560. gl.enable(gl.SCISSOR_TEST);
  12561. }
  12562. else {
  12563. gl.disable(gl.SCISSOR_TEST);
  12564. }
  12565. };
  12566. /**
  12567. * Set the WebGL's viewport
  12568. * @param viewport defines the viewport element to be used
  12569. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12570. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12571. */
  12572. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12573. var width = requiredWidth || this.getRenderWidth();
  12574. var height = requiredHeight || this.getRenderHeight();
  12575. var x = viewport.x || 0;
  12576. var y = viewport.y || 0;
  12577. this._cachedViewport = viewport;
  12578. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12579. };
  12580. /**
  12581. * Directly set the WebGL Viewport
  12582. * @param x defines the x coordinate of the viewport (in screen space)
  12583. * @param y defines the y coordinate of the viewport (in screen space)
  12584. * @param width defines the width of the viewport (in screen space)
  12585. * @param height defines the height of the viewport (in screen space)
  12586. * @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
  12587. */
  12588. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12589. var currentViewport = this._cachedViewport;
  12590. this._cachedViewport = null;
  12591. this._gl.viewport(x, y, width, height);
  12592. return currentViewport;
  12593. };
  12594. /**
  12595. * Begin a new frame
  12596. */
  12597. Engine.prototype.beginFrame = function () {
  12598. this.onBeginFrameObservable.notifyObservers(this);
  12599. this._measureFps();
  12600. };
  12601. /**
  12602. * Enf the current frame
  12603. */
  12604. Engine.prototype.endFrame = function () {
  12605. // Force a flush in case we are using a bad OS.
  12606. if (this._badOS) {
  12607. this.flushFramebuffer();
  12608. }
  12609. // Submit frame to the vr device, if enabled
  12610. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12611. // TODO: We should only submit the frame if we read frameData successfully.
  12612. this._vrDisplay.submitFrame();
  12613. }
  12614. this.onEndFrameObservable.notifyObservers(this);
  12615. };
  12616. /**
  12617. * Resize the view according to the canvas' size
  12618. */
  12619. Engine.prototype.resize = function () {
  12620. // We're not resizing the size of the canvas while in VR mode & presenting
  12621. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12622. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12623. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12624. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12625. }
  12626. };
  12627. /**
  12628. * Force a specific size of the canvas
  12629. * @param width defines the new canvas' width
  12630. * @param height defines the new canvas' height
  12631. */
  12632. Engine.prototype.setSize = function (width, height) {
  12633. if (!this._renderingCanvas) {
  12634. return;
  12635. }
  12636. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12637. return;
  12638. }
  12639. this._renderingCanvas.width = width;
  12640. this._renderingCanvas.height = height;
  12641. for (var index = 0; index < this.scenes.length; index++) {
  12642. var scene = this.scenes[index];
  12643. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12644. var cam = scene.cameras[camIndex];
  12645. cam._currentRenderId = 0;
  12646. }
  12647. }
  12648. if (this.onResizeObservable.hasObservers) {
  12649. this.onResizeObservable.notifyObservers(this);
  12650. }
  12651. };
  12652. // WebVR functions
  12653. /**
  12654. * Gets a boolean indicating if a webVR device was detected
  12655. * @returns true if a webVR device was detected
  12656. */
  12657. Engine.prototype.isVRDevicePresent = function () {
  12658. return !!this._vrDisplay;
  12659. };
  12660. /**
  12661. * Gets the current webVR device
  12662. * @returns the current webVR device (or null)
  12663. */
  12664. Engine.prototype.getVRDevice = function () {
  12665. return this._vrDisplay;
  12666. };
  12667. /**
  12668. * Initializes a webVR display and starts listening to display change events
  12669. * The onVRDisplayChangedObservable will be notified upon these changes
  12670. * @returns The onVRDisplayChangedObservable
  12671. */
  12672. Engine.prototype.initWebVR = function () {
  12673. this.initWebVRAsync();
  12674. return this.onVRDisplayChangedObservable;
  12675. };
  12676. /**
  12677. * Initializes a webVR display and starts listening to display change events
  12678. * The onVRDisplayChangedObservable will be notified upon these changes
  12679. * @returns A promise containing a VRDisplay and if vr is supported
  12680. */
  12681. Engine.prototype.initWebVRAsync = function () {
  12682. var _this = this;
  12683. var notifyObservers = function () {
  12684. var eventArgs = {
  12685. vrDisplay: _this._vrDisplay,
  12686. vrSupported: _this._vrSupported
  12687. };
  12688. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12689. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12690. };
  12691. if (!this._onVrDisplayConnect) {
  12692. this._onVrDisplayConnect = function (event) {
  12693. _this._vrDisplay = event.display;
  12694. notifyObservers();
  12695. };
  12696. this._onVrDisplayDisconnect = function () {
  12697. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12698. _this._vrDisplay = undefined;
  12699. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12700. notifyObservers();
  12701. };
  12702. this._onVrDisplayPresentChange = function () {
  12703. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12704. };
  12705. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12706. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12707. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12708. }
  12709. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12710. this._webVRInitPromise.then(notifyObservers);
  12711. return this._webVRInitPromise;
  12712. };
  12713. /**
  12714. * Call this function to switch to webVR mode
  12715. * Will do nothing if webVR is not supported or if there is no webVR device
  12716. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12717. */
  12718. Engine.prototype.enableVR = function () {
  12719. var _this = this;
  12720. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12721. var onResolved = function () {
  12722. _this.onVRRequestPresentComplete.notifyObservers(true);
  12723. _this._onVRFullScreenTriggered();
  12724. };
  12725. var onRejected = function () {
  12726. _this.onVRRequestPresentComplete.notifyObservers(false);
  12727. };
  12728. this.onVRRequestPresentStart.notifyObservers(this);
  12729. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12730. }
  12731. };
  12732. /**
  12733. * Call this function to leave webVR mode
  12734. * Will do nothing if webVR is not supported or if there is no webVR device
  12735. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12736. */
  12737. Engine.prototype.disableVR = function () {
  12738. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12739. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12740. }
  12741. };
  12742. Engine.prototype._getVRDisplaysAsync = function () {
  12743. var _this = this;
  12744. return new Promise(function (res, rej) {
  12745. if (navigator.getVRDisplays) {
  12746. navigator.getVRDisplays().then(function (devices) {
  12747. _this._vrSupported = true;
  12748. // note that devices may actually be an empty array. This is fine;
  12749. // we expect this._vrDisplay to be undefined in this case.
  12750. _this._vrDisplay = devices[0];
  12751. res({
  12752. vrDisplay: _this._vrDisplay,
  12753. vrSupported: _this._vrSupported
  12754. });
  12755. });
  12756. }
  12757. else {
  12758. _this._vrDisplay = undefined;
  12759. _this._vrSupported = false;
  12760. res({
  12761. vrDisplay: _this._vrDisplay,
  12762. vrSupported: _this._vrSupported
  12763. });
  12764. }
  12765. });
  12766. };
  12767. /**
  12768. * Binds the frame buffer to the specified texture.
  12769. * @param texture The texture to render to or null for the default canvas
  12770. * @param faceIndex The face of the texture to render to in case of cube texture
  12771. * @param requiredWidth The width of the target to render to
  12772. * @param requiredHeight The height of the target to render to
  12773. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12774. * @param depthStencilTexture The depth stencil texture to use to render
  12775. */
  12776. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12777. if (this._currentRenderTarget) {
  12778. this.unBindFramebuffer(this._currentRenderTarget);
  12779. }
  12780. this._currentRenderTarget = texture;
  12781. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12782. var gl = this._gl;
  12783. if (texture.isCube) {
  12784. if (faceIndex === undefined) {
  12785. faceIndex = 0;
  12786. }
  12787. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12788. if (depthStencilTexture) {
  12789. if (depthStencilTexture._generateStencilBuffer) {
  12790. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12791. }
  12792. else {
  12793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12794. }
  12795. }
  12796. }
  12797. if (this._cachedViewport && !forceFullscreenViewport) {
  12798. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12799. }
  12800. else {
  12801. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12802. }
  12803. this.wipeCaches();
  12804. };
  12805. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12806. if (this._currentFramebuffer !== framebuffer) {
  12807. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12808. this._currentFramebuffer = framebuffer;
  12809. }
  12810. };
  12811. /**
  12812. * Unbind the current render target texture from the webGL context
  12813. * @param texture defines the render target texture to unbind
  12814. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12815. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12816. */
  12817. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12818. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12819. this._currentRenderTarget = null;
  12820. // If MSAA, we need to bitblt back to main texture
  12821. var gl = this._gl;
  12822. if (texture._MSAAFramebuffer) {
  12823. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12824. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12825. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12826. }
  12827. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12828. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12829. gl.generateMipmap(gl.TEXTURE_2D);
  12830. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12831. }
  12832. if (onBeforeUnbind) {
  12833. if (texture._MSAAFramebuffer) {
  12834. // Bind the correct framebuffer
  12835. this.bindUnboundFramebuffer(texture._framebuffer);
  12836. }
  12837. onBeforeUnbind();
  12838. }
  12839. this.bindUnboundFramebuffer(null);
  12840. };
  12841. /**
  12842. * Unbind a list of render target textures from the webGL context
  12843. * This is used only when drawBuffer extension or webGL2 are active
  12844. * @param textures defines the render target textures to unbind
  12845. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12846. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12847. */
  12848. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12849. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12850. this._currentRenderTarget = null;
  12851. // If MSAA, we need to bitblt back to main texture
  12852. var gl = this._gl;
  12853. if (textures[0]._MSAAFramebuffer) {
  12854. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12855. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12856. var attachments = textures[0]._attachments;
  12857. if (!attachments) {
  12858. attachments = new Array(textures.length);
  12859. textures[0]._attachments = attachments;
  12860. }
  12861. for (var i = 0; i < textures.length; i++) {
  12862. var texture = textures[i];
  12863. for (var j = 0; j < attachments.length; j++) {
  12864. attachments[j] = gl.NONE;
  12865. }
  12866. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12867. gl.readBuffer(attachments[i]);
  12868. gl.drawBuffers(attachments);
  12869. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12870. }
  12871. for (var i = 0; i < attachments.length; i++) {
  12872. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12873. }
  12874. gl.drawBuffers(attachments);
  12875. }
  12876. for (var i = 0; i < textures.length; i++) {
  12877. var texture = textures[i];
  12878. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12879. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12880. gl.generateMipmap(gl.TEXTURE_2D);
  12881. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12882. }
  12883. }
  12884. if (onBeforeUnbind) {
  12885. if (textures[0]._MSAAFramebuffer) {
  12886. // Bind the correct framebuffer
  12887. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12888. }
  12889. onBeforeUnbind();
  12890. }
  12891. this.bindUnboundFramebuffer(null);
  12892. };
  12893. /**
  12894. * Force the mipmap generation for the given render target texture
  12895. * @param texture defines the render target texture to use
  12896. */
  12897. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12898. if (texture.generateMipMaps) {
  12899. var gl = this._gl;
  12900. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12901. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12902. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12903. }
  12904. };
  12905. /**
  12906. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  12907. */
  12908. Engine.prototype.flushFramebuffer = function () {
  12909. this._gl.flush();
  12910. };
  12911. /**
  12912. * Unbind the current render target and bind the default framebuffer
  12913. */
  12914. Engine.prototype.restoreDefaultFramebuffer = function () {
  12915. if (this._currentRenderTarget) {
  12916. this.unBindFramebuffer(this._currentRenderTarget);
  12917. }
  12918. else {
  12919. this.bindUnboundFramebuffer(null);
  12920. }
  12921. if (this._cachedViewport) {
  12922. this.setViewport(this._cachedViewport);
  12923. }
  12924. this.wipeCaches();
  12925. };
  12926. // UBOs
  12927. /**
  12928. * Create an uniform buffer
  12929. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12930. * @param elements defines the content of the uniform buffer
  12931. * @returns the webGL uniform buffer
  12932. */
  12933. Engine.prototype.createUniformBuffer = function (elements) {
  12934. var ubo = this._gl.createBuffer();
  12935. if (!ubo) {
  12936. throw new Error("Unable to create uniform buffer");
  12937. }
  12938. this.bindUniformBuffer(ubo);
  12939. if (elements instanceof Float32Array) {
  12940. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12941. }
  12942. else {
  12943. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12944. }
  12945. this.bindUniformBuffer(null);
  12946. ubo.references = 1;
  12947. return ubo;
  12948. };
  12949. /**
  12950. * Create a dynamic uniform buffer
  12951. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12952. * @param elements defines the content of the uniform buffer
  12953. * @returns the webGL uniform buffer
  12954. */
  12955. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12956. var ubo = this._gl.createBuffer();
  12957. if (!ubo) {
  12958. throw new Error("Unable to create dynamic uniform buffer");
  12959. }
  12960. this.bindUniformBuffer(ubo);
  12961. if (elements instanceof Float32Array) {
  12962. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12963. }
  12964. else {
  12965. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12966. }
  12967. this.bindUniformBuffer(null);
  12968. ubo.references = 1;
  12969. return ubo;
  12970. };
  12971. /**
  12972. * Update an existing uniform buffer
  12973. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12974. * @param uniformBuffer defines the target uniform buffer
  12975. * @param elements defines the content to update
  12976. * @param offset defines the offset in the uniform buffer where update should start
  12977. * @param count defines the size of the data to update
  12978. */
  12979. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12980. this.bindUniformBuffer(uniformBuffer);
  12981. if (offset === undefined) {
  12982. offset = 0;
  12983. }
  12984. if (count === undefined) {
  12985. if (elements instanceof Float32Array) {
  12986. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12987. }
  12988. else {
  12989. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12990. }
  12991. }
  12992. else {
  12993. if (elements instanceof Float32Array) {
  12994. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12995. }
  12996. else {
  12997. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12998. }
  12999. }
  13000. this.bindUniformBuffer(null);
  13001. };
  13002. // VBOs
  13003. Engine.prototype._resetVertexBufferBinding = function () {
  13004. this.bindArrayBuffer(null);
  13005. this._cachedVertexBuffers = null;
  13006. };
  13007. /**
  13008. * Creates a vertex buffer
  13009. * @param data the data for the vertex buffer
  13010. * @returns the new WebGL static buffer
  13011. */
  13012. Engine.prototype.createVertexBuffer = function (data) {
  13013. var vbo = this._gl.createBuffer();
  13014. if (!vbo) {
  13015. throw new Error("Unable to create vertex buffer");
  13016. }
  13017. this.bindArrayBuffer(vbo);
  13018. if (data instanceof Array) {
  13019. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13020. }
  13021. else {
  13022. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13023. }
  13024. this._resetVertexBufferBinding();
  13025. vbo.references = 1;
  13026. return vbo;
  13027. };
  13028. /**
  13029. * Creates a dynamic vertex buffer
  13030. * @param data the data for the dynamic vertex buffer
  13031. * @returns the new WebGL dynamic buffer
  13032. */
  13033. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13034. var vbo = this._gl.createBuffer();
  13035. if (!vbo) {
  13036. throw new Error("Unable to create dynamic vertex buffer");
  13037. }
  13038. this.bindArrayBuffer(vbo);
  13039. if (data instanceof Array) {
  13040. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13041. }
  13042. else {
  13043. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13044. }
  13045. this._resetVertexBufferBinding();
  13046. vbo.references = 1;
  13047. return vbo;
  13048. };
  13049. /**
  13050. * Update a dynamic index buffer
  13051. * @param indexBuffer defines the target index buffer
  13052. * @param indices defines the data to update
  13053. * @param offset defines the offset in the target index buffer where update should start
  13054. */
  13055. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13056. if (offset === void 0) { offset = 0; }
  13057. // Force cache update
  13058. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13059. this.bindIndexBuffer(indexBuffer);
  13060. var arrayBuffer;
  13061. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13062. arrayBuffer = indices;
  13063. }
  13064. else {
  13065. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13066. }
  13067. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13068. this._resetIndexBufferBinding();
  13069. };
  13070. /**
  13071. * Updates a dynamic vertex buffer.
  13072. * @param vertexBuffer the vertex buffer to update
  13073. * @param data the data used to update the vertex buffer
  13074. * @param byteOffset the byte offset of the data
  13075. * @param byteLength the byte length of the data
  13076. */
  13077. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13078. this.bindArrayBuffer(vertexBuffer);
  13079. if (byteOffset === undefined) {
  13080. byteOffset = 0;
  13081. }
  13082. if (byteLength === undefined) {
  13083. if (data instanceof Array) {
  13084. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13085. }
  13086. else {
  13087. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13088. }
  13089. }
  13090. else {
  13091. if (data instanceof Array) {
  13092. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13093. }
  13094. else {
  13095. if (data instanceof ArrayBuffer) {
  13096. data = new Uint8Array(data, byteOffset, byteLength);
  13097. }
  13098. else {
  13099. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13100. }
  13101. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13102. }
  13103. }
  13104. this._resetVertexBufferBinding();
  13105. };
  13106. Engine.prototype._resetIndexBufferBinding = function () {
  13107. this.bindIndexBuffer(null);
  13108. this._cachedIndexBuffer = null;
  13109. };
  13110. /**
  13111. * Creates a new index buffer
  13112. * @param indices defines the content of the index buffer
  13113. * @param updatable defines if the index buffer must be updatable
  13114. * @returns a new webGL buffer
  13115. */
  13116. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13117. var vbo = this._gl.createBuffer();
  13118. if (!vbo) {
  13119. throw new Error("Unable to create index buffer");
  13120. }
  13121. this.bindIndexBuffer(vbo);
  13122. // Check for 32 bits indices
  13123. var arrayBuffer;
  13124. var need32Bits = false;
  13125. if (indices instanceof Uint16Array) {
  13126. arrayBuffer = indices;
  13127. }
  13128. else {
  13129. //check 32 bit support
  13130. if (this._caps.uintIndices) {
  13131. if (indices instanceof Uint32Array) {
  13132. arrayBuffer = indices;
  13133. need32Bits = true;
  13134. }
  13135. else {
  13136. //number[] or Int32Array, check if 32 bit is necessary
  13137. for (var index = 0; index < indices.length; index++) {
  13138. if (indices[index] > 65535) {
  13139. need32Bits = true;
  13140. break;
  13141. }
  13142. }
  13143. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13144. }
  13145. }
  13146. else {
  13147. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13148. arrayBuffer = new Uint16Array(indices);
  13149. }
  13150. }
  13151. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13152. this._resetIndexBufferBinding();
  13153. vbo.references = 1;
  13154. vbo.is32Bits = need32Bits;
  13155. return vbo;
  13156. };
  13157. /**
  13158. * Bind a webGL buffer to the webGL context
  13159. * @param buffer defines the buffer to bind
  13160. */
  13161. Engine.prototype.bindArrayBuffer = function (buffer) {
  13162. if (!this._vaoRecordInProgress) {
  13163. this._unbindVertexArrayObject();
  13164. }
  13165. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13166. };
  13167. /**
  13168. * Bind an uniform buffer to the current webGL context
  13169. * @param buffer defines the buffer to bind
  13170. */
  13171. Engine.prototype.bindUniformBuffer = function (buffer) {
  13172. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13173. };
  13174. /**
  13175. * Bind a buffer to the current webGL context at a given location
  13176. * @param buffer defines the buffer to bind
  13177. * @param location defines the index where to bind the buffer
  13178. */
  13179. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13180. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13181. };
  13182. /**
  13183. * Bind a specific block at a given index in a specific shader program
  13184. * @param shaderProgram defines the shader program
  13185. * @param blockName defines the block name
  13186. * @param index defines the index where to bind the block
  13187. */
  13188. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13189. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13190. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13191. };
  13192. ;
  13193. Engine.prototype.bindIndexBuffer = function (buffer) {
  13194. if (!this._vaoRecordInProgress) {
  13195. this._unbindVertexArrayObject();
  13196. }
  13197. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13198. };
  13199. Engine.prototype.bindBuffer = function (buffer, target) {
  13200. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13201. this._gl.bindBuffer(target, buffer);
  13202. this._currentBoundBuffer[target] = buffer;
  13203. }
  13204. };
  13205. /**
  13206. * update the bound buffer with the given data
  13207. * @param data defines the data to update
  13208. */
  13209. Engine.prototype.updateArrayBuffer = function (data) {
  13210. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13211. };
  13212. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13213. var pointer = this._currentBufferPointers[indx];
  13214. var changed = false;
  13215. if (!pointer.active) {
  13216. changed = true;
  13217. pointer.active = true;
  13218. pointer.index = indx;
  13219. pointer.size = size;
  13220. pointer.type = type;
  13221. pointer.normalized = normalized;
  13222. pointer.stride = stride;
  13223. pointer.offset = offset;
  13224. pointer.buffer = buffer;
  13225. }
  13226. else {
  13227. if (pointer.buffer !== buffer) {
  13228. pointer.buffer = buffer;
  13229. changed = true;
  13230. }
  13231. if (pointer.size !== size) {
  13232. pointer.size = size;
  13233. changed = true;
  13234. }
  13235. if (pointer.type !== type) {
  13236. pointer.type = type;
  13237. changed = true;
  13238. }
  13239. if (pointer.normalized !== normalized) {
  13240. pointer.normalized = normalized;
  13241. changed = true;
  13242. }
  13243. if (pointer.stride !== stride) {
  13244. pointer.stride = stride;
  13245. changed = true;
  13246. }
  13247. if (pointer.offset !== offset) {
  13248. pointer.offset = offset;
  13249. changed = true;
  13250. }
  13251. }
  13252. if (changed || this._vaoRecordInProgress) {
  13253. this.bindArrayBuffer(buffer);
  13254. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13255. }
  13256. };
  13257. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13258. if (indexBuffer == null) {
  13259. return;
  13260. }
  13261. if (this._cachedIndexBuffer !== indexBuffer) {
  13262. this._cachedIndexBuffer = indexBuffer;
  13263. this.bindIndexBuffer(indexBuffer);
  13264. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13265. }
  13266. };
  13267. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13268. var attributes = effect.getAttributesNames();
  13269. if (!this._vaoRecordInProgress) {
  13270. this._unbindVertexArrayObject();
  13271. }
  13272. this.unbindAllAttributes();
  13273. for (var index = 0; index < attributes.length; index++) {
  13274. var order = effect.getAttributeLocation(index);
  13275. if (order >= 0) {
  13276. var vertexBuffer = vertexBuffers[attributes[index]];
  13277. if (!vertexBuffer) {
  13278. continue;
  13279. }
  13280. this._gl.enableVertexAttribArray(order);
  13281. if (!this._vaoRecordInProgress) {
  13282. this._vertexAttribArraysEnabled[order] = true;
  13283. }
  13284. var buffer = vertexBuffer.getBuffer();
  13285. if (buffer) {
  13286. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13287. if (vertexBuffer.getIsInstanced()) {
  13288. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13289. if (!this._vaoRecordInProgress) {
  13290. this._currentInstanceLocations.push(order);
  13291. this._currentInstanceBuffers.push(buffer);
  13292. }
  13293. }
  13294. }
  13295. }
  13296. }
  13297. };
  13298. /**
  13299. * Records a vertex array object
  13300. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13301. * @param vertexBuffers defines the list of vertex buffers to store
  13302. * @param indexBuffer defines the index buffer to store
  13303. * @param effect defines the effect to store
  13304. * @returns the new vertex array object
  13305. */
  13306. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13307. var vao = this._gl.createVertexArray();
  13308. this._vaoRecordInProgress = true;
  13309. this._gl.bindVertexArray(vao);
  13310. this._mustWipeVertexAttributes = true;
  13311. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13312. this.bindIndexBuffer(indexBuffer);
  13313. this._vaoRecordInProgress = false;
  13314. this._gl.bindVertexArray(null);
  13315. return vao;
  13316. };
  13317. /**
  13318. * Bind a specific vertex array object
  13319. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13320. * @param vertexArrayObject defines the vertex array object to bind
  13321. * @param indexBuffer defines the index buffer to bind
  13322. */
  13323. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13324. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13325. this._cachedVertexArrayObject = vertexArrayObject;
  13326. this._gl.bindVertexArray(vertexArrayObject);
  13327. this._cachedVertexBuffers = null;
  13328. this._cachedIndexBuffer = null;
  13329. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13330. this._mustWipeVertexAttributes = true;
  13331. }
  13332. };
  13333. /**
  13334. * Bind webGl buffers directly to the webGL context
  13335. * @param vertexBuffer defines the vertex buffer to bind
  13336. * @param indexBuffer defines the index buffer to bind
  13337. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13338. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13339. * @param effect defines the effect associated with the vertex buffer
  13340. */
  13341. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13342. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13343. this._cachedVertexBuffers = vertexBuffer;
  13344. this._cachedEffectForVertexBuffers = effect;
  13345. var attributesCount = effect.getAttributesCount();
  13346. this._unbindVertexArrayObject();
  13347. this.unbindAllAttributes();
  13348. var offset = 0;
  13349. for (var index = 0; index < attributesCount; index++) {
  13350. if (index < vertexDeclaration.length) {
  13351. var order = effect.getAttributeLocation(index);
  13352. if (order >= 0) {
  13353. this._gl.enableVertexAttribArray(order);
  13354. this._vertexAttribArraysEnabled[order] = true;
  13355. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13356. }
  13357. offset += vertexDeclaration[index] * 4;
  13358. }
  13359. }
  13360. }
  13361. this._bindIndexBufferWithCache(indexBuffer);
  13362. };
  13363. Engine.prototype._unbindVertexArrayObject = function () {
  13364. if (!this._cachedVertexArrayObject) {
  13365. return;
  13366. }
  13367. this._cachedVertexArrayObject = null;
  13368. this._gl.bindVertexArray(null);
  13369. };
  13370. /**
  13371. * Bind a list of vertex buffers to the webGL context
  13372. * @param vertexBuffers defines the list of vertex buffers to bind
  13373. * @param indexBuffer defines the index buffer to bind
  13374. * @param effect defines the effect associated with the vertex buffers
  13375. */
  13376. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13377. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13378. this._cachedVertexBuffers = vertexBuffers;
  13379. this._cachedEffectForVertexBuffers = effect;
  13380. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13381. }
  13382. this._bindIndexBufferWithCache(indexBuffer);
  13383. };
  13384. /**
  13385. * Unbind all instance attributes
  13386. */
  13387. Engine.prototype.unbindInstanceAttributes = function () {
  13388. var boundBuffer;
  13389. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13390. var instancesBuffer = this._currentInstanceBuffers[i];
  13391. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13392. boundBuffer = instancesBuffer;
  13393. this.bindArrayBuffer(instancesBuffer);
  13394. }
  13395. var offsetLocation = this._currentInstanceLocations[i];
  13396. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13397. }
  13398. this._currentInstanceBuffers.length = 0;
  13399. this._currentInstanceLocations.length = 0;
  13400. };
  13401. /**
  13402. * Release and free the memory of a vertex array object
  13403. * @param vao defines the vertex array object to delete
  13404. */
  13405. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13406. this._gl.deleteVertexArray(vao);
  13407. };
  13408. /** @ignore */
  13409. Engine.prototype._releaseBuffer = function (buffer) {
  13410. buffer.references--;
  13411. if (buffer.references === 0) {
  13412. this._gl.deleteBuffer(buffer);
  13413. return true;
  13414. }
  13415. return false;
  13416. };
  13417. /**
  13418. * Creates a webGL buffer to use with instanciation
  13419. * @param capacity defines the size of the buffer
  13420. * @returns the webGL buffer
  13421. */
  13422. Engine.prototype.createInstancesBuffer = function (capacity) {
  13423. var buffer = this._gl.createBuffer();
  13424. if (!buffer) {
  13425. throw new Error("Unable to create instance buffer");
  13426. }
  13427. buffer.capacity = capacity;
  13428. this.bindArrayBuffer(buffer);
  13429. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13430. return buffer;
  13431. };
  13432. /**
  13433. * Delete a webGL buffer used with instanciation
  13434. * @param buffer defines the webGL buffer to delete
  13435. */
  13436. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13437. this._gl.deleteBuffer(buffer);
  13438. };
  13439. /**
  13440. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13441. * @param instancesBuffer defines the webGL buffer to update and bind
  13442. * @param data defines the data to store in the buffer
  13443. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13444. */
  13445. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13446. this.bindArrayBuffer(instancesBuffer);
  13447. if (data) {
  13448. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13449. }
  13450. if (offsetLocations[0].index !== undefined) {
  13451. var stride = 0;
  13452. for (var i = 0; i < offsetLocations.length; i++) {
  13453. var ai = offsetLocations[i];
  13454. stride += ai.attributeSize * 4;
  13455. }
  13456. for (var i = 0; i < offsetLocations.length; i++) {
  13457. var ai = offsetLocations[i];
  13458. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13459. this._gl.enableVertexAttribArray(ai.index);
  13460. this._vertexAttribArraysEnabled[ai.index] = true;
  13461. }
  13462. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13463. this._gl.vertexAttribDivisor(ai.index, 1);
  13464. this._currentInstanceLocations.push(ai.index);
  13465. this._currentInstanceBuffers.push(instancesBuffer);
  13466. }
  13467. }
  13468. else {
  13469. for (var index = 0; index < 4; index++) {
  13470. var offsetLocation = offsetLocations[index];
  13471. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13472. this._gl.enableVertexAttribArray(offsetLocation);
  13473. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13474. }
  13475. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13476. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13477. this._currentInstanceLocations.push(offsetLocation);
  13478. this._currentInstanceBuffers.push(instancesBuffer);
  13479. }
  13480. }
  13481. };
  13482. /**
  13483. * Apply all cached states (depth, culling, stencil and alpha)
  13484. */
  13485. Engine.prototype.applyStates = function () {
  13486. this._depthCullingState.apply(this._gl);
  13487. this._stencilState.apply(this._gl);
  13488. this._alphaState.apply(this._gl);
  13489. };
  13490. /**
  13491. * Send a draw order
  13492. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13493. * @param indexStart defines the starting index
  13494. * @param indexCount defines the number of index to draw
  13495. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13496. */
  13497. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13498. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13499. };
  13500. /**
  13501. * Draw a list of points
  13502. * @param verticesStart defines the index of first vertex to draw
  13503. * @param verticesCount defines the count of vertices to draw
  13504. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13505. */
  13506. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13507. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13508. };
  13509. /**
  13510. * Draw a list of unindexed primitives
  13511. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13512. * @param verticesStart defines the index of first vertex to draw
  13513. * @param verticesCount defines the count of vertices to draw
  13514. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13515. */
  13516. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13517. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13518. };
  13519. /**
  13520. * Draw a list of indexed primitives
  13521. * @param fillMode defines the primitive to use
  13522. * @param indexStart defines the starting index
  13523. * @param indexCount defines the number of index to draw
  13524. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13525. */
  13526. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13527. // Apply states
  13528. this.applyStates();
  13529. this._drawCalls.addCount(1, false);
  13530. // Render
  13531. var drawMode = this._drawMode(fillMode);
  13532. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13533. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13534. if (instancesCount) {
  13535. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13536. }
  13537. else {
  13538. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13539. }
  13540. };
  13541. /**
  13542. * Draw a list of unindexed primitives
  13543. * @param fillMode defines the primitive to use
  13544. * @param verticesStart defines the index of first vertex to draw
  13545. * @param verticesCount defines the count of vertices to draw
  13546. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13547. */
  13548. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13549. // Apply states
  13550. this.applyStates();
  13551. this._drawCalls.addCount(1, false);
  13552. var drawMode = this._drawMode(fillMode);
  13553. if (instancesCount) {
  13554. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13555. }
  13556. else {
  13557. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13558. }
  13559. };
  13560. Engine.prototype._drawMode = function (fillMode) {
  13561. switch (fillMode) {
  13562. // Triangle views
  13563. case BABYLON.Material.TriangleFillMode:
  13564. return this._gl.TRIANGLES;
  13565. case BABYLON.Material.PointFillMode:
  13566. return this._gl.POINTS;
  13567. case BABYLON.Material.WireFrameFillMode:
  13568. return this._gl.LINES;
  13569. // Draw modes
  13570. case BABYLON.Material.PointListDrawMode:
  13571. return this._gl.POINTS;
  13572. case BABYLON.Material.LineListDrawMode:
  13573. return this._gl.LINES;
  13574. case BABYLON.Material.LineLoopDrawMode:
  13575. return this._gl.LINE_LOOP;
  13576. case BABYLON.Material.LineStripDrawMode:
  13577. return this._gl.LINE_STRIP;
  13578. case BABYLON.Material.TriangleStripDrawMode:
  13579. return this._gl.TRIANGLE_STRIP;
  13580. case BABYLON.Material.TriangleFanDrawMode:
  13581. return this._gl.TRIANGLE_FAN;
  13582. default:
  13583. return this._gl.TRIANGLES;
  13584. }
  13585. };
  13586. // Shaders
  13587. /** @ignore */
  13588. Engine.prototype._releaseEffect = function (effect) {
  13589. if (this._compiledEffects[effect._key]) {
  13590. delete this._compiledEffects[effect._key];
  13591. this._deleteProgram(effect.getProgram());
  13592. }
  13593. };
  13594. /** @ignore */
  13595. Engine.prototype._deleteProgram = function (program) {
  13596. if (program) {
  13597. program.__SPECTOR_rebuildProgram = null;
  13598. if (program.transformFeedback) {
  13599. this.deleteTransformFeedback(program.transformFeedback);
  13600. program.transformFeedback = null;
  13601. }
  13602. this._gl.deleteProgram(program);
  13603. }
  13604. };
  13605. /**
  13606. * Create a new effect (used to store vertex/fragment shaders)
  13607. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13608. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13609. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13610. * @param samplers defines an array of string used to represent textures
  13611. * @param defines defines the string containing the defines to use to compile the shaders
  13612. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13613. * @param onCompiled defines a function to call when the effect creation is successful
  13614. * @param onError defines a function to call when the effect creation has failed
  13615. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13616. * @returns the new Effect
  13617. */
  13618. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13619. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13620. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13621. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13622. if (this._compiledEffects[name]) {
  13623. var compiledEffect = this._compiledEffects[name];
  13624. if (onCompiled && compiledEffect.isReady()) {
  13625. onCompiled(compiledEffect);
  13626. }
  13627. return compiledEffect;
  13628. }
  13629. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13630. effect._key = name;
  13631. this._compiledEffects[name] = effect;
  13632. return effect;
  13633. };
  13634. /**
  13635. * Create an effect to use with particle systems
  13636. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13637. * @param uniformsNames defines a list of attribute names
  13638. * @param samplers defines an array of string used to represent textures
  13639. * @param defines defines the string containing the defines to use to compile the shaders
  13640. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13641. * @param onCompiled defines a function to call when the effect creation is successful
  13642. * @param onError defines a function to call when the effect creation has failed
  13643. * @returns the new Effect
  13644. */
  13645. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13646. if (uniformsNames === void 0) { uniformsNames = []; }
  13647. if (samplers === void 0) { samplers = []; }
  13648. if (defines === void 0) { defines = ""; }
  13649. return this.createEffect({
  13650. vertex: "particles",
  13651. fragmentElement: fragmentName
  13652. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13653. };
  13654. /**
  13655. * Directly creates a webGL program
  13656. * @param vertexCode defines the vertex shader code to use
  13657. * @param fragmentCode defines the fragment shader code to use
  13658. * @param context defines the webGL context to use (if not set, the current one will be used)
  13659. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13660. * @returns the new webGL program
  13661. */
  13662. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13663. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13664. context = context || this._gl;
  13665. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13666. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13667. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13668. };
  13669. /**
  13670. * Creates a webGL program
  13671. * @param vertexCode defines the vertex shader code to use
  13672. * @param fragmentCode defines the fragment shader code to use
  13673. * @param defines defines the string containing the defines to use to compile the shaders
  13674. * @param context defines the webGL context to use (if not set, the current one will be used)
  13675. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13676. * @returns the new webGL program
  13677. */
  13678. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13679. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13680. context = context || this._gl;
  13681. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13682. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13683. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13684. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13685. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13686. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13687. return program;
  13688. };
  13689. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13690. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13691. var shaderProgram = context.createProgram();
  13692. if (!shaderProgram) {
  13693. throw new Error("Unable to create program");
  13694. }
  13695. context.attachShader(shaderProgram, vertexShader);
  13696. context.attachShader(shaderProgram, fragmentShader);
  13697. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13698. var transformFeedback = this.createTransformFeedback();
  13699. this.bindTransformFeedback(transformFeedback);
  13700. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13701. shaderProgram.transformFeedback = transformFeedback;
  13702. }
  13703. context.linkProgram(shaderProgram);
  13704. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13705. this.bindTransformFeedback(null);
  13706. }
  13707. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13708. if (!linked) {
  13709. context.validateProgram(shaderProgram);
  13710. var error = context.getProgramInfoLog(shaderProgram);
  13711. if (error) {
  13712. throw new Error(error);
  13713. }
  13714. }
  13715. context.deleteShader(vertexShader);
  13716. context.deleteShader(fragmentShader);
  13717. return shaderProgram;
  13718. };
  13719. /**
  13720. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13721. * @param shaderProgram defines the webGL program to use
  13722. * @param uniformsNames defines the list of uniform names
  13723. * @returns an array of webGL uniform locations
  13724. */
  13725. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13726. var results = new Array();
  13727. for (var index = 0; index < uniformsNames.length; index++) {
  13728. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13729. }
  13730. return results;
  13731. };
  13732. /**
  13733. * Gets the lsit of active attributes for a given webGL program
  13734. * @param shaderProgram defines the webGL program to use
  13735. * @param attributesNames defines the list of attribute names to get
  13736. * @returns an array of indices indicating the offset of each attribute
  13737. */
  13738. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13739. var results = [];
  13740. for (var index = 0; index < attributesNames.length; index++) {
  13741. try {
  13742. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13743. }
  13744. catch (e) {
  13745. results.push(-1);
  13746. }
  13747. }
  13748. return results;
  13749. };
  13750. /**
  13751. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13752. * @param effect defines the effect to activate
  13753. */
  13754. Engine.prototype.enableEffect = function (effect) {
  13755. if (!effect) {
  13756. return;
  13757. }
  13758. // Use program
  13759. this.bindSamplers(effect);
  13760. this._currentEffect = effect;
  13761. if (effect.onBind) {
  13762. effect.onBind(effect);
  13763. }
  13764. effect.onBindObservable.notifyObservers(effect);
  13765. };
  13766. /**
  13767. * Set the value of an uniform to an array of int32
  13768. * @param uniform defines the webGL uniform location where to store the value
  13769. * @param array defines the array of int32 to store
  13770. */
  13771. Engine.prototype.setIntArray = function (uniform, array) {
  13772. if (!uniform)
  13773. return;
  13774. this._gl.uniform1iv(uniform, array);
  13775. };
  13776. /**
  13777. * Set the value of an uniform to an array of int32 (stored as vec2)
  13778. * @param uniform defines the webGL uniform location where to store the value
  13779. * @param array defines the array of int32 to store
  13780. */
  13781. Engine.prototype.setIntArray2 = function (uniform, array) {
  13782. if (!uniform || array.length % 2 !== 0)
  13783. return;
  13784. this._gl.uniform2iv(uniform, array);
  13785. };
  13786. /**
  13787. * Set the value of an uniform to an array of int32 (stored as vec3)
  13788. * @param uniform defines the webGL uniform location where to store the value
  13789. * @param array defines the array of int32 to store
  13790. */
  13791. Engine.prototype.setIntArray3 = function (uniform, array) {
  13792. if (!uniform || array.length % 3 !== 0)
  13793. return;
  13794. this._gl.uniform3iv(uniform, array);
  13795. };
  13796. /**
  13797. * Set the value of an uniform to an array of int32 (stored as vec4)
  13798. * @param uniform defines the webGL uniform location where to store the value
  13799. * @param array defines the array of int32 to store
  13800. */
  13801. Engine.prototype.setIntArray4 = function (uniform, array) {
  13802. if (!uniform || array.length % 4 !== 0)
  13803. return;
  13804. this._gl.uniform4iv(uniform, array);
  13805. };
  13806. /**
  13807. * Set the value of an uniform to an array of float32
  13808. * @param uniform defines the webGL uniform location where to store the value
  13809. * @param array defines the array of float32 to store
  13810. */
  13811. Engine.prototype.setFloatArray = function (uniform, array) {
  13812. if (!uniform)
  13813. return;
  13814. this._gl.uniform1fv(uniform, array);
  13815. };
  13816. /**
  13817. * Set the value of an uniform to an array of float32 (stored as vec2)
  13818. * @param uniform defines the webGL uniform location where to store the value
  13819. * @param array defines the array of float32 to store
  13820. */
  13821. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13822. if (!uniform || array.length % 2 !== 0)
  13823. return;
  13824. this._gl.uniform2fv(uniform, array);
  13825. };
  13826. /**
  13827. * Set the value of an uniform to an array of float32 (stored as vec3)
  13828. * @param uniform defines the webGL uniform location where to store the value
  13829. * @param array defines the array of float32 to store
  13830. */
  13831. Engine.prototype.setFloatArray3 = function (uniform, array) {
  13832. if (!uniform || array.length % 3 !== 0)
  13833. return;
  13834. this._gl.uniform3fv(uniform, array);
  13835. };
  13836. /**
  13837. * Set the value of an uniform to an array of float32 (stored as vec4)
  13838. * @param uniform defines the webGL uniform location where to store the value
  13839. * @param array defines the array of float32 to store
  13840. */
  13841. Engine.prototype.setFloatArray4 = function (uniform, array) {
  13842. if (!uniform || array.length % 4 !== 0)
  13843. return;
  13844. this._gl.uniform4fv(uniform, array);
  13845. };
  13846. /**
  13847. * Set the value of an uniform to an array of number
  13848. * @param uniform defines the webGL uniform location where to store the value
  13849. * @param array defines the array of number to store
  13850. */
  13851. Engine.prototype.setArray = function (uniform, array) {
  13852. if (!uniform)
  13853. return;
  13854. this._gl.uniform1fv(uniform, array);
  13855. };
  13856. /**
  13857. * Set the value of an uniform to an array of number (stored as vec2)
  13858. * @param uniform defines the webGL uniform location where to store the value
  13859. * @param array defines the array of number to store
  13860. */
  13861. Engine.prototype.setArray2 = function (uniform, array) {
  13862. if (!uniform || array.length % 2 !== 0)
  13863. return;
  13864. this._gl.uniform2fv(uniform, array);
  13865. };
  13866. /**
  13867. * Set the value of an uniform to an array of number (stored as vec3)
  13868. * @param uniform defines the webGL uniform location where to store the value
  13869. * @param array defines the array of number to store
  13870. */
  13871. Engine.prototype.setArray3 = function (uniform, array) {
  13872. if (!uniform || array.length % 3 !== 0)
  13873. return;
  13874. this._gl.uniform3fv(uniform, array);
  13875. };
  13876. /**
  13877. * Set the value of an uniform to an array of number (stored as vec4)
  13878. * @param uniform defines the webGL uniform location where to store the value
  13879. * @param array defines the array of number to store
  13880. */
  13881. Engine.prototype.setArray4 = function (uniform, array) {
  13882. if (!uniform || array.length % 4 !== 0)
  13883. return;
  13884. this._gl.uniform4fv(uniform, array);
  13885. };
  13886. /**
  13887. * Set the value of an uniform to an array of float32 (stored as matrices)
  13888. * @param uniform defines the webGL uniform location where to store the value
  13889. * @param matrices defines the array of float32 to store
  13890. */
  13891. Engine.prototype.setMatrices = function (uniform, matrices) {
  13892. if (!uniform)
  13893. return;
  13894. this._gl.uniformMatrix4fv(uniform, false, matrices);
  13895. };
  13896. /**
  13897. * Set the value of an uniform to a matrix
  13898. * @param uniform defines the webGL uniform location where to store the value
  13899. * @param matrix defines the matrix to store
  13900. */
  13901. Engine.prototype.setMatrix = function (uniform, matrix) {
  13902. if (!uniform)
  13903. return;
  13904. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  13905. };
  13906. /**
  13907. * Set the value of an uniform to a matrix (3x3)
  13908. * @param uniform defines the webGL uniform location where to store the value
  13909. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  13910. */
  13911. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  13912. if (!uniform)
  13913. return;
  13914. this._gl.uniformMatrix3fv(uniform, false, matrix);
  13915. };
  13916. /**
  13917. * Set the value of an uniform to a matrix (2x2)
  13918. * @param uniform defines the webGL uniform location where to store the value
  13919. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  13920. */
  13921. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  13922. if (!uniform)
  13923. return;
  13924. this._gl.uniformMatrix2fv(uniform, false, matrix);
  13925. };
  13926. /**
  13927. * Set the value of an uniform to a number (int)
  13928. * @param uniform defines the webGL uniform location where to store the value
  13929. * @param value defines the int number to store
  13930. */
  13931. Engine.prototype.setInt = function (uniform, value) {
  13932. if (!uniform)
  13933. return;
  13934. this._gl.uniform1i(uniform, value);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to a number (float)
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param value defines the float number to store
  13940. */
  13941. Engine.prototype.setFloat = function (uniform, value) {
  13942. if (!uniform)
  13943. return;
  13944. this._gl.uniform1f(uniform, value);
  13945. };
  13946. /**
  13947. * Set the value of an uniform to a vec2
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param x defines the 1st component of the value
  13950. * @param y defines the 2nd component of the value
  13951. */
  13952. Engine.prototype.setFloat2 = function (uniform, x, y) {
  13953. if (!uniform)
  13954. return;
  13955. this._gl.uniform2f(uniform, x, y);
  13956. };
  13957. /**
  13958. * Set the value of an uniform to a vec3
  13959. * @param uniform defines the webGL uniform location where to store the value
  13960. * @param x defines the 1st component of the value
  13961. * @param y defines the 2nd component of the value
  13962. * @param z defines the 3rd component of the value
  13963. */
  13964. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  13965. if (!uniform)
  13966. return;
  13967. this._gl.uniform3f(uniform, x, y, z);
  13968. };
  13969. /**
  13970. * Set the value of an uniform to a boolean
  13971. * @param uniform defines the webGL uniform location where to store the value
  13972. * @param bool defines the boolean to store
  13973. */
  13974. Engine.prototype.setBool = function (uniform, bool) {
  13975. if (!uniform)
  13976. return;
  13977. this._gl.uniform1i(uniform, bool);
  13978. };
  13979. /**
  13980. * Set the value of an uniform to a vec4
  13981. * @param uniform defines the webGL uniform location where to store the value
  13982. * @param x defines the 1st component of the value
  13983. * @param y defines the 2nd component of the value
  13984. * @param z defines the 3rd component of the value
  13985. * @param w defines the 4th component of the value
  13986. */
  13987. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  13988. if (!uniform)
  13989. return;
  13990. this._gl.uniform4f(uniform, x, y, z, w);
  13991. };
  13992. /**
  13993. * Set the value of an uniform to a Color3
  13994. * @param uniform defines the webGL uniform location where to store the value
  13995. * @param color3 defines the color to store
  13996. */
  13997. Engine.prototype.setColor3 = function (uniform, color3) {
  13998. if (!uniform)
  13999. return;
  14000. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14001. };
  14002. /**
  14003. * Set the value of an uniform to a Color3 and an alpha value
  14004. * @param uniform defines the webGL uniform location where to store the value
  14005. * @param color3 defines the color to store
  14006. * @param alpha defines the alpha component to store
  14007. */
  14008. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14009. if (!uniform)
  14010. return;
  14011. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14012. };
  14013. /**
  14014. * Sets a Color4 on a uniform variable
  14015. * @param uniform defines the uniform location
  14016. * @param color4 defines the value to be set
  14017. */
  14018. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14019. if (!uniform)
  14020. return;
  14021. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14022. };
  14023. // States
  14024. /**
  14025. * Set various states to the webGL context
  14026. * @param culling defines backface culling state
  14027. * @param zOffset defines the value to apply to zOffset (0 by default)
  14028. * @param force defines if states must be applied even if cache is up to date
  14029. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14030. */
  14031. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14032. if (zOffset === void 0) { zOffset = 0; }
  14033. if (reverseSide === void 0) { reverseSide = false; }
  14034. // Culling
  14035. if (this._depthCullingState.cull !== culling || force) {
  14036. this._depthCullingState.cull = culling;
  14037. }
  14038. // Cull face
  14039. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14040. if (this._depthCullingState.cullFace !== cullFace || force) {
  14041. this._depthCullingState.cullFace = cullFace;
  14042. }
  14043. // Z offset
  14044. this.setZOffset(zOffset);
  14045. // Front face
  14046. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14047. if (this._depthCullingState.frontFace !== frontFace || force) {
  14048. this._depthCullingState.frontFace = frontFace;
  14049. }
  14050. };
  14051. /**
  14052. * Set the z offset to apply to current rendering
  14053. * @param value defines the offset to apply
  14054. */
  14055. Engine.prototype.setZOffset = function (value) {
  14056. this._depthCullingState.zOffset = value;
  14057. };
  14058. /**
  14059. * Gets the current value of the zOffset
  14060. * @returns the current zOffset state
  14061. */
  14062. Engine.prototype.getZOffset = function () {
  14063. return this._depthCullingState.zOffset;
  14064. };
  14065. /**
  14066. * Enable or disable depth buffering
  14067. * @param enable defines the state to set
  14068. */
  14069. Engine.prototype.setDepthBuffer = function (enable) {
  14070. this._depthCullingState.depthTest = enable;
  14071. };
  14072. /**
  14073. * Gets a boolean indicating if depth writing is enabled
  14074. * @returns the current depth writing state
  14075. */
  14076. Engine.prototype.getDepthWrite = function () {
  14077. return this._depthCullingState.depthMask;
  14078. };
  14079. /**
  14080. * Enable or disable depth writing
  14081. * @param enable defines the state to set
  14082. */
  14083. Engine.prototype.setDepthWrite = function (enable) {
  14084. this._depthCullingState.depthMask = enable;
  14085. };
  14086. /**
  14087. * Enable or disable color writing
  14088. * @param enable defines the state to set
  14089. */
  14090. Engine.prototype.setColorWrite = function (enable) {
  14091. this._gl.colorMask(enable, enable, enable, enable);
  14092. this._colorWrite = enable;
  14093. };
  14094. /**
  14095. * Gets a boolean indicating if color writing is enabled
  14096. * @returns the current color writing state
  14097. */
  14098. Engine.prototype.getColorWrite = function () {
  14099. return this._colorWrite;
  14100. };
  14101. /**
  14102. * Sets alpha constants used by some alpha blending modes
  14103. * @param r defines the red component
  14104. * @param g defines the green component
  14105. * @param b defines the blue component
  14106. * @param a defines the alpha component
  14107. */
  14108. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14109. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14110. };
  14111. /**
  14112. * Sets the current alpha mode
  14113. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14114. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14115. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14116. */
  14117. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14118. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14119. if (this._alphaMode === mode) {
  14120. return;
  14121. }
  14122. switch (mode) {
  14123. case Engine.ALPHA_DISABLE:
  14124. this._alphaState.alphaBlend = false;
  14125. break;
  14126. case Engine.ALPHA_PREMULTIPLIED:
  14127. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14128. this._alphaState.alphaBlend = true;
  14129. break;
  14130. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14131. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14132. this._alphaState.alphaBlend = true;
  14133. break;
  14134. case Engine.ALPHA_COMBINE:
  14135. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14136. this._alphaState.alphaBlend = true;
  14137. break;
  14138. case Engine.ALPHA_ONEONE:
  14139. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14140. this._alphaState.alphaBlend = true;
  14141. break;
  14142. case Engine.ALPHA_ADD:
  14143. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14144. this._alphaState.alphaBlend = true;
  14145. break;
  14146. case Engine.ALPHA_SUBTRACT:
  14147. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14148. this._alphaState.alphaBlend = true;
  14149. break;
  14150. case Engine.ALPHA_MULTIPLY:
  14151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14152. this._alphaState.alphaBlend = true;
  14153. break;
  14154. case Engine.ALPHA_MAXIMIZED:
  14155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14156. this._alphaState.alphaBlend = true;
  14157. break;
  14158. case Engine.ALPHA_INTERPOLATE:
  14159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14160. this._alphaState.alphaBlend = true;
  14161. break;
  14162. case Engine.ALPHA_SCREENMODE:
  14163. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14164. this._alphaState.alphaBlend = true;
  14165. break;
  14166. }
  14167. if (!noDepthWriteChange) {
  14168. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14169. }
  14170. this._alphaMode = mode;
  14171. };
  14172. /**
  14173. * Gets the current alpha mode
  14174. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14175. * @returns the current alpha mode
  14176. */
  14177. Engine.prototype.getAlphaMode = function () {
  14178. return this._alphaMode;
  14179. };
  14180. // Textures
  14181. /**
  14182. * Force the entire cache to be cleared
  14183. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14184. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14185. */
  14186. Engine.prototype.wipeCaches = function (bruteForce) {
  14187. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14188. return;
  14189. }
  14190. this._currentEffect = null;
  14191. if (bruteForce) {
  14192. this.resetTextureCache();
  14193. this._currentProgram = null;
  14194. this._stencilState.reset();
  14195. this._depthCullingState.reset();
  14196. this.setDepthFunctionToLessOrEqual();
  14197. this._alphaState.reset();
  14198. }
  14199. this._resetVertexBufferBinding();
  14200. this._cachedIndexBuffer = null;
  14201. this._cachedEffectForVertexBuffers = null;
  14202. this._unbindVertexArrayObject();
  14203. this.bindIndexBuffer(null);
  14204. };
  14205. /**
  14206. * Set the compressed texture format to use, based on the formats you have, and the formats
  14207. * supported by the hardware / browser.
  14208. *
  14209. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14210. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14211. * to API arguments needed to compressed textures. This puts the burden on the container
  14212. * generator to house the arcane code for determining these for current & future formats.
  14213. *
  14214. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14215. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14216. *
  14217. * Note: The result of this call is not taken into account when a texture is base64.
  14218. *
  14219. * @param formatsAvailable defines the list of those format families you have created
  14220. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14221. *
  14222. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14223. * @returns The extension selected.
  14224. */
  14225. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14226. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14227. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14228. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14229. return this._textureFormatInUse = this._texturesSupported[i];
  14230. }
  14231. }
  14232. }
  14233. // actively set format to nothing, to allow this to be called more than once
  14234. // and possibly fail the 2nd time
  14235. this._textureFormatInUse = null;
  14236. return null;
  14237. };
  14238. /** @ignore */
  14239. Engine.prototype._createTexture = function () {
  14240. var texture = this._gl.createTexture();
  14241. if (!texture) {
  14242. throw new Error("Unable to create texture");
  14243. }
  14244. return texture;
  14245. };
  14246. /**
  14247. * Usually called from BABYLON.Texture.ts.
  14248. * Passed information to create a WebGLTexture
  14249. * @param urlArg defines a value which contains one of the following:
  14250. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14251. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14252. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14253. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14254. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14255. * @param scene needed for loading to the correct scene
  14256. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14257. * @param onLoad optional callback to be called upon successful completion
  14258. * @param onError optional callback to be called upon failure
  14259. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14260. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14261. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14262. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14263. */
  14264. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14265. var _this = this;
  14266. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14267. if (onLoad === void 0) { onLoad = null; }
  14268. if (onError === void 0) { onError = null; }
  14269. if (buffer === void 0) { buffer = null; }
  14270. if (fallback === void 0) { fallback = null; }
  14271. if (format === void 0) { format = null; }
  14272. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14273. var fromData = url.substr(0, 5) === "data:";
  14274. var fromBlob = url.substr(0, 5) === "blob:";
  14275. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14276. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14277. // establish the file extension, if possible
  14278. var lastDot = url.lastIndexOf('.');
  14279. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14280. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14281. var isTGA = (extension.indexOf(".tga") === 0);
  14282. // determine if a ktx file should be substituted
  14283. var isKTX = false;
  14284. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14285. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14286. isKTX = true;
  14287. }
  14288. if (scene) {
  14289. scene._addPendingData(texture);
  14290. }
  14291. texture.url = url;
  14292. texture.generateMipMaps = !noMipmap;
  14293. texture.samplingMode = samplingMode;
  14294. texture.invertY = invertY;
  14295. if (!this._doNotHandleContextLost) {
  14296. // Keep a link to the buffer only if we plan to handle context lost
  14297. texture._buffer = buffer;
  14298. }
  14299. var onLoadObserver = null;
  14300. if (onLoad && !fallback) {
  14301. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14302. }
  14303. if (!fallback)
  14304. this._internalTexturesCache.push(texture);
  14305. var onerror = function (message, exception) {
  14306. if (scene) {
  14307. scene._removePendingData(texture);
  14308. }
  14309. if (onLoadObserver) {
  14310. texture.onLoadedObservable.remove(onLoadObserver);
  14311. }
  14312. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14313. if (isKTX) {
  14314. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14315. }
  14316. else if (BABYLON.Tools.UseFallbackTexture) {
  14317. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14318. }
  14319. if (onError) {
  14320. onError(message || "Unknown error", exception);
  14321. }
  14322. };
  14323. var callback = null;
  14324. // processing for non-image formats
  14325. if (isKTX || isTGA || isDDS) {
  14326. if (isKTX) {
  14327. callback = function (data) {
  14328. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14329. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14330. ktx.uploadLevels(_this._gl, !noMipmap);
  14331. return false;
  14332. }, samplingMode);
  14333. };
  14334. }
  14335. else if (isTGA) {
  14336. callback = function (arrayBuffer) {
  14337. var data = new Uint8Array(arrayBuffer);
  14338. var header = BABYLON.TGATools.GetTGAHeader(data);
  14339. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14340. BABYLON.TGATools.UploadContent(_this._gl, data);
  14341. return false;
  14342. }, samplingMode);
  14343. };
  14344. }
  14345. else if (isDDS) {
  14346. callback = function (data) {
  14347. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14348. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14349. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14350. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14351. return false;
  14352. }, samplingMode);
  14353. };
  14354. }
  14355. if (!buffer) {
  14356. this._loadFile(url, function (data) {
  14357. if (callback) {
  14358. callback(data);
  14359. }
  14360. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14361. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14362. });
  14363. }
  14364. else {
  14365. if (callback) {
  14366. callback(buffer);
  14367. }
  14368. }
  14369. // image format processing
  14370. }
  14371. else {
  14372. var onload = function (img) {
  14373. if (fromBlob && !_this._doNotHandleContextLost) {
  14374. // We need to store the image if we need to rebuild the texture
  14375. // in case of a webgl context lost
  14376. texture._buffer = img;
  14377. }
  14378. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14379. var gl = _this._gl;
  14380. var isPot = (img.width === potWidth && img.height === potHeight);
  14381. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14382. if (isPot) {
  14383. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14384. return false;
  14385. }
  14386. // Using shaders to rescale because canvas.drawImage is lossy
  14387. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14388. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14389. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14390. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14391. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14392. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14393. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14394. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14395. _this._releaseTexture(source);
  14396. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14397. continuationCallback();
  14398. });
  14399. return true;
  14400. }, samplingMode);
  14401. };
  14402. if (!fromData || isBase64)
  14403. if (buffer instanceof HTMLImageElement) {
  14404. onload(buffer);
  14405. }
  14406. else {
  14407. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14408. }
  14409. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14410. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14411. else
  14412. onload(buffer);
  14413. }
  14414. return texture;
  14415. };
  14416. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14417. var _this = this;
  14418. var rtt = this.createRenderTargetTexture({
  14419. width: destination.width,
  14420. height: destination.height,
  14421. }, {
  14422. generateMipMaps: false,
  14423. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14424. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14425. generateDepthBuffer: false,
  14426. generateStencilBuffer: false
  14427. });
  14428. if (!this._rescalePostProcess) {
  14429. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14430. }
  14431. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14432. _this._rescalePostProcess.onApply = function (effect) {
  14433. effect._bindTexture("textureSampler", source);
  14434. };
  14435. var hostingScene = scene;
  14436. if (!hostingScene) {
  14437. hostingScene = _this.scenes[_this.scenes.length - 1];
  14438. }
  14439. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14440. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14441. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14442. _this.unBindFramebuffer(rtt);
  14443. _this._releaseTexture(rtt);
  14444. if (onComplete) {
  14445. onComplete();
  14446. }
  14447. });
  14448. };
  14449. /**
  14450. * Update a raw texture
  14451. * @param texture defines the texture to update
  14452. * @param data defines the data to store in the texture
  14453. * @param format defines the format of the data
  14454. * @param invertY defines if data must be stored with Y axis inverted
  14455. * @param compression defines the compression used (null by default)
  14456. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14457. */
  14458. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14459. if (compression === void 0) { compression = null; }
  14460. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14461. if (!texture) {
  14462. return;
  14463. }
  14464. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14465. var internalFormat = this._getInternalFormat(format);
  14466. var textureType = this._getWebGLTextureType(type);
  14467. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14468. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14469. if (!this._doNotHandleContextLost) {
  14470. texture._bufferView = data;
  14471. texture.format = format;
  14472. texture.type = type;
  14473. texture.invertY = invertY;
  14474. texture._compression = compression;
  14475. }
  14476. if (texture.width % 4 !== 0) {
  14477. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14478. }
  14479. if (compression && data) {
  14480. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14481. }
  14482. else {
  14483. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14484. }
  14485. if (texture.generateMipMaps) {
  14486. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14487. }
  14488. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14489. // this.resetTextureCache();
  14490. texture.isReady = true;
  14491. };
  14492. /**
  14493. * Creates a raw texture
  14494. * @param data defines the data to store in the texture
  14495. * @param width defines the width of the texture
  14496. * @param height defines the height of the texture
  14497. * @param format defines the format of the data
  14498. * @param generateMipMaps defines if the engine should generate the mip levels
  14499. * @param invertY defines if data must be stored with Y axis inverted
  14500. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14501. * @param compression defines the compression used (null by default)
  14502. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14503. * @returns the raw texture inside an InternalTexture
  14504. */
  14505. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14506. if (compression === void 0) { compression = null; }
  14507. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14508. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14509. texture.baseWidth = width;
  14510. texture.baseHeight = height;
  14511. texture.width = width;
  14512. texture.height = height;
  14513. texture.format = format;
  14514. texture.generateMipMaps = generateMipMaps;
  14515. texture.samplingMode = samplingMode;
  14516. texture.invertY = invertY;
  14517. texture._compression = compression;
  14518. texture.type = type;
  14519. if (!this._doNotHandleContextLost) {
  14520. texture._bufferView = data;
  14521. }
  14522. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14523. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14524. // Filters
  14525. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14526. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14527. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14528. if (generateMipMaps) {
  14529. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14530. }
  14531. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14532. this._internalTexturesCache.push(texture);
  14533. return texture;
  14534. };
  14535. /**
  14536. * Creates a dynamic texture
  14537. * @param width defines the width of the texture
  14538. * @param height defines the height of the texture
  14539. * @param generateMipMaps defines if the engine should generate the mip levels
  14540. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14541. * @returns the dynamic texture inside an InternalTexture
  14542. */
  14543. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14544. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14545. texture.baseWidth = width;
  14546. texture.baseHeight = height;
  14547. if (generateMipMaps) {
  14548. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14549. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14550. }
  14551. // this.resetTextureCache();
  14552. texture.width = width;
  14553. texture.height = height;
  14554. texture.isReady = false;
  14555. texture.generateMipMaps = generateMipMaps;
  14556. texture.samplingMode = samplingMode;
  14557. this.updateTextureSamplingMode(samplingMode, texture);
  14558. this._internalTexturesCache.push(texture);
  14559. return texture;
  14560. };
  14561. /**
  14562. * Update the sampling mode of a given texture
  14563. * @param samplingMode defines the required sampling mode
  14564. * @param texture defines the texture to update
  14565. */
  14566. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14567. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14568. if (texture.isCube) {
  14569. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14570. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14571. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14572. }
  14573. else if (texture.is3D) {
  14574. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14575. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14576. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14577. }
  14578. else {
  14579. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14580. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14581. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14582. }
  14583. texture.samplingMode = samplingMode;
  14584. };
  14585. /**
  14586. * Update the content of a dynamic texture
  14587. * @param texture defines the texture to update
  14588. * @param canvas defines the canvas containing the source
  14589. * @param invertY defines if data must be stored with Y axis inverted
  14590. * @param premulAlpha defines if alpha is stored as premultiplied
  14591. * @param format defines the format of the data
  14592. */
  14593. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14594. if (premulAlpha === void 0) { premulAlpha = false; }
  14595. if (!texture) {
  14596. return;
  14597. }
  14598. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14599. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14600. if (premulAlpha) {
  14601. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14602. }
  14603. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14604. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14605. if (texture.generateMipMaps) {
  14606. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14607. }
  14608. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14609. if (premulAlpha) {
  14610. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14611. }
  14612. texture.isReady = true;
  14613. };
  14614. /**
  14615. * Update a video texture
  14616. * @param texture defines the texture to update
  14617. * @param video defines the video element to use
  14618. * @param invertY defines if data must be stored with Y axis inverted
  14619. */
  14620. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14621. if (!texture || texture._isDisabled) {
  14622. return;
  14623. }
  14624. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14625. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14626. try {
  14627. // Testing video texture support
  14628. if (this._videoTextureSupported === undefined) {
  14629. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14630. if (this._gl.getError() !== 0) {
  14631. this._videoTextureSupported = false;
  14632. }
  14633. else {
  14634. this._videoTextureSupported = true;
  14635. }
  14636. }
  14637. // Copy video through the current working canvas if video texture is not supported
  14638. if (!this._videoTextureSupported) {
  14639. if (!texture._workingCanvas) {
  14640. texture._workingCanvas = document.createElement("canvas");
  14641. var context = texture._workingCanvas.getContext("2d");
  14642. if (!context) {
  14643. throw new Error("Unable to get 2d context");
  14644. }
  14645. texture._workingContext = context;
  14646. texture._workingCanvas.width = texture.width;
  14647. texture._workingCanvas.height = texture.height;
  14648. }
  14649. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14650. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14651. }
  14652. else {
  14653. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14654. }
  14655. if (texture.generateMipMaps) {
  14656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14657. }
  14658. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14659. // this.resetTextureCache();
  14660. texture.isReady = true;
  14661. }
  14662. catch (ex) {
  14663. // Something unexpected
  14664. // Let's disable the texture
  14665. texture._isDisabled = true;
  14666. }
  14667. };
  14668. /**
  14669. * Updates a depth texture Comparison Mode and Function.
  14670. * If the comparison Function is equal to 0, the mode will be set to none.
  14671. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14672. * @param texture The texture to set the comparison function for
  14673. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14674. */
  14675. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14676. if (this.webGLVersion === 1) {
  14677. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14678. return;
  14679. }
  14680. var gl = this._gl;
  14681. if (texture.isCube) {
  14682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14683. if (comparisonFunction === 0) {
  14684. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14685. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14686. }
  14687. else {
  14688. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14689. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14690. }
  14691. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14692. }
  14693. else {
  14694. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14695. if (comparisonFunction === 0) {
  14696. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14697. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14698. }
  14699. else {
  14700. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14701. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14702. }
  14703. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14704. }
  14705. texture._comparisonFunction = comparisonFunction;
  14706. };
  14707. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14708. var width = size.width || size;
  14709. var height = size.height || size;
  14710. internalTexture.baseWidth = width;
  14711. internalTexture.baseHeight = height;
  14712. internalTexture.width = width;
  14713. internalTexture.height = height;
  14714. internalTexture.isReady = true;
  14715. internalTexture.samples = 1;
  14716. internalTexture.generateMipMaps = false;
  14717. internalTexture._generateDepthBuffer = true;
  14718. internalTexture._generateStencilBuffer = generateStencil;
  14719. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14720. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14721. internalTexture._comparisonFunction = comparisonFunction;
  14722. var gl = this._gl;
  14723. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14724. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14725. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14726. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14727. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14728. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14729. if (comparisonFunction === 0) {
  14730. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14731. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14732. }
  14733. else {
  14734. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14735. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14736. }
  14737. };
  14738. /**
  14739. * Creates a depth stencil texture.
  14740. * This is only available in WebGL 2 or with the depth texture extension available.
  14741. * @param size The size of face edge in the texture.
  14742. * @param options The options defining the texture.
  14743. * @returns The texture
  14744. */
  14745. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14746. if (options.isCube) {
  14747. var width = size.width || size;
  14748. return this._createDepthStencilCubeTexture(width, options);
  14749. }
  14750. else {
  14751. return this._createDepthStencilTexture(size, options);
  14752. }
  14753. };
  14754. /**
  14755. * Creates a depth stencil texture.
  14756. * This is only available in WebGL 2 or with the depth texture extension available.
  14757. * @param size The size of face edge in the texture.
  14758. * @param options The options defining the texture.
  14759. * @returns The texture
  14760. */
  14761. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14762. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14763. if (!this._caps.depthTextureExtension) {
  14764. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14765. return internalTexture;
  14766. }
  14767. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14768. var gl = this._gl;
  14769. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14770. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14771. if (this.webGLVersion > 1) {
  14772. if (internalOptions.generateStencil) {
  14773. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14774. }
  14775. else {
  14776. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14777. }
  14778. }
  14779. else {
  14780. if (internalOptions.generateStencil) {
  14781. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14782. }
  14783. else {
  14784. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14785. }
  14786. }
  14787. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14788. return internalTexture;
  14789. };
  14790. /**
  14791. * Creates a depth stencil cube texture.
  14792. * This is only available in WebGL 2.
  14793. * @param size The size of face edge in the cube texture.
  14794. * @param options The options defining the cube texture.
  14795. * @returns The cube texture
  14796. */
  14797. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14798. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14799. internalTexture.isCube = true;
  14800. if (this.webGLVersion === 1) {
  14801. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14802. return internalTexture;
  14803. }
  14804. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14805. var gl = this._gl;
  14806. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14807. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14808. // Create the depth/stencil buffer
  14809. for (var face = 0; face < 6; face++) {
  14810. if (internalOptions.generateStencil) {
  14811. 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);
  14812. }
  14813. else {
  14814. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14815. }
  14816. }
  14817. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14818. return internalTexture;
  14819. };
  14820. /**
  14821. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14822. * @param renderTarget The render target to set the frame buffer for
  14823. */
  14824. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14825. // Create the framebuffer
  14826. var internalTexture = renderTarget.getInternalTexture();
  14827. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14828. return;
  14829. }
  14830. var gl = this._gl;
  14831. var depthStencilTexture = renderTarget.depthStencilTexture;
  14832. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  14833. if (depthStencilTexture.isCube) {
  14834. if (depthStencilTexture._generateStencilBuffer) {
  14835. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14836. }
  14837. else {
  14838. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  14839. }
  14840. }
  14841. else {
  14842. if (depthStencilTexture._generateStencilBuffer) {
  14843. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14844. }
  14845. else {
  14846. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  14847. }
  14848. }
  14849. this.bindUnboundFramebuffer(null);
  14850. };
  14851. /**
  14852. * Creates a new render target texture
  14853. * @param size defines the size of the texture
  14854. * @param options defines the options used to create the texture
  14855. * @returns a new render target texture stored in an InternalTexture
  14856. */
  14857. Engine.prototype.createRenderTargetTexture = function (size, options) {
  14858. var fullOptions = new RenderTargetCreationOptions();
  14859. if (options !== undefined && typeof options === "object") {
  14860. fullOptions.generateMipMaps = options.generateMipMaps;
  14861. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14862. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  14863. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  14864. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  14865. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  14866. }
  14867. else {
  14868. fullOptions.generateMipMaps = options;
  14869. fullOptions.generateDepthBuffer = true;
  14870. fullOptions.generateStencilBuffer = false;
  14871. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14872. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14873. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  14874. }
  14875. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14876. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14877. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14878. }
  14879. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14880. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14881. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14882. }
  14883. var gl = this._gl;
  14884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  14885. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14886. var width = size.width || size;
  14887. var height = size.height || size;
  14888. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  14889. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14890. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14891. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14892. }
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14894. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14895. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14896. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14897. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  14898. // Create the framebuffer
  14899. var framebuffer = gl.createFramebuffer();
  14900. this.bindUnboundFramebuffer(framebuffer);
  14901. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14902. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  14903. if (fullOptions.generateMipMaps) {
  14904. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14905. }
  14906. // Unbind
  14907. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14909. this.bindUnboundFramebuffer(null);
  14910. texture._framebuffer = framebuffer;
  14911. texture.baseWidth = width;
  14912. texture.baseHeight = height;
  14913. texture.width = width;
  14914. texture.height = height;
  14915. texture.isReady = true;
  14916. texture.samples = 1;
  14917. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  14918. texture.samplingMode = fullOptions.samplingMode;
  14919. texture.type = fullOptions.type;
  14920. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14921. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  14922. // this.resetTextureCache();
  14923. this._internalTexturesCache.push(texture);
  14924. return texture;
  14925. };
  14926. /**
  14927. * Create a multi render target texture
  14928. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  14929. * @param size defines the size of the texture
  14930. * @param options defines the creation options
  14931. * @returns the cube texture as an InternalTexture
  14932. */
  14933. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  14934. var generateMipMaps = false;
  14935. var generateDepthBuffer = true;
  14936. var generateStencilBuffer = false;
  14937. var generateDepthTexture = false;
  14938. var textureCount = 1;
  14939. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  14940. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  14941. var types = new Array();
  14942. var samplingModes = new Array();
  14943. if (options !== undefined) {
  14944. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  14945. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  14946. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  14947. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  14948. textureCount = options.textureCount || 1;
  14949. if (options.types) {
  14950. types = options.types;
  14951. }
  14952. if (options.samplingModes) {
  14953. samplingModes = options.samplingModes;
  14954. }
  14955. }
  14956. var gl = this._gl;
  14957. // Create the framebuffer
  14958. var framebuffer = gl.createFramebuffer();
  14959. this.bindUnboundFramebuffer(framebuffer);
  14960. var width = size.width || size;
  14961. var height = size.height || size;
  14962. var textures = [];
  14963. var attachments = [];
  14964. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  14965. for (var i = 0; i < textureCount; i++) {
  14966. var samplingMode = samplingModes[i] || defaultSamplingMode;
  14967. var type = types[i] || defaultType;
  14968. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  14969. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  14970. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14971. }
  14972. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  14973. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  14974. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14975. }
  14976. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14977. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  14978. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14979. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  14980. }
  14981. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  14982. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  14983. textures.push(texture);
  14984. attachments.push(attachment);
  14985. gl.activeTexture(gl["TEXTURE" + i]);
  14986. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  14987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14988. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14989. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14990. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14991. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14992. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14993. if (generateMipMaps) {
  14994. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14995. }
  14996. // Unbind
  14997. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14998. texture._framebuffer = framebuffer;
  14999. texture._depthStencilBuffer = depthStencilBuffer;
  15000. texture.baseWidth = width;
  15001. texture.baseHeight = height;
  15002. texture.width = width;
  15003. texture.height = height;
  15004. texture.isReady = true;
  15005. texture.samples = 1;
  15006. texture.generateMipMaps = generateMipMaps;
  15007. texture.samplingMode = samplingMode;
  15008. texture.type = type;
  15009. texture._generateDepthBuffer = generateDepthBuffer;
  15010. texture._generateStencilBuffer = generateStencilBuffer;
  15011. texture._attachments = attachments;
  15012. this._internalTexturesCache.push(texture);
  15013. }
  15014. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15015. // Depth texture
  15016. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15017. gl.activeTexture(gl.TEXTURE0);
  15018. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15019. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15020. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15021. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15022. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15023. 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);
  15024. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15025. depthTexture._framebuffer = framebuffer;
  15026. depthTexture.baseWidth = width;
  15027. depthTexture.baseHeight = height;
  15028. depthTexture.width = width;
  15029. depthTexture.height = height;
  15030. depthTexture.isReady = true;
  15031. depthTexture.samples = 1;
  15032. depthTexture.generateMipMaps = generateMipMaps;
  15033. depthTexture.samplingMode = gl.NEAREST;
  15034. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15035. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15036. textures.push(depthTexture);
  15037. this._internalTexturesCache.push(depthTexture);
  15038. }
  15039. gl.drawBuffers(attachments);
  15040. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15041. this.bindUnboundFramebuffer(null);
  15042. this.resetTextureCache();
  15043. return textures;
  15044. };
  15045. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15046. if (samples === void 0) { samples = 1; }
  15047. var depthStencilBuffer = null;
  15048. var gl = this._gl;
  15049. // Create the depth/stencil buffer
  15050. if (generateStencilBuffer) {
  15051. depthStencilBuffer = gl.createRenderbuffer();
  15052. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15053. if (samples > 1) {
  15054. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15055. }
  15056. else {
  15057. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15058. }
  15059. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15060. }
  15061. else if (generateDepthBuffer) {
  15062. depthStencilBuffer = gl.createRenderbuffer();
  15063. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15064. if (samples > 1) {
  15065. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15066. }
  15067. else {
  15068. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15069. }
  15070. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15071. }
  15072. return depthStencilBuffer;
  15073. };
  15074. /**
  15075. * Updates the sample count of a render target texture
  15076. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15077. * @param texture defines the texture to update
  15078. * @param samples defines the sample count to set
  15079. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15080. */
  15081. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15082. if (this.webGLVersion < 2 || !texture) {
  15083. return 1;
  15084. }
  15085. if (texture.samples === samples) {
  15086. return samples;
  15087. }
  15088. var gl = this._gl;
  15089. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15090. // Dispose previous render buffers
  15091. if (texture._depthStencilBuffer) {
  15092. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15093. texture._depthStencilBuffer = null;
  15094. }
  15095. if (texture._MSAAFramebuffer) {
  15096. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15097. texture._MSAAFramebuffer = null;
  15098. }
  15099. if (texture._MSAARenderBuffer) {
  15100. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15101. texture._MSAARenderBuffer = null;
  15102. }
  15103. if (samples > 1) {
  15104. var framebuffer = gl.createFramebuffer();
  15105. if (!framebuffer) {
  15106. throw new Error("Unable to create multi sampled framebuffer");
  15107. }
  15108. texture._MSAAFramebuffer = framebuffer;
  15109. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15110. var colorRenderbuffer = gl.createRenderbuffer();
  15111. if (!colorRenderbuffer) {
  15112. throw new Error("Unable to create multi sampled framebuffer");
  15113. }
  15114. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15115. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15116. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15117. texture._MSAARenderBuffer = colorRenderbuffer;
  15118. }
  15119. else {
  15120. this.bindUnboundFramebuffer(texture._framebuffer);
  15121. }
  15122. texture.samples = samples;
  15123. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15124. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15125. this.bindUnboundFramebuffer(null);
  15126. return samples;
  15127. };
  15128. /**
  15129. * Update the sample count for a given multiple render target texture
  15130. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15131. * @param textures defines the textures to update
  15132. * @param samples defines the sample count to set
  15133. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15134. */
  15135. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15136. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15137. return 1;
  15138. }
  15139. if (textures[0].samples === samples) {
  15140. return samples;
  15141. }
  15142. var gl = this._gl;
  15143. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15144. // Dispose previous render buffers
  15145. if (textures[0]._depthStencilBuffer) {
  15146. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15147. textures[0]._depthStencilBuffer = null;
  15148. }
  15149. if (textures[0]._MSAAFramebuffer) {
  15150. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15151. textures[0]._MSAAFramebuffer = null;
  15152. }
  15153. for (var i = 0; i < textures.length; i++) {
  15154. if (textures[i]._MSAARenderBuffer) {
  15155. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15156. textures[i]._MSAARenderBuffer = null;
  15157. }
  15158. }
  15159. if (samples > 1) {
  15160. var framebuffer = gl.createFramebuffer();
  15161. if (!framebuffer) {
  15162. throw new Error("Unable to create multi sampled framebuffer");
  15163. }
  15164. this.bindUnboundFramebuffer(framebuffer);
  15165. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15166. var attachments = [];
  15167. for (var i = 0; i < textures.length; i++) {
  15168. var texture = textures[i];
  15169. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15170. var colorRenderbuffer = gl.createRenderbuffer();
  15171. if (!colorRenderbuffer) {
  15172. throw new Error("Unable to create multi sampled framebuffer");
  15173. }
  15174. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15175. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15176. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15177. texture._MSAAFramebuffer = framebuffer;
  15178. texture._MSAARenderBuffer = colorRenderbuffer;
  15179. texture.samples = samples;
  15180. texture._depthStencilBuffer = depthStencilBuffer;
  15181. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15182. attachments.push(attachment);
  15183. }
  15184. gl.drawBuffers(attachments);
  15185. }
  15186. else {
  15187. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15188. }
  15189. this.bindUnboundFramebuffer(null);
  15190. return samples;
  15191. };
  15192. /** @ignore */
  15193. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15194. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15195. };
  15196. /** @ignore */
  15197. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15198. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15199. };
  15200. /**
  15201. * Creates a new render target cube texture
  15202. * @param size defines the size of the texture
  15203. * @param options defines the options used to create the texture
  15204. * @returns a new render target cube texture stored in an InternalTexture
  15205. */
  15206. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15207. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15208. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15209. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15210. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15211. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15212. }
  15213. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15214. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15215. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15216. }
  15217. var gl = this._gl;
  15218. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15219. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15220. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15221. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15222. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15223. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15224. }
  15225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15227. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15228. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15229. for (var face = 0; face < 6; face++) {
  15230. 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);
  15231. }
  15232. // Create the framebuffer
  15233. var framebuffer = gl.createFramebuffer();
  15234. this.bindUnboundFramebuffer(framebuffer);
  15235. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15236. // MipMaps
  15237. if (fullOptions.generateMipMaps) {
  15238. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15239. }
  15240. // Unbind
  15241. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15242. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15243. this.bindUnboundFramebuffer(null);
  15244. texture._framebuffer = framebuffer;
  15245. texture.width = size;
  15246. texture.height = size;
  15247. texture.isReady = true;
  15248. texture.isCube = true;
  15249. texture.samples = 1;
  15250. texture.generateMipMaps = fullOptions.generateMipMaps;
  15251. texture.samplingMode = fullOptions.samplingMode;
  15252. texture.type = fullOptions.type;
  15253. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15254. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15255. this._internalTexturesCache.push(texture);
  15256. return texture;
  15257. };
  15258. /**
  15259. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15260. * @param rootUrl defines the url where the file to load is located
  15261. * @param scene defines the current scene
  15262. * @param scale defines scale to apply to the mip map selection
  15263. * @param offset defines offset to apply to the mip map selection
  15264. * @param onLoad defines an optional callback raised when the texture is loaded
  15265. * @param onError defines an optional callback raised if there is an issue to load the texture
  15266. * @param format defines the format of the data
  15267. * @param forcedExtension defines the extension to use to pick the right loader
  15268. * @returns the cube texture as an InternalTexture
  15269. */
  15270. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15271. var _this = this;
  15272. if (onLoad === void 0) { onLoad = null; }
  15273. if (onError === void 0) { onError = null; }
  15274. if (forcedExtension === void 0) { forcedExtension = null; }
  15275. var callback = function (loadData) {
  15276. if (!loadData) {
  15277. if (onLoad) {
  15278. onLoad(null);
  15279. }
  15280. return;
  15281. }
  15282. var texture = loadData.texture;
  15283. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15284. texture._lodGenerationScale = scale;
  15285. texture._lodGenerationOffset = offset;
  15286. if (_this._caps.textureLOD) {
  15287. // Do not add extra process if texture lod is supported.
  15288. if (onLoad) {
  15289. onLoad(texture);
  15290. }
  15291. return;
  15292. }
  15293. var mipSlices = 3;
  15294. var gl = _this._gl;
  15295. var width = loadData.width;
  15296. if (!width) {
  15297. return;
  15298. }
  15299. var textures = [];
  15300. for (var i = 0; i < mipSlices; i++) {
  15301. //compute LOD from even spacing in smoothness (matching shader calculation)
  15302. var smoothness = i / (mipSlices - 1);
  15303. var roughness = 1 - smoothness;
  15304. var minLODIndex = offset; // roughness = 0
  15305. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15306. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15307. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15308. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15309. glTextureFromLod.isCube = true;
  15310. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15311. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15312. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15313. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15314. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15315. if (loadData.isDDS) {
  15316. var info = loadData.info;
  15317. var data = loadData.data;
  15318. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15319. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15320. }
  15321. else {
  15322. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15323. }
  15324. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15325. // Wrap in a base texture for easy binding.
  15326. var lodTexture = new BABYLON.BaseTexture(scene);
  15327. lodTexture.isCube = true;
  15328. lodTexture._texture = glTextureFromLod;
  15329. glTextureFromLod.isReady = true;
  15330. textures.push(lodTexture);
  15331. }
  15332. texture._lodTextureHigh = textures[2];
  15333. texture._lodTextureMid = textures[1];
  15334. texture._lodTextureLow = textures[0];
  15335. if (onLoad) {
  15336. onLoad(texture);
  15337. }
  15338. };
  15339. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  15340. };
  15341. /**
  15342. * Creates a cube texture
  15343. * @param rootUrl defines the url where the files to load is located
  15344. * @param scene defines the current scene
  15345. * @param files defines the list of files to load (1 per face)
  15346. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15347. * @param onLoad defines an optional callback raised when the texture is loaded
  15348. * @param onError defines an optional callback raised if there is an issue to load the texture
  15349. * @param format defines the format of the data
  15350. * @param forcedExtension defines the extension to use to pick the right loader
  15351. * @returns the cube texture as an InternalTexture
  15352. */
  15353. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  15354. var _this = this;
  15355. if (onLoad === void 0) { onLoad = null; }
  15356. if (onError === void 0) { onError = null; }
  15357. if (forcedExtension === void 0) { forcedExtension = null; }
  15358. var gl = this._gl;
  15359. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15360. texture.isCube = true;
  15361. texture.url = rootUrl;
  15362. texture.generateMipMaps = !noMipmap;
  15363. if (!this._doNotHandleContextLost) {
  15364. texture._extension = forcedExtension;
  15365. texture._files = files;
  15366. }
  15367. var isKTX = false;
  15368. var isDDS = false;
  15369. var lastDot = rootUrl.lastIndexOf('.');
  15370. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15371. if (this._textureFormatInUse) {
  15372. extension = this._textureFormatInUse;
  15373. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15374. isKTX = true;
  15375. }
  15376. else {
  15377. isDDS = (extension === ".dds");
  15378. }
  15379. var onerror = function (request, exception) {
  15380. if (onError && request) {
  15381. onError(request.status + " " + request.statusText, exception);
  15382. }
  15383. };
  15384. if (isKTX) {
  15385. this._loadFile(rootUrl, function (data) {
  15386. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15387. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15388. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15389. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15390. ktx.uploadLevels(_this._gl, !noMipmap);
  15391. _this.setCubeMapTextureParams(gl, loadMipmap);
  15392. texture.width = ktx.pixelWidth;
  15393. texture.height = ktx.pixelHeight;
  15394. texture.isReady = true;
  15395. }, undefined, undefined, true, onerror);
  15396. }
  15397. else if (isDDS) {
  15398. if (files && files.length === 6) {
  15399. this._cascadeLoadFiles(scene, function (imgs) {
  15400. var info;
  15401. var loadMipmap = false;
  15402. var width = 0;
  15403. for (var index = 0; index < imgs.length; index++) {
  15404. var data = imgs[index];
  15405. info = BABYLON.DDSTools.GetDDSInfo(data);
  15406. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15407. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15408. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15409. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15410. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15411. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15412. }
  15413. texture.width = info.width;
  15414. texture.height = info.height;
  15415. texture.type = info.textureType;
  15416. width = info.width;
  15417. }
  15418. _this.setCubeMapTextureParams(gl, loadMipmap);
  15419. texture.isReady = true;
  15420. if (onLoad) {
  15421. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15422. }
  15423. }, files, onError);
  15424. }
  15425. else {
  15426. this._loadFile(rootUrl, function (data) {
  15427. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15428. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15429. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15430. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15431. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15432. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15433. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15434. }
  15435. _this.setCubeMapTextureParams(gl, loadMipmap);
  15436. texture.width = info.width;
  15437. texture.height = info.height;
  15438. texture.isReady = true;
  15439. texture.type = info.textureType;
  15440. if (onLoad) {
  15441. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15442. }
  15443. }, undefined, undefined, true, onerror);
  15444. }
  15445. }
  15446. else {
  15447. if (!files) {
  15448. throw new Error("Cannot load cubemap because files were not defined");
  15449. }
  15450. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15451. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15452. var height = width;
  15453. _this._prepareWorkingCanvas();
  15454. if (!_this._workingCanvas || !_this._workingContext) {
  15455. return;
  15456. }
  15457. _this._workingCanvas.width = width;
  15458. _this._workingCanvas.height = height;
  15459. var faces = [
  15460. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15461. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15462. ];
  15463. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15464. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15465. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15466. for (var index = 0; index < faces.length; index++) {
  15467. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15468. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15469. }
  15470. if (!noMipmap) {
  15471. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15472. }
  15473. _this.setCubeMapTextureParams(gl, !noMipmap);
  15474. texture.width = width;
  15475. texture.height = height;
  15476. texture.isReady = true;
  15477. if (format) {
  15478. texture.format = format;
  15479. }
  15480. texture.onLoadedObservable.notifyObservers(texture);
  15481. texture.onLoadedObservable.clear();
  15482. if (onLoad) {
  15483. onLoad();
  15484. }
  15485. }, files, onError);
  15486. }
  15487. this._internalTexturesCache.push(texture);
  15488. return texture;
  15489. };
  15490. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15491. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15492. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15495. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15496. // this.resetTextureCache();
  15497. };
  15498. /**
  15499. * Update a raw cube texture
  15500. * @param texture defines the texture to udpdate
  15501. * @param data defines the data to store
  15502. * @param format defines the data format
  15503. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15504. * @param invertY defines if data must be stored with Y axis inverted
  15505. * @param compression defines the compression used (null by default)
  15506. * @param level defines which level of the texture to update
  15507. */
  15508. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15509. if (compression === void 0) { compression = null; }
  15510. if (level === void 0) { level = 0; }
  15511. texture._bufferViewArray = data;
  15512. texture.format = format;
  15513. texture.type = type;
  15514. texture.invertY = invertY;
  15515. texture._compression = compression;
  15516. var gl = this._gl;
  15517. var textureType = this._getWebGLTextureType(type);
  15518. var internalFormat = this._getInternalFormat(format);
  15519. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15520. var needConversion = false;
  15521. if (internalFormat === gl.RGB) {
  15522. internalFormat = gl.RGBA;
  15523. needConversion = true;
  15524. }
  15525. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15526. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15527. if (texture.width % 4 !== 0) {
  15528. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15529. }
  15530. // Data are known to be in +X +Y +Z -X -Y -Z
  15531. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15532. var faceData = data[faceIndex];
  15533. if (compression) {
  15534. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15535. }
  15536. else {
  15537. if (needConversion) {
  15538. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15539. }
  15540. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15541. }
  15542. }
  15543. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15544. if (isPot && texture.generateMipMaps && level === 0) {
  15545. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15546. }
  15547. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15548. // this.resetTextureCache();
  15549. texture.isReady = true;
  15550. };
  15551. /**
  15552. * Creates a new raw cube texture
  15553. * @param data defines the array of data to use to create each face
  15554. * @param size defines the size of the textures
  15555. * @param format defines the format of the data
  15556. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15557. * @param generateMipMaps defines if the engine should generate the mip levels
  15558. * @param invertY defines if data must be stored with Y axis inverted
  15559. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15560. * @param compression defines the compression used (null by default)
  15561. * @returns the cube texture as an InternalTexture
  15562. */
  15563. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15564. if (compression === void 0) { compression = null; }
  15565. var gl = this._gl;
  15566. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15567. texture.isCube = true;
  15568. texture.generateMipMaps = generateMipMaps;
  15569. texture.format = format;
  15570. texture.type = type;
  15571. if (!this._doNotHandleContextLost) {
  15572. texture._bufferViewArray = data;
  15573. }
  15574. var textureType = this._getWebGLTextureType(type);
  15575. var internalFormat = this._getInternalFormat(format);
  15576. if (internalFormat === gl.RGB) {
  15577. internalFormat = gl.RGBA;
  15578. }
  15579. var width = size;
  15580. var height = width;
  15581. texture.width = width;
  15582. texture.height = height;
  15583. // Double check on POT to generate Mips.
  15584. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15585. if (!isPot) {
  15586. generateMipMaps = false;
  15587. }
  15588. // Upload data if needed. The texture won't be ready until then.
  15589. if (data) {
  15590. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15591. }
  15592. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15593. // Filters
  15594. if (data && generateMipMaps) {
  15595. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15596. }
  15597. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15598. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15599. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15600. }
  15601. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15602. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15603. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15604. }
  15605. else {
  15606. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15609. }
  15610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15611. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15612. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15613. return texture;
  15614. };
  15615. /**
  15616. * Creates a new raw cube texture from a specified url
  15617. * @param url defines the url where the data is located
  15618. * @param scene defines the current scene
  15619. * @param size defines the size of the textures
  15620. * @param format defines the format of the data
  15621. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15622. * @param noMipmap defines if the engine should avoid generating the mip levels
  15623. * @param callback defines a callback used to extract texture data from loaded data
  15624. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15625. * @param onLoad defines a callback called when texture is loaded
  15626. * @param onError defines a callback called if there is an error
  15627. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15628. * @param invertY defines if data must be stored with Y axis inverted
  15629. * @returns the cube texture as an InternalTexture
  15630. */
  15631. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15632. var _this = this;
  15633. if (onLoad === void 0) { onLoad = null; }
  15634. if (onError === void 0) { onError = null; }
  15635. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15636. if (invertY === void 0) { invertY = false; }
  15637. var gl = this._gl;
  15638. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15639. scene._addPendingData(texture);
  15640. texture.url = url;
  15641. this._internalTexturesCache.push(texture);
  15642. var onerror = function (request, exception) {
  15643. scene._removePendingData(texture);
  15644. if (onError && request) {
  15645. onError(request.status + " " + request.statusText, exception);
  15646. }
  15647. };
  15648. var internalCallback = function (data) {
  15649. var width = texture.width;
  15650. var faceDataArrays = callback(data);
  15651. if (!faceDataArrays) {
  15652. return;
  15653. }
  15654. if (mipmapGenerator) {
  15655. var textureType = _this._getWebGLTextureType(type);
  15656. var internalFormat = _this._getInternalFormat(format);
  15657. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15658. var needConversion = false;
  15659. if (internalFormat === gl.RGB) {
  15660. internalFormat = gl.RGBA;
  15661. needConversion = true;
  15662. }
  15663. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15664. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15665. var mipData = mipmapGenerator(faceDataArrays);
  15666. for (var level = 0; level < mipData.length; level++) {
  15667. var mipSize = width >> level;
  15668. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15669. var mipFaceData = mipData[level][faceIndex];
  15670. if (needConversion) {
  15671. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15672. }
  15673. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15674. }
  15675. }
  15676. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15677. }
  15678. else {
  15679. texture.generateMipMaps = !noMipmap;
  15680. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15681. }
  15682. texture.isReady = true;
  15683. // this.resetTextureCache();
  15684. scene._removePendingData(texture);
  15685. if (onLoad) {
  15686. onLoad();
  15687. }
  15688. };
  15689. this._loadFile(url, function (data) {
  15690. internalCallback(data);
  15691. }, undefined, scene.database, true, onerror);
  15692. return texture;
  15693. };
  15694. ;
  15695. /**
  15696. * Update a raw 3D texture
  15697. * @param texture defines the texture to update
  15698. * @param data defines the data to store
  15699. * @param format defines the data format
  15700. * @param invertY defines if data must be stored with Y axis inverted
  15701. * @param compression defines the used compression (can be null)
  15702. */
  15703. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15704. if (compression === void 0) { compression = null; }
  15705. var internalFormat = this._getInternalFormat(format);
  15706. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15707. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15708. if (!this._doNotHandleContextLost) {
  15709. texture._bufferView = data;
  15710. texture.format = format;
  15711. texture.invertY = invertY;
  15712. texture._compression = compression;
  15713. }
  15714. if (texture.width % 4 !== 0) {
  15715. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15716. }
  15717. if (compression && data) {
  15718. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15719. }
  15720. else {
  15721. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15722. }
  15723. if (texture.generateMipMaps) {
  15724. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15725. }
  15726. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15727. // this.resetTextureCache();
  15728. texture.isReady = true;
  15729. };
  15730. /**
  15731. * Creates a new raw 3D texture
  15732. * @param data defines the data used to create the texture
  15733. * @param width defines the width of the texture
  15734. * @param height defines the height of the texture
  15735. * @param depth defines the depth of the texture
  15736. * @param format defines the format of the texture
  15737. * @param generateMipMaps defines if the engine must generate mip levels
  15738. * @param invertY defines if data must be stored with Y axis inverted
  15739. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15740. * @param compression defines the compressed used (can be null)
  15741. * @returns a new raw 3D texture (stored in an InternalTexture)
  15742. */
  15743. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15744. if (compression === void 0) { compression = null; }
  15745. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15746. texture.baseWidth = width;
  15747. texture.baseHeight = height;
  15748. texture.baseDepth = depth;
  15749. texture.width = width;
  15750. texture.height = height;
  15751. texture.depth = depth;
  15752. texture.format = format;
  15753. texture.generateMipMaps = generateMipMaps;
  15754. texture.samplingMode = samplingMode;
  15755. texture.is3D = true;
  15756. if (!this._doNotHandleContextLost) {
  15757. texture._bufferView = data;
  15758. }
  15759. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15760. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15761. // Filters
  15762. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15763. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15764. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15765. if (generateMipMaps) {
  15766. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15767. }
  15768. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15769. this._internalTexturesCache.push(texture);
  15770. return texture;
  15771. };
  15772. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15773. var gl = this._gl;
  15774. if (!gl) {
  15775. return;
  15776. }
  15777. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15780. if (!noMipmap && !isCompressed) {
  15781. gl.generateMipmap(gl.TEXTURE_2D);
  15782. }
  15783. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15784. // this.resetTextureCache();
  15785. if (scene) {
  15786. scene._removePendingData(texture);
  15787. }
  15788. texture.onLoadedObservable.notifyObservers(texture);
  15789. texture.onLoadedObservable.clear();
  15790. };
  15791. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15792. var _this = this;
  15793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15794. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15795. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15796. var gl = this._gl;
  15797. if (!gl) {
  15798. return;
  15799. }
  15800. if (!texture._webGLTexture) {
  15801. // this.resetTextureCache();
  15802. if (scene) {
  15803. scene._removePendingData(texture);
  15804. }
  15805. return;
  15806. }
  15807. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15808. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15809. texture.baseWidth = width;
  15810. texture.baseHeight = height;
  15811. texture.width = potWidth;
  15812. texture.height = potHeight;
  15813. texture.isReady = true;
  15814. if (processFunction(potWidth, potHeight, function () {
  15815. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15816. })) {
  15817. // Returning as texture needs extra async steps
  15818. return;
  15819. }
  15820. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15821. };
  15822. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  15823. // Create new RGBA data container.
  15824. var rgbaData;
  15825. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  15826. rgbaData = new Float32Array(width * height * 4);
  15827. }
  15828. else {
  15829. rgbaData = new Uint32Array(width * height * 4);
  15830. }
  15831. // Convert each pixel.
  15832. for (var x = 0; x < width; x++) {
  15833. for (var y = 0; y < height; y++) {
  15834. var index = (y * width + x) * 3;
  15835. var newIndex = (y * width + x) * 4;
  15836. // Map Old Value to new value.
  15837. rgbaData[newIndex + 0] = rgbData[index + 0];
  15838. rgbaData[newIndex + 1] = rgbData[index + 1];
  15839. rgbaData[newIndex + 2] = rgbData[index + 2];
  15840. // Add fully opaque alpha channel.
  15841. rgbaData[newIndex + 3] = 1;
  15842. }
  15843. }
  15844. return rgbaData;
  15845. };
  15846. /** @ignore */
  15847. Engine.prototype._releaseFramebufferObjects = function (texture) {
  15848. var gl = this._gl;
  15849. if (texture._framebuffer) {
  15850. gl.deleteFramebuffer(texture._framebuffer);
  15851. texture._framebuffer = null;
  15852. }
  15853. if (texture._depthStencilBuffer) {
  15854. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15855. texture._depthStencilBuffer = null;
  15856. }
  15857. if (texture._MSAAFramebuffer) {
  15858. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15859. texture._MSAAFramebuffer = null;
  15860. }
  15861. if (texture._MSAARenderBuffer) {
  15862. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15863. texture._MSAARenderBuffer = null;
  15864. }
  15865. };
  15866. /** @ignore */
  15867. Engine.prototype._releaseTexture = function (texture) {
  15868. var gl = this._gl;
  15869. this._releaseFramebufferObjects(texture);
  15870. gl.deleteTexture(texture._webGLTexture);
  15871. // Unbind channels
  15872. this.unbindAllTextures();
  15873. var index = this._internalTexturesCache.indexOf(texture);
  15874. if (index !== -1) {
  15875. this._internalTexturesCache.splice(index, 1);
  15876. }
  15877. // Integrated fixed lod samplers.
  15878. if (texture._lodTextureHigh) {
  15879. texture._lodTextureHigh.dispose();
  15880. }
  15881. if (texture._lodTextureMid) {
  15882. texture._lodTextureMid.dispose();
  15883. }
  15884. if (texture._lodTextureLow) {
  15885. texture._lodTextureLow.dispose();
  15886. }
  15887. // Set output texture of post process to null if the texture has been released/disposed
  15888. this.scenes.forEach(function (scene) {
  15889. scene.postProcesses.forEach(function (postProcess) {
  15890. if (postProcess._outputTexture == texture) {
  15891. postProcess._outputTexture = null;
  15892. }
  15893. });
  15894. scene.cameras.forEach(function (camera) {
  15895. camera._postProcesses.forEach(function (postProcess) {
  15896. if (postProcess) {
  15897. if (postProcess._outputTexture == texture) {
  15898. postProcess._outputTexture = null;
  15899. }
  15900. }
  15901. });
  15902. });
  15903. });
  15904. };
  15905. Engine.prototype.setProgram = function (program) {
  15906. if (this._currentProgram !== program) {
  15907. this._gl.useProgram(program);
  15908. this._currentProgram = program;
  15909. }
  15910. };
  15911. /**
  15912. * Binds an effect to the webGL context
  15913. * @param effect defines the effect to bind
  15914. */
  15915. Engine.prototype.bindSamplers = function (effect) {
  15916. this.setProgram(effect.getProgram());
  15917. var samplers = effect.getSamplers();
  15918. for (var index = 0; index < samplers.length; index++) {
  15919. var uniform = effect.getUniform(samplers[index]);
  15920. if (uniform) {
  15921. this._boundUniforms[index] = uniform;
  15922. }
  15923. }
  15924. this._currentEffect = null;
  15925. };
  15926. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  15927. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  15928. return;
  15929. }
  15930. // Remove
  15931. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15932. // Bind last to it
  15933. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  15934. // Bind to dummy
  15935. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  15936. };
  15937. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  15938. if (!internalTexture) {
  15939. return -1;
  15940. }
  15941. internalTexture._initialSlot = channel;
  15942. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  15943. if (channel !== internalTexture._designatedSlot) {
  15944. this._textureCollisions.addCount(1, false);
  15945. }
  15946. }
  15947. else {
  15948. if (channel !== internalTexture._designatedSlot) {
  15949. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  15950. return internalTexture._designatedSlot;
  15951. }
  15952. else {
  15953. // No slot for this texture, let's pick a new one (if we find a free slot)
  15954. if (this._nextFreeTextureSlots.length) {
  15955. return this._nextFreeTextureSlots[0];
  15956. }
  15957. // We need to recycle the oldest bound texture, sorry.
  15958. this._textureCollisions.addCount(1, false);
  15959. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  15960. }
  15961. }
  15962. }
  15963. return channel;
  15964. };
  15965. Engine.prototype._linkTrackers = function (previous, next) {
  15966. previous.next = next;
  15967. next.previous = previous;
  15968. };
  15969. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  15970. var currentSlot = internalTexture._designatedSlot;
  15971. if (currentSlot === -1) {
  15972. return -1;
  15973. }
  15974. internalTexture._designatedSlot = -1;
  15975. if (this.disableTextureBindingOptimization) {
  15976. return -1;
  15977. }
  15978. // Remove from bound list
  15979. this._linkTrackers(internalTexture.previous, internalTexture.next);
  15980. // Free the slot
  15981. this._boundTexturesCache[currentSlot] = null;
  15982. this._nextFreeTextureSlots.push(currentSlot);
  15983. return currentSlot;
  15984. };
  15985. Engine.prototype._activateCurrentTexture = function () {
  15986. if (this._currentTextureChannel !== this._activeChannel) {
  15987. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  15988. this._currentTextureChannel = this._activeChannel;
  15989. }
  15990. };
  15991. /** @ignore */
  15992. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  15993. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  15994. if (force === void 0) { force = false; }
  15995. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  15996. this._activeChannel = texture._designatedSlot;
  15997. }
  15998. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  15999. var isTextureForRendering = texture && texture._initialSlot > -1;
  16000. if (currentTextureBound !== texture || force) {
  16001. if (currentTextureBound) {
  16002. this._removeDesignatedSlot(currentTextureBound);
  16003. }
  16004. this._activateCurrentTexture();
  16005. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16006. this._boundTexturesCache[this._activeChannel] = texture;
  16007. if (texture) {
  16008. if (!this.disableTextureBindingOptimization) {
  16009. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16010. if (slotIndex > -1) {
  16011. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16012. }
  16013. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16014. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16015. }
  16016. texture._designatedSlot = this._activeChannel;
  16017. }
  16018. }
  16019. else if (forTextureDataUpdate) {
  16020. this._activateCurrentTexture();
  16021. }
  16022. if (isTextureForRendering && !forTextureDataUpdate) {
  16023. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16024. }
  16025. };
  16026. /** @ignore */
  16027. Engine.prototype._bindTexture = function (channel, texture) {
  16028. if (channel < 0) {
  16029. return;
  16030. }
  16031. if (texture) {
  16032. channel = this._getCorrectTextureChannel(channel, texture);
  16033. }
  16034. this._activeChannel = channel;
  16035. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16036. };
  16037. /**
  16038. * Sets a texture to the webGL context from a postprocess
  16039. * @param channel defines the channel to use
  16040. * @param postProcess defines the source postprocess
  16041. */
  16042. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16043. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16044. };
  16045. /**
  16046. * Binds the output of the passed in post process to the texture channel specified
  16047. * @param channel The channel the texture should be bound to
  16048. * @param postProcess The post process which's output should be bound
  16049. */
  16050. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16051. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16052. };
  16053. /**
  16054. * Unbind all textures from the webGL context
  16055. */
  16056. Engine.prototype.unbindAllTextures = function () {
  16057. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16058. this._activeChannel = channel;
  16059. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16060. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16061. if (this.webGLVersion > 1) {
  16062. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16063. }
  16064. }
  16065. };
  16066. /**
  16067. * Sets a texture to the according uniform.
  16068. * @param channel The texture channel
  16069. * @param uniform The uniform to set
  16070. * @param texture The texture to apply
  16071. */
  16072. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16073. if (channel < 0) {
  16074. return;
  16075. }
  16076. if (uniform) {
  16077. this._boundUniforms[channel] = uniform;
  16078. }
  16079. this._setTexture(channel, texture);
  16080. };
  16081. /**
  16082. * Sets a depth stencil texture from a render target to the according uniform.
  16083. * @param channel The texture channel
  16084. * @param uniform The uniform to set
  16085. * @param texture The render target texture containing the depth stencil texture to apply
  16086. */
  16087. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16088. if (channel < 0) {
  16089. return;
  16090. }
  16091. if (uniform) {
  16092. this._boundUniforms[channel] = uniform;
  16093. }
  16094. if (!texture || !texture.depthStencilTexture) {
  16095. this._setTexture(channel, null);
  16096. }
  16097. else {
  16098. this._setTexture(channel, texture, false, true);
  16099. }
  16100. };
  16101. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16102. var uniform = this._boundUniforms[sourceSlot];
  16103. if (uniform._currentState === destination) {
  16104. return;
  16105. }
  16106. this._gl.uniform1i(uniform, destination);
  16107. uniform._currentState = destination;
  16108. };
  16109. Engine.prototype._getTextureWrapMode = function (mode) {
  16110. switch (mode) {
  16111. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16112. return this._gl.REPEAT;
  16113. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16114. return this._gl.CLAMP_TO_EDGE;
  16115. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16116. return this._gl.MIRRORED_REPEAT;
  16117. }
  16118. return this._gl.REPEAT;
  16119. };
  16120. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16121. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16122. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16123. // Not ready?
  16124. if (!texture) {
  16125. if (this._boundTexturesCache[channel] != null) {
  16126. this._activeChannel = channel;
  16127. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16128. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16129. if (this.webGLVersion > 1) {
  16130. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16131. }
  16132. }
  16133. return false;
  16134. }
  16135. // Video
  16136. if (texture.video) {
  16137. this._activeChannel = channel;
  16138. texture.update();
  16139. }
  16140. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16141. texture.delayLoad();
  16142. return false;
  16143. }
  16144. var internalTexture;
  16145. if (depthStencilTexture) {
  16146. internalTexture = texture.depthStencilTexture;
  16147. }
  16148. else if (texture.isReady()) {
  16149. internalTexture = texture.getInternalTexture();
  16150. }
  16151. else if (texture.isCube) {
  16152. internalTexture = this.emptyCubeTexture;
  16153. }
  16154. else if (texture.is3D) {
  16155. internalTexture = this.emptyTexture3D;
  16156. }
  16157. else {
  16158. internalTexture = this.emptyTexture;
  16159. }
  16160. if (!isPartOfTextureArray) {
  16161. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16162. }
  16163. var needToBind = true;
  16164. if (this._boundTexturesCache[channel] === internalTexture) {
  16165. this._moveBoundTextureOnTop(internalTexture);
  16166. if (!isPartOfTextureArray) {
  16167. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16168. }
  16169. needToBind = false;
  16170. }
  16171. this._activeChannel = channel;
  16172. if (internalTexture && internalTexture.is3D) {
  16173. if (needToBind) {
  16174. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16175. }
  16176. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16177. internalTexture._cachedWrapU = texture.wrapU;
  16178. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16179. }
  16180. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16181. internalTexture._cachedWrapV = texture.wrapV;
  16182. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16183. }
  16184. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16185. internalTexture._cachedWrapR = texture.wrapR;
  16186. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16187. }
  16188. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16189. }
  16190. else if (internalTexture && internalTexture.isCube) {
  16191. if (needToBind) {
  16192. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16193. }
  16194. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16195. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16196. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16197. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16198. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16199. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16200. }
  16201. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16202. }
  16203. else {
  16204. if (needToBind) {
  16205. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16206. }
  16207. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16208. internalTexture._cachedWrapU = texture.wrapU;
  16209. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16210. }
  16211. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16212. internalTexture._cachedWrapV = texture.wrapV;
  16213. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16214. }
  16215. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16216. }
  16217. return true;
  16218. };
  16219. /**
  16220. * Sets an array of texture to the webGL context
  16221. * @param channel defines the channel where the texture array must be set
  16222. * @param uniform defines the associated uniform location
  16223. * @param textures defines the array of textures to bind
  16224. */
  16225. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16226. if (channel < 0 || !uniform) {
  16227. return;
  16228. }
  16229. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16230. this._textureUnits = new Int32Array(textures.length);
  16231. }
  16232. for (var i = 0; i < textures.length; i++) {
  16233. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16234. }
  16235. this._gl.uniform1iv(uniform, this._textureUnits);
  16236. for (var index = 0; index < textures.length; index++) {
  16237. this._setTexture(this._textureUnits[index], textures[index], true);
  16238. }
  16239. };
  16240. /** @ignore */
  16241. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16242. var internalTexture = texture.getInternalTexture();
  16243. if (!internalTexture) {
  16244. return;
  16245. }
  16246. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16247. var value = texture.anisotropicFilteringLevel;
  16248. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16249. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16250. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16251. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16252. }
  16253. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16254. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16255. internalTexture._cachedAnisotropicFilteringLevel = value;
  16256. }
  16257. };
  16258. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16259. this._bindTextureDirectly(target, texture, true, true);
  16260. this._gl.texParameterf(target, parameter, value);
  16261. };
  16262. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16263. if (texture) {
  16264. this._bindTextureDirectly(target, texture, true, true);
  16265. }
  16266. this._gl.texParameteri(target, parameter, value);
  16267. };
  16268. /**
  16269. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16270. * @param x defines the x coordinate of the rectangle where pixels must be read
  16271. * @param y defines the y coordinate of the rectangle where pixels must be read
  16272. * @param width defines the width of the rectangle where pixels must be read
  16273. * @param height defines the height of the rectangle where pixels must be read
  16274. * @returns a Uint8Array containing RGBA colors
  16275. */
  16276. Engine.prototype.readPixels = function (x, y, width, height) {
  16277. var data = new Uint8Array(height * width * 4);
  16278. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16279. return data;
  16280. };
  16281. /**
  16282. * Add an externaly attached data from its key.
  16283. * This method call will fail and return false, if such key already exists.
  16284. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16285. * @param key the unique key that identifies the data
  16286. * @param data the data object to associate to the key for this Engine instance
  16287. * @return true if no such key were already present and the data was added successfully, false otherwise
  16288. */
  16289. Engine.prototype.addExternalData = function (key, data) {
  16290. if (!this._externalData) {
  16291. this._externalData = new BABYLON.StringDictionary();
  16292. }
  16293. return this._externalData.add(key, data);
  16294. };
  16295. /**
  16296. * Get an externaly attached data from its key
  16297. * @param key the unique key that identifies the data
  16298. * @return the associated data, if present (can be null), or undefined if not present
  16299. */
  16300. Engine.prototype.getExternalData = function (key) {
  16301. if (!this._externalData) {
  16302. this._externalData = new BABYLON.StringDictionary();
  16303. }
  16304. return this._externalData.get(key);
  16305. };
  16306. /**
  16307. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16308. * @param key the unique key that identifies the data
  16309. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16310. * @return the associated data, can be null if the factory returned null.
  16311. */
  16312. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16313. if (!this._externalData) {
  16314. this._externalData = new BABYLON.StringDictionary();
  16315. }
  16316. return this._externalData.getOrAddWithFactory(key, factory);
  16317. };
  16318. /**
  16319. * Remove an externaly attached data from the Engine instance
  16320. * @param key the unique key that identifies the data
  16321. * @return true if the data was successfully removed, false if it doesn't exist
  16322. */
  16323. Engine.prototype.removeExternalData = function (key) {
  16324. if (!this._externalData) {
  16325. this._externalData = new BABYLON.StringDictionary();
  16326. }
  16327. return this._externalData.remove(key);
  16328. };
  16329. /**
  16330. * Unbind all vertex attributes from the webGL context
  16331. */
  16332. Engine.prototype.unbindAllAttributes = function () {
  16333. if (this._mustWipeVertexAttributes) {
  16334. this._mustWipeVertexAttributes = false;
  16335. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16336. this._gl.disableVertexAttribArray(i);
  16337. this._vertexAttribArraysEnabled[i] = false;
  16338. this._currentBufferPointers[i].active = false;
  16339. }
  16340. return;
  16341. }
  16342. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16343. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16344. continue;
  16345. }
  16346. this._gl.disableVertexAttribArray(i);
  16347. this._vertexAttribArraysEnabled[i] = false;
  16348. this._currentBufferPointers[i].active = false;
  16349. }
  16350. };
  16351. /**
  16352. * 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
  16353. */
  16354. Engine.prototype.releaseEffects = function () {
  16355. for (var name in this._compiledEffects) {
  16356. this._deleteProgram(this._compiledEffects[name]._program);
  16357. }
  16358. this._compiledEffects = {};
  16359. };
  16360. /**
  16361. * Dispose and release all associated resources
  16362. */
  16363. Engine.prototype.dispose = function () {
  16364. this.hideLoadingUI();
  16365. this.stopRenderLoop();
  16366. // Release postProcesses
  16367. while (this.postProcesses.length) {
  16368. this.postProcesses[0].dispose();
  16369. }
  16370. // Empty texture
  16371. if (this._emptyTexture) {
  16372. this._releaseTexture(this._emptyTexture);
  16373. this._emptyTexture = null;
  16374. }
  16375. if (this._emptyCubeTexture) {
  16376. this._releaseTexture(this._emptyCubeTexture);
  16377. this._emptyCubeTexture = null;
  16378. }
  16379. // Rescale PP
  16380. if (this._rescalePostProcess) {
  16381. this._rescalePostProcess.dispose();
  16382. }
  16383. // Release scenes
  16384. while (this.scenes.length) {
  16385. this.scenes[0].dispose();
  16386. }
  16387. // Release audio engine
  16388. if (Engine.audioEngine) {
  16389. Engine.audioEngine.dispose();
  16390. }
  16391. // Release effects
  16392. this.releaseEffects();
  16393. // Unbind
  16394. this.unbindAllAttributes();
  16395. this._boundUniforms = [];
  16396. if (this._dummyFramebuffer) {
  16397. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16398. }
  16399. //WebVR
  16400. this.disableVR();
  16401. // Events
  16402. if (BABYLON.Tools.IsWindowObjectExist()) {
  16403. window.removeEventListener("blur", this._onBlur);
  16404. window.removeEventListener("focus", this._onFocus);
  16405. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16406. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16407. if (this._renderingCanvas) {
  16408. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16409. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16410. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16411. if (!this._doNotHandleContextLost) {
  16412. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16413. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16414. }
  16415. }
  16416. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16417. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16418. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16419. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16420. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16421. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16422. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16423. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16424. if (this._onVrDisplayConnect) {
  16425. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16426. if (this._onVrDisplayDisconnect) {
  16427. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16428. }
  16429. if (this._onVrDisplayPresentChange) {
  16430. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16431. }
  16432. this._onVrDisplayConnect = null;
  16433. this._onVrDisplayDisconnect = null;
  16434. }
  16435. }
  16436. // Remove from Instances
  16437. var index = Engine.Instances.indexOf(this);
  16438. if (index >= 0) {
  16439. Engine.Instances.splice(index, 1);
  16440. }
  16441. this._workingCanvas = null;
  16442. this._workingContext = null;
  16443. this._currentBufferPointers = [];
  16444. this._renderingCanvas = null;
  16445. this._currentProgram = null;
  16446. this._bindedRenderFunction = null;
  16447. this.onResizeObservable.clear();
  16448. this.onCanvasBlurObservable.clear();
  16449. this.onCanvasFocusObservable.clear();
  16450. this.onCanvasPointerOutObservable.clear();
  16451. this.onBeginFrameObservable.clear();
  16452. this.onEndFrameObservable.clear();
  16453. BABYLON.Effect.ResetCache();
  16454. // Abort active requests
  16455. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16456. var request = _a[_i];
  16457. request.abort();
  16458. }
  16459. };
  16460. // Loading screen
  16461. /**
  16462. * Display the loading screen
  16463. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16464. */
  16465. Engine.prototype.displayLoadingUI = function () {
  16466. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16467. return;
  16468. }
  16469. var loadingScreen = this.loadingScreen;
  16470. if (loadingScreen) {
  16471. loadingScreen.displayLoadingUI();
  16472. }
  16473. };
  16474. /**
  16475. * Hide the loading screen
  16476. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16477. */
  16478. Engine.prototype.hideLoadingUI = function () {
  16479. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16480. return;
  16481. }
  16482. var loadingScreen = this.loadingScreen;
  16483. if (loadingScreen) {
  16484. loadingScreen.hideLoadingUI();
  16485. }
  16486. };
  16487. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16488. /**
  16489. * Gets the current loading screen object
  16490. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16491. */
  16492. get: function () {
  16493. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16494. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16495. return this._loadingScreen;
  16496. },
  16497. /**
  16498. * Sets the current loading screen object
  16499. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16500. */
  16501. set: function (loadingScreen) {
  16502. this._loadingScreen = loadingScreen;
  16503. },
  16504. enumerable: true,
  16505. configurable: true
  16506. });
  16507. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16508. /**
  16509. * Sets the current loading screen text
  16510. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16511. */
  16512. set: function (text) {
  16513. this.loadingScreen.loadingUIText = text;
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16519. /**
  16520. * Sets the current loading screen background color
  16521. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16522. */
  16523. set: function (color) {
  16524. this.loadingScreen.loadingUIBackgroundColor = color;
  16525. },
  16526. enumerable: true,
  16527. configurable: true
  16528. });
  16529. /**
  16530. * Attach a new callback raised when context lost event is fired
  16531. * @param callback defines the callback to call
  16532. */
  16533. Engine.prototype.attachContextLostEvent = function (callback) {
  16534. if (this._renderingCanvas) {
  16535. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16536. }
  16537. };
  16538. /**
  16539. * Attach a new callback raised when context restored event is fired
  16540. * @param callback defines the callback to call
  16541. */
  16542. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16543. if (this._renderingCanvas) {
  16544. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16545. }
  16546. };
  16547. /**
  16548. * Gets the source code of the vertex shader associated with a specific webGL program
  16549. * @param program defines the program to use
  16550. * @returns a string containing the source code of the vertex shader associated with the program
  16551. */
  16552. Engine.prototype.getVertexShaderSource = function (program) {
  16553. var shaders = this._gl.getAttachedShaders(program);
  16554. if (!shaders) {
  16555. return null;
  16556. }
  16557. return this._gl.getShaderSource(shaders[0]);
  16558. };
  16559. /**
  16560. * Gets the source code of the fragment shader associated with a specific webGL program
  16561. * @param program defines the program to use
  16562. * @returns a string containing the source code of the fragment shader associated with the program
  16563. */
  16564. Engine.prototype.getFragmentShaderSource = function (program) {
  16565. var shaders = this._gl.getAttachedShaders(program);
  16566. if (!shaders) {
  16567. return null;
  16568. }
  16569. return this._gl.getShaderSource(shaders[1]);
  16570. };
  16571. /**
  16572. * Get the current error code of the webGL context
  16573. * @returns the error code
  16574. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16575. */
  16576. Engine.prototype.getError = function () {
  16577. return this._gl.getError();
  16578. };
  16579. // FPS
  16580. /**
  16581. * Gets the current framerate
  16582. * @returns a number representing the framerate
  16583. */
  16584. Engine.prototype.getFps = function () {
  16585. return this._fps;
  16586. };
  16587. /**
  16588. * Gets the time spent between current and previous frame
  16589. * @returns a number representing the delta time in ms
  16590. */
  16591. Engine.prototype.getDeltaTime = function () {
  16592. return this._deltaTime;
  16593. };
  16594. Engine.prototype._measureFps = function () {
  16595. this._performanceMonitor.sampleFrame();
  16596. this._fps = this._performanceMonitor.averageFPS;
  16597. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16598. };
  16599. /** @ignore */
  16600. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16601. if (faceIndex === void 0) { faceIndex = -1; }
  16602. var gl = this._gl;
  16603. if (!this._dummyFramebuffer) {
  16604. var dummy = gl.createFramebuffer();
  16605. if (!dummy) {
  16606. throw new Error("Unable to create dummy framebuffer");
  16607. }
  16608. this._dummyFramebuffer = dummy;
  16609. }
  16610. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16611. if (faceIndex > -1) {
  16612. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16613. }
  16614. else {
  16615. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16616. }
  16617. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16618. var buffer;
  16619. switch (readType) {
  16620. case gl.UNSIGNED_BYTE:
  16621. buffer = new Uint8Array(4 * width * height);
  16622. readType = gl.UNSIGNED_BYTE;
  16623. break;
  16624. default:
  16625. buffer = new Float32Array(4 * width * height);
  16626. readType = gl.FLOAT;
  16627. break;
  16628. }
  16629. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16630. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16631. return buffer;
  16632. };
  16633. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16634. if (this._webGLVersion > 1) {
  16635. return this._caps.colorBufferFloat;
  16636. }
  16637. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16638. };
  16639. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16640. if (this._webGLVersion > 1) {
  16641. return this._caps.colorBufferFloat;
  16642. }
  16643. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16644. };
  16645. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16646. Engine.prototype._canRenderToFramebuffer = function (type) {
  16647. var gl = this._gl;
  16648. //clear existing errors
  16649. while (gl.getError() !== gl.NO_ERROR) { }
  16650. var successful = true;
  16651. var texture = gl.createTexture();
  16652. gl.bindTexture(gl.TEXTURE_2D, texture);
  16653. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16654. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16655. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16656. var fb = gl.createFramebuffer();
  16657. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16658. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16659. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16660. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16661. successful = successful && (gl.getError() === gl.NO_ERROR);
  16662. //try render by clearing frame buffer's color buffer
  16663. if (successful) {
  16664. gl.clear(gl.COLOR_BUFFER_BIT);
  16665. successful = successful && (gl.getError() === gl.NO_ERROR);
  16666. }
  16667. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16668. if (successful) {
  16669. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16670. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16671. var readFormat = gl.RGBA;
  16672. var readType = gl.UNSIGNED_BYTE;
  16673. var buffer = new Uint8Array(4);
  16674. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16675. successful = successful && (gl.getError() === gl.NO_ERROR);
  16676. }
  16677. //clean up
  16678. gl.deleteTexture(texture);
  16679. gl.deleteFramebuffer(fb);
  16680. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16681. //clear accumulated errors
  16682. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16683. return successful;
  16684. };
  16685. /** @ignore */
  16686. Engine.prototype._getWebGLTextureType = function (type) {
  16687. if (type === Engine.TEXTURETYPE_FLOAT) {
  16688. return this._gl.FLOAT;
  16689. }
  16690. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16691. // Add Half Float Constant.
  16692. return this._gl.HALF_FLOAT_OES;
  16693. }
  16694. return this._gl.UNSIGNED_BYTE;
  16695. };
  16696. ;
  16697. Engine.prototype._getInternalFormat = function (format) {
  16698. var internalFormat = this._gl.RGBA;
  16699. switch (format) {
  16700. case Engine.TEXTUREFORMAT_ALPHA:
  16701. internalFormat = this._gl.ALPHA;
  16702. break;
  16703. case Engine.TEXTUREFORMAT_LUMINANCE:
  16704. internalFormat = this._gl.LUMINANCE;
  16705. break;
  16706. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16707. internalFormat = this._gl.LUMINANCE_ALPHA;
  16708. break;
  16709. case Engine.TEXTUREFORMAT_RGB:
  16710. case Engine.TEXTUREFORMAT_RGB32F:
  16711. internalFormat = this._gl.RGB;
  16712. break;
  16713. case Engine.TEXTUREFORMAT_RGBA:
  16714. case Engine.TEXTUREFORMAT_RGBA32F:
  16715. internalFormat = this._gl.RGBA;
  16716. break;
  16717. case Engine.TEXTUREFORMAT_R32F:
  16718. internalFormat = this._gl.RED;
  16719. break;
  16720. case Engine.TEXTUREFORMAT_RG32F:
  16721. internalFormat = this._gl.RG;
  16722. break;
  16723. }
  16724. return internalFormat;
  16725. };
  16726. /** @ignore */
  16727. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16728. if (this._webGLVersion === 1) {
  16729. if (format) {
  16730. switch (format) {
  16731. case Engine.TEXTUREFORMAT_LUMINANCE:
  16732. return this._gl.LUMINANCE;
  16733. }
  16734. }
  16735. return this._gl.RGBA;
  16736. }
  16737. if (type === Engine.TEXTURETYPE_FLOAT) {
  16738. if (format) {
  16739. switch (format) {
  16740. case Engine.TEXTUREFORMAT_R32F:
  16741. return this._gl.R32F;
  16742. case Engine.TEXTUREFORMAT_RG32F:
  16743. return this._gl.RG32F;
  16744. case Engine.TEXTUREFORMAT_RGB32F:
  16745. return this._gl.RGB32F;
  16746. }
  16747. }
  16748. return this._gl.RGBA32F;
  16749. }
  16750. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16751. return this._gl.RGBA16F;
  16752. }
  16753. if (format) {
  16754. switch (format) {
  16755. case Engine.TEXTUREFORMAT_LUMINANCE:
  16756. return this._gl.LUMINANCE;
  16757. }
  16758. }
  16759. return this._gl.RGBA;
  16760. };
  16761. ;
  16762. /** @ignore */
  16763. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16764. if (type === Engine.TEXTURETYPE_FLOAT) {
  16765. return this._gl.RGBA32F;
  16766. }
  16767. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16768. return this._gl.RGBA16F;
  16769. }
  16770. return this._gl.RGBA8;
  16771. };
  16772. ;
  16773. /**
  16774. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16775. * @return the new query
  16776. */
  16777. Engine.prototype.createQuery = function () {
  16778. return this._gl.createQuery();
  16779. };
  16780. /**
  16781. * Delete and release a webGL query
  16782. * @param query defines the query to delete
  16783. * @return the current engine
  16784. */
  16785. Engine.prototype.deleteQuery = function (query) {
  16786. this._gl.deleteQuery(query);
  16787. return this;
  16788. };
  16789. /**
  16790. * Check if a given query has resolved and got its value
  16791. * @param query defines the query to check
  16792. * @returns true if the query got its value
  16793. */
  16794. Engine.prototype.isQueryResultAvailable = function (query) {
  16795. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16796. };
  16797. /**
  16798. * Gets the value of a given query
  16799. * @param query defines the query to check
  16800. * @returns the value of the query
  16801. */
  16802. Engine.prototype.getQueryResult = function (query) {
  16803. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16804. };
  16805. /**
  16806. * Initiates an occlusion query
  16807. * @param algorithmType defines the algorithm to use
  16808. * @param query defines the query to use
  16809. * @returns the current engine
  16810. * @see http://doc.babylonjs.com/features/occlusionquery
  16811. */
  16812. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16813. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16814. this._gl.beginQuery(glAlgorithm, query);
  16815. return this;
  16816. };
  16817. /**
  16818. * Ends an occlusion query
  16819. * @see http://doc.babylonjs.com/features/occlusionquery
  16820. * @param algorithmType defines the algorithm to use
  16821. * @returns the current engine
  16822. */
  16823. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  16824. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16825. this._gl.endQuery(glAlgorithm);
  16826. return this;
  16827. };
  16828. /* Time queries */
  16829. Engine.prototype._createTimeQuery = function () {
  16830. var timerQuery = this._caps.timerQuery;
  16831. if (timerQuery.createQueryEXT) {
  16832. return timerQuery.createQueryEXT();
  16833. }
  16834. return this.createQuery();
  16835. };
  16836. Engine.prototype._deleteTimeQuery = function (query) {
  16837. var timerQuery = this._caps.timerQuery;
  16838. if (timerQuery.deleteQueryEXT) {
  16839. timerQuery.deleteQueryEXT(query);
  16840. return;
  16841. }
  16842. this.deleteQuery(query);
  16843. };
  16844. Engine.prototype._getTimeQueryResult = function (query) {
  16845. var timerQuery = this._caps.timerQuery;
  16846. if (timerQuery.getQueryObjectEXT) {
  16847. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  16848. }
  16849. return this.getQueryResult(query);
  16850. };
  16851. Engine.prototype._getTimeQueryAvailability = function (query) {
  16852. var timerQuery = this._caps.timerQuery;
  16853. if (timerQuery.getQueryObjectEXT) {
  16854. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  16855. }
  16856. return this.isQueryResultAvailable(query);
  16857. };
  16858. /**
  16859. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  16860. * Please note that only one query can be issued at a time
  16861. * @returns a time token used to track the time span
  16862. */
  16863. Engine.prototype.startTimeQuery = function () {
  16864. var timerQuery = this._caps.timerQuery;
  16865. if (!timerQuery) {
  16866. return null;
  16867. }
  16868. var token = new BABYLON._TimeToken();
  16869. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16870. if (this._caps.canUseTimestampForTimerQuery) {
  16871. token._startTimeQuery = this._createTimeQuery();
  16872. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  16873. }
  16874. else {
  16875. if (this._currentNonTimestampToken) {
  16876. return this._currentNonTimestampToken;
  16877. }
  16878. token._timeElapsedQuery = this._createTimeQuery();
  16879. if (timerQuery.beginQueryEXT) {
  16880. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16881. }
  16882. else {
  16883. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  16884. }
  16885. this._currentNonTimestampToken = token;
  16886. }
  16887. return token;
  16888. };
  16889. /**
  16890. * Ends a time query
  16891. * @param token defines the token used to measure the time span
  16892. * @returns the time spent (in ns)
  16893. */
  16894. Engine.prototype.endTimeQuery = function (token) {
  16895. var timerQuery = this._caps.timerQuery;
  16896. if (!timerQuery || !token) {
  16897. return -1;
  16898. }
  16899. if (this._caps.canUseTimestampForTimerQuery) {
  16900. if (!token._startTimeQuery) {
  16901. return -1;
  16902. }
  16903. if (!token._endTimeQuery) {
  16904. token._endTimeQuery = this._createTimeQuery();
  16905. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  16906. }
  16907. }
  16908. else if (!token._timeElapsedQueryEnded) {
  16909. if (!token._timeElapsedQuery) {
  16910. return -1;
  16911. }
  16912. if (timerQuery.endQueryEXT) {
  16913. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  16914. }
  16915. else {
  16916. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  16917. }
  16918. token._timeElapsedQueryEnded = true;
  16919. }
  16920. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  16921. var available = false;
  16922. if (token._endTimeQuery) {
  16923. available = this._getTimeQueryAvailability(token._endTimeQuery);
  16924. }
  16925. else if (token._timeElapsedQuery) {
  16926. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  16927. }
  16928. if (available && !disjoint) {
  16929. var result = 0;
  16930. if (this._caps.canUseTimestampForTimerQuery) {
  16931. if (!token._startTimeQuery || !token._endTimeQuery) {
  16932. return -1;
  16933. }
  16934. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  16935. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  16936. result = timeEnd - timeStart;
  16937. this._deleteTimeQuery(token._startTimeQuery);
  16938. this._deleteTimeQuery(token._endTimeQuery);
  16939. token._startTimeQuery = null;
  16940. token._endTimeQuery = null;
  16941. }
  16942. else {
  16943. if (!token._timeElapsedQuery) {
  16944. return -1;
  16945. }
  16946. result = this._getTimeQueryResult(token._timeElapsedQuery);
  16947. this._deleteTimeQuery(token._timeElapsedQuery);
  16948. token._timeElapsedQuery = null;
  16949. token._timeElapsedQueryEnded = false;
  16950. this._currentNonTimestampToken = null;
  16951. }
  16952. return result;
  16953. }
  16954. return -1;
  16955. };
  16956. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  16957. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  16958. };
  16959. // Transform feedback
  16960. /**
  16961. * Creates a webGL transform feedback object
  16962. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  16963. * @returns the webGL transform feedback object
  16964. */
  16965. Engine.prototype.createTransformFeedback = function () {
  16966. return this._gl.createTransformFeedback();
  16967. };
  16968. /**
  16969. * Delete a webGL transform feedback object
  16970. * @param value defines the webGL transform feedback object to delete
  16971. */
  16972. Engine.prototype.deleteTransformFeedback = function (value) {
  16973. this._gl.deleteTransformFeedback(value);
  16974. };
  16975. /**
  16976. * Bind a webGL transform feedback object to the webgl context
  16977. * @param value defines the webGL transform feedback object to bind
  16978. */
  16979. Engine.prototype.bindTransformFeedback = function (value) {
  16980. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  16981. };
  16982. /**
  16983. * Begins a transform feedback operation
  16984. * @param usePoints defines if points or triangles must be used
  16985. */
  16986. Engine.prototype.beginTransformFeedback = function (usePoints) {
  16987. if (usePoints === void 0) { usePoints = true; }
  16988. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  16989. };
  16990. /**
  16991. * Ends a transform feedback operation
  16992. */
  16993. Engine.prototype.endTransformFeedback = function () {
  16994. this._gl.endTransformFeedback();
  16995. };
  16996. /**
  16997. * Specify the varyings to use with transform feedback
  16998. * @param program defines the associated webGL program
  16999. * @param value defines the list of strings representing the varying names
  17000. */
  17001. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17002. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17003. };
  17004. /**
  17005. * Bind a webGL buffer for a transform feedback operation
  17006. * @param value defines the webGL buffer to bind
  17007. */
  17008. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17009. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17010. };
  17011. /** @ignore */
  17012. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17013. var _this = this;
  17014. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17015. this._activeRequests.push(request);
  17016. request.onCompleteObservable.add(function (request) {
  17017. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17018. });
  17019. return request;
  17020. };
  17021. /** @ignore */
  17022. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17023. var _this = this;
  17024. return new Promise(function (resolve, reject) {
  17025. _this._loadFile(url, function (data) {
  17026. resolve(data);
  17027. }, undefined, database, useArrayBuffer, function (request, exception) {
  17028. reject(exception);
  17029. });
  17030. });
  17031. };
  17032. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17033. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17034. var onload = function (data) {
  17035. loadedFiles[index] = data;
  17036. loadedFiles._internalCount++;
  17037. if (loadedFiles._internalCount === 6) {
  17038. onfinish(loadedFiles);
  17039. }
  17040. };
  17041. var onerror = function (request, exception) {
  17042. if (onErrorCallBack && request) {
  17043. onErrorCallBack(request.status + " " + request.statusText, exception);
  17044. }
  17045. };
  17046. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17047. };
  17048. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17049. if (onError === void 0) { onError = null; }
  17050. var loadedFiles = [];
  17051. loadedFiles._internalCount = 0;
  17052. for (var index = 0; index < 6; index++) {
  17053. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17054. }
  17055. };
  17056. // Statics
  17057. /**
  17058. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17059. * @returns true if the engine can be created
  17060. * @ignoreNaming
  17061. */
  17062. Engine.isSupported = function () {
  17063. try {
  17064. var tempcanvas = document.createElement("canvas");
  17065. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17066. return gl != null && !!window.WebGLRenderingContext;
  17067. }
  17068. catch (e) {
  17069. return false;
  17070. }
  17071. };
  17072. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17073. Engine.ExceptionList = [
  17074. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17075. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17076. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17077. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17078. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17079. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17080. ];
  17081. /** Gets the list of created engines */
  17082. Engine.Instances = new Array();
  17083. // Const statics
  17084. Engine._ALPHA_DISABLE = 0;
  17085. Engine._ALPHA_ADD = 1;
  17086. Engine._ALPHA_COMBINE = 2;
  17087. Engine._ALPHA_SUBTRACT = 3;
  17088. Engine._ALPHA_MULTIPLY = 4;
  17089. Engine._ALPHA_MAXIMIZED = 5;
  17090. Engine._ALPHA_ONEONE = 6;
  17091. Engine._ALPHA_PREMULTIPLIED = 7;
  17092. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17093. Engine._ALPHA_INTERPOLATE = 9;
  17094. Engine._ALPHA_SCREENMODE = 10;
  17095. Engine._DELAYLOADSTATE_NONE = 0;
  17096. Engine._DELAYLOADSTATE_LOADED = 1;
  17097. Engine._DELAYLOADSTATE_LOADING = 2;
  17098. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17099. Engine._TEXTUREFORMAT_ALPHA = 0;
  17100. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17101. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17102. Engine._TEXTUREFORMAT_RGB = 4;
  17103. Engine._TEXTUREFORMAT_RGBA = 5;
  17104. Engine._TEXTUREFORMAT_R32F = 6;
  17105. Engine._TEXTUREFORMAT_RG32F = 7;
  17106. Engine._TEXTUREFORMAT_RGB32F = 8;
  17107. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17108. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17109. Engine._TEXTURETYPE_FLOAT = 1;
  17110. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17111. // Depht or Stencil test Constants.
  17112. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17113. 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.
  17114. 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.
  17115. 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.
  17116. 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.
  17117. 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.
  17118. 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.
  17119. 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.
  17120. // Stencil Actions Constants.
  17121. Engine._KEEP = 0x1E00;
  17122. Engine._REPLACE = 0x1E01;
  17123. Engine._INCR = 0x1E02;
  17124. Engine._DECR = 0x1E03;
  17125. Engine._INVERT = 0x150A;
  17126. Engine._INCR_WRAP = 0x8507;
  17127. Engine._DECR_WRAP = 0x8508;
  17128. // Texture rescaling mode
  17129. Engine._SCALEMODE_FLOOR = 1;
  17130. Engine._SCALEMODE_NEAREST = 2;
  17131. Engine._SCALEMODE_CEILING = 3;
  17132. // Updatable statics so stick with vars here
  17133. /**
  17134. * Gets or sets the epsilon value used by collision engine
  17135. */
  17136. Engine.CollisionsEpsilon = 0.001;
  17137. /**
  17138. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17139. */
  17140. Engine.CodeRepository = "src/";
  17141. /**
  17142. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17143. */
  17144. Engine.ShadersRepository = "src/Shaders/";
  17145. return Engine;
  17146. }());
  17147. BABYLON.Engine = Engine;
  17148. })(BABYLON || (BABYLON = {}));
  17149. //# sourceMappingURL=babylon.engine.js.map
  17150. var BABYLON;
  17151. (function (BABYLON) {
  17152. /**
  17153. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17154. */
  17155. var Node = /** @class */ (function () {
  17156. /**
  17157. * Creates a new Node
  17158. * @param {string} name - the name and id to be given to this node
  17159. * @param {BABYLON.Scene} the scene this node will be added to
  17160. */
  17161. function Node(name, scene) {
  17162. if (scene === void 0) { scene = null; }
  17163. /**
  17164. * Gets or sets a string used to store user defined state for the node
  17165. */
  17166. this.state = "";
  17167. /**
  17168. * Gets or sets an object used to store user defined information for the node
  17169. */
  17170. this.metadata = null;
  17171. /**
  17172. * Gets or sets a boolean used to define if the node must be serialized
  17173. */
  17174. this.doNotSerialize = false;
  17175. /** @ignore */
  17176. this._isDisposed = false;
  17177. /**
  17178. * Gets a list of Animations associated with the node
  17179. */
  17180. this.animations = new Array();
  17181. this._ranges = {};
  17182. this._isEnabled = true;
  17183. this._isReady = true;
  17184. /** @ignore */
  17185. this._currentRenderId = -1;
  17186. this._parentRenderId = -1;
  17187. this._childRenderId = -1;
  17188. this._animationPropertiesOverride = null;
  17189. /**
  17190. * An event triggered when the mesh is disposed
  17191. */
  17192. this.onDisposeObservable = new BABYLON.Observable();
  17193. // Behaviors
  17194. this._behaviors = new Array();
  17195. this.name = name;
  17196. this.id = name;
  17197. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17198. this.uniqueId = this._scene.getUniqueId();
  17199. this._initCache();
  17200. }
  17201. /**
  17202. * Gets a boolean indicating if the node has been disposed
  17203. * @returns true if the node was disposed
  17204. */
  17205. Node.prototype.isDisposed = function () {
  17206. return this._isDisposed;
  17207. };
  17208. Object.defineProperty(Node.prototype, "parent", {
  17209. get: function () {
  17210. return this._parentNode;
  17211. },
  17212. /**
  17213. * Gets or sets the parent of the node
  17214. */
  17215. set: function (parent) {
  17216. if (this._parentNode === parent) {
  17217. return;
  17218. }
  17219. // Remove self from list of children of parent
  17220. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17221. var index = this._parentNode._children.indexOf(this);
  17222. if (index !== -1) {
  17223. this._parentNode._children.splice(index, 1);
  17224. }
  17225. }
  17226. // Store new parent
  17227. this._parentNode = parent;
  17228. // Add as child to new parent
  17229. if (this._parentNode) {
  17230. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17231. this._parentNode._children = new Array();
  17232. }
  17233. this._parentNode._children.push(this);
  17234. }
  17235. },
  17236. enumerable: true,
  17237. configurable: true
  17238. });
  17239. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17240. /**
  17241. * Gets or sets the animation properties override
  17242. */
  17243. get: function () {
  17244. if (!this._animationPropertiesOverride) {
  17245. return this._scene.animationPropertiesOverride;
  17246. }
  17247. return this._animationPropertiesOverride;
  17248. },
  17249. set: function (value) {
  17250. this._animationPropertiesOverride = value;
  17251. },
  17252. enumerable: true,
  17253. configurable: true
  17254. });
  17255. /**
  17256. * Gets a string idenfifying the name of the class
  17257. * @returns "Node" string
  17258. */
  17259. Node.prototype.getClassName = function () {
  17260. return "Node";
  17261. };
  17262. Object.defineProperty(Node.prototype, "onDispose", {
  17263. /**
  17264. * Sets a callback that will be raised when the node will be disposed
  17265. */
  17266. set: function (callback) {
  17267. if (this._onDisposeObserver) {
  17268. this.onDisposeObservable.remove(this._onDisposeObserver);
  17269. }
  17270. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17271. },
  17272. enumerable: true,
  17273. configurable: true
  17274. });
  17275. /**
  17276. * Gets the scene of the node
  17277. * @returns a {BABYLON.Scene}
  17278. */
  17279. Node.prototype.getScene = function () {
  17280. return this._scene;
  17281. };
  17282. /**
  17283. * Gets the engine of the node
  17284. * @returns a {BABYLON.Engine}
  17285. */
  17286. Node.prototype.getEngine = function () {
  17287. return this._scene.getEngine();
  17288. };
  17289. /**
  17290. * Attach a behavior to the node
  17291. * @see http://doc.babylonjs.com/features/behaviour
  17292. * @param behavior defines the behavior to attach
  17293. * @returns the current Node
  17294. */
  17295. Node.prototype.addBehavior = function (behavior) {
  17296. var _this = this;
  17297. var index = this._behaviors.indexOf(behavior);
  17298. if (index !== -1) {
  17299. return this;
  17300. }
  17301. behavior.init();
  17302. if (this._scene.isLoading) {
  17303. // We defer the attach when the scene will be loaded
  17304. var observer = this._scene.onDataLoadedObservable.add(function () {
  17305. behavior.attach(_this);
  17306. setTimeout(function () {
  17307. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17308. _this._scene.onDataLoadedObservable.remove(observer);
  17309. }, 0);
  17310. });
  17311. }
  17312. else {
  17313. behavior.attach(this);
  17314. }
  17315. this._behaviors.push(behavior);
  17316. return this;
  17317. };
  17318. /**
  17319. * Remove an attached behavior
  17320. * @see http://doc.babylonjs.com/features/behaviour
  17321. * @param behavior defines the behavior to attach
  17322. * @returns the current Node
  17323. */
  17324. Node.prototype.removeBehavior = function (behavior) {
  17325. var index = this._behaviors.indexOf(behavior);
  17326. if (index === -1) {
  17327. return this;
  17328. }
  17329. this._behaviors[index].detach();
  17330. this._behaviors.splice(index, 1);
  17331. return this;
  17332. };
  17333. Object.defineProperty(Node.prototype, "behaviors", {
  17334. /**
  17335. * Gets the list of attached behaviors
  17336. * @see http://doc.babylonjs.com/features/behaviour
  17337. */
  17338. get: function () {
  17339. return this._behaviors;
  17340. },
  17341. enumerable: true,
  17342. configurable: true
  17343. });
  17344. /**
  17345. * Gets an attached behavior by name
  17346. * @param name defines the name of the behavior to look for
  17347. * @see http://doc.babylonjs.com/features/behaviour
  17348. * @returns null if behavior was not found else the requested behavior
  17349. */
  17350. Node.prototype.getBehaviorByName = function (name) {
  17351. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17352. var behavior = _a[_i];
  17353. if (behavior.name === name) {
  17354. return behavior;
  17355. }
  17356. }
  17357. return null;
  17358. };
  17359. /**
  17360. * Returns the world matrix of the node
  17361. * @returns a matrix containing the node's world matrix
  17362. */
  17363. Node.prototype.getWorldMatrix = function () {
  17364. return BABYLON.Matrix.Identity();
  17365. };
  17366. // override it in derived class if you add new variables to the cache
  17367. // and call the parent class method
  17368. /** @ignore */
  17369. Node.prototype._initCache = function () {
  17370. this._cache = {};
  17371. this._cache.parent = undefined;
  17372. };
  17373. /** @ignore */
  17374. Node.prototype.updateCache = function (force) {
  17375. if (!force && this.isSynchronized())
  17376. return;
  17377. this._cache.parent = this.parent;
  17378. this._updateCache();
  17379. };
  17380. // override it in derived class if you add new variables to the cache
  17381. // and call the parent class method if !ignoreParentClass
  17382. /** @ignore */
  17383. Node.prototype._updateCache = function (ignoreParentClass) {
  17384. };
  17385. // override it in derived class if you add new variables to the cache
  17386. /** @ignore */
  17387. Node.prototype._isSynchronized = function () {
  17388. return true;
  17389. };
  17390. /** @ignore */
  17391. Node.prototype._markSyncedWithParent = function () {
  17392. if (this.parent) {
  17393. this._parentRenderId = this.parent._childRenderId;
  17394. }
  17395. };
  17396. /** @ignore */
  17397. Node.prototype.isSynchronizedWithParent = function () {
  17398. if (!this.parent) {
  17399. return true;
  17400. }
  17401. if (this._parentRenderId !== this.parent._childRenderId) {
  17402. return false;
  17403. }
  17404. return this.parent.isSynchronized();
  17405. };
  17406. /** @ignore */
  17407. Node.prototype.isSynchronized = function (updateCache) {
  17408. var check = this.hasNewParent();
  17409. check = check || !this.isSynchronizedWithParent();
  17410. check = check || !this._isSynchronized();
  17411. if (updateCache)
  17412. this.updateCache(true);
  17413. return !check;
  17414. };
  17415. /** @ignore */
  17416. Node.prototype.hasNewParent = function (update) {
  17417. if (this._cache.parent === this.parent)
  17418. return false;
  17419. if (update)
  17420. this._cache.parent = this.parent;
  17421. return true;
  17422. };
  17423. /**
  17424. * Is this node ready to be used/rendered
  17425. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17426. * @return true if the node is ready
  17427. */
  17428. Node.prototype.isReady = function (completeCheck) {
  17429. if (completeCheck === void 0) { completeCheck = false; }
  17430. return this._isReady;
  17431. };
  17432. /**
  17433. * Is this node enabled?
  17434. * 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
  17435. * @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
  17436. * @return whether this node (and its parent) is enabled
  17437. */
  17438. Node.prototype.isEnabled = function (checkAncestors) {
  17439. if (checkAncestors === void 0) { checkAncestors = true; }
  17440. if (checkAncestors === false) {
  17441. return this._isEnabled;
  17442. }
  17443. if (this._isEnabled === false) {
  17444. return false;
  17445. }
  17446. if (this.parent !== undefined && this.parent !== null) {
  17447. return this.parent.isEnabled(checkAncestors);
  17448. }
  17449. return true;
  17450. };
  17451. /**
  17452. * Set the enabled state of this node
  17453. * @param value defines the new enabled state
  17454. */
  17455. Node.prototype.setEnabled = function (value) {
  17456. this._isEnabled = value;
  17457. };
  17458. /**
  17459. * Is this node a descendant of the given node?
  17460. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17461. * @param ancestor defines the parent node to inspect
  17462. * @returns a boolean indicating if this node is a descendant of the given node
  17463. */
  17464. Node.prototype.isDescendantOf = function (ancestor) {
  17465. if (this.parent) {
  17466. if (this.parent === ancestor) {
  17467. return true;
  17468. }
  17469. return this.parent.isDescendantOf(ancestor);
  17470. }
  17471. return false;
  17472. };
  17473. /** @ignore */
  17474. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17475. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17476. if (!this._children) {
  17477. return;
  17478. }
  17479. for (var index = 0; index < this._children.length; index++) {
  17480. var item = this._children[index];
  17481. if (!predicate || predicate(item)) {
  17482. results.push(item);
  17483. }
  17484. if (!directDescendantsOnly) {
  17485. item._getDescendants(results, false, predicate);
  17486. }
  17487. }
  17488. };
  17489. /**
  17490. * Will return all nodes that have this node as ascendant
  17491. * @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
  17492. * @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
  17493. * @return all children nodes of all types
  17494. */
  17495. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17496. var results = new Array();
  17497. this._getDescendants(results, directDescendantsOnly, predicate);
  17498. return results;
  17499. };
  17500. /**
  17501. * Get all child-meshes of this node
  17502. * @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
  17503. * @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
  17504. * @returns an array of {BABYLON.AbstractMesh}
  17505. */
  17506. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17507. var results = [];
  17508. this._getDescendants(results, directDescendantsOnly, function (node) {
  17509. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17510. });
  17511. return results;
  17512. };
  17513. /**
  17514. * Get all child-transformNodes of this node
  17515. * @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
  17516. * @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
  17517. * @returns an array of {BABYLON.TransformNode}
  17518. */
  17519. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17520. var results = [];
  17521. this._getDescendants(results, directDescendantsOnly, function (node) {
  17522. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17523. });
  17524. return results;
  17525. };
  17526. /**
  17527. * Get all direct children of this node
  17528. * @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
  17529. * @returns an array of {BABYLON.Node}
  17530. */
  17531. Node.prototype.getChildren = function (predicate) {
  17532. return this.getDescendants(true, predicate);
  17533. };
  17534. /** @ignore */
  17535. Node.prototype._setReady = function (state) {
  17536. if (state === this._isReady) {
  17537. return;
  17538. }
  17539. if (!state) {
  17540. this._isReady = false;
  17541. return;
  17542. }
  17543. if (this.onReady) {
  17544. this.onReady(this);
  17545. }
  17546. this._isReady = true;
  17547. };
  17548. /**
  17549. * Get an animation by name
  17550. * @param name defines the name of the animation to look for
  17551. * @returns null if not found else the requested animation
  17552. */
  17553. Node.prototype.getAnimationByName = function (name) {
  17554. for (var i = 0; i < this.animations.length; i++) {
  17555. var animation = this.animations[i];
  17556. if (animation.name === name) {
  17557. return animation;
  17558. }
  17559. }
  17560. return null;
  17561. };
  17562. /**
  17563. * Creates an animation range for this node
  17564. * @param name defines the name of the range
  17565. * @param from defines the starting key
  17566. * @param to defines the end key
  17567. */
  17568. Node.prototype.createAnimationRange = function (name, from, to) {
  17569. // check name not already in use
  17570. if (!this._ranges[name]) {
  17571. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17572. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17573. if (this.animations[i]) {
  17574. this.animations[i].createRange(name, from, to);
  17575. }
  17576. }
  17577. }
  17578. };
  17579. /**
  17580. * Delete a specific animation range
  17581. * @param name defines the name of the range to delete
  17582. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17583. */
  17584. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17585. if (deleteFrames === void 0) { deleteFrames = true; }
  17586. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17587. if (this.animations[i]) {
  17588. this.animations[i].deleteRange(name, deleteFrames);
  17589. }
  17590. }
  17591. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17592. };
  17593. /**
  17594. * Get an animation range by name
  17595. * @param name defines the name of the animation range to look for
  17596. * @returns null if not found else the requested animation range
  17597. */
  17598. Node.prototype.getAnimationRange = function (name) {
  17599. return this._ranges[name];
  17600. };
  17601. /**
  17602. * Will start the animation sequence
  17603. * @param name defines the range frames for animation sequence
  17604. * @param loop defines if the animation should loop (false by default)
  17605. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17606. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17607. * @returns the object created for this animation. If range does not exist, it will return null
  17608. */
  17609. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17610. var range = this.getAnimationRange(name);
  17611. if (!range) {
  17612. return null;
  17613. }
  17614. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17615. };
  17616. /**
  17617. * Serialize animation ranges into a JSON compatible object
  17618. * @returns serialization object
  17619. */
  17620. Node.prototype.serializeAnimationRanges = function () {
  17621. var serializationRanges = [];
  17622. for (var name in this._ranges) {
  17623. var localRange = this._ranges[name];
  17624. if (!localRange) {
  17625. continue;
  17626. }
  17627. var range = {};
  17628. range.name = name;
  17629. range.from = localRange.from;
  17630. range.to = localRange.to;
  17631. serializationRanges.push(range);
  17632. }
  17633. return serializationRanges;
  17634. };
  17635. /**
  17636. * Computes the world matrix of the node
  17637. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17638. * @returns the world matrix
  17639. */
  17640. Node.prototype.computeWorldMatrix = function (force) {
  17641. return BABYLON.Matrix.Identity();
  17642. };
  17643. /**
  17644. * Releases resources associated with this node.
  17645. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17646. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17647. */
  17648. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17649. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17650. if (!doNotRecurse) {
  17651. var nodes = this.getDescendants(true);
  17652. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17653. var node = nodes_1[_i];
  17654. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17655. }
  17656. }
  17657. else {
  17658. var transformNodes = this.getChildTransformNodes(true);
  17659. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17660. var transformNode = transformNodes_1[_a];
  17661. transformNode.parent = null;
  17662. transformNode.computeWorldMatrix(true);
  17663. }
  17664. }
  17665. this.parent = null;
  17666. // Callback
  17667. this.onDisposeObservable.notifyObservers(this);
  17668. this.onDisposeObservable.clear();
  17669. // Behaviors
  17670. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17671. var behavior = _c[_b];
  17672. behavior.detach();
  17673. }
  17674. this._behaviors = [];
  17675. this._isDisposed = true;
  17676. };
  17677. /**
  17678. * Parse animation range data from a serialization object and store them into a given node
  17679. * @param node defines where to store the animation ranges
  17680. * @param parsedNode defines the serialization object to read data from
  17681. * @param scene defines the hosting scene
  17682. */
  17683. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17684. if (parsedNode.ranges) {
  17685. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17686. var data = parsedNode.ranges[index];
  17687. node.createAnimationRange(data.name, data.from, data.to);
  17688. }
  17689. }
  17690. };
  17691. __decorate([
  17692. BABYLON.serialize()
  17693. ], Node.prototype, "name", void 0);
  17694. __decorate([
  17695. BABYLON.serialize()
  17696. ], Node.prototype, "id", void 0);
  17697. __decorate([
  17698. BABYLON.serialize()
  17699. ], Node.prototype, "uniqueId", void 0);
  17700. __decorate([
  17701. BABYLON.serialize()
  17702. ], Node.prototype, "state", void 0);
  17703. __decorate([
  17704. BABYLON.serialize()
  17705. ], Node.prototype, "metadata", void 0);
  17706. return Node;
  17707. }());
  17708. BABYLON.Node = Node;
  17709. })(BABYLON || (BABYLON = {}));
  17710. //# sourceMappingURL=babylon.node.js.map
  17711. var BABYLON;
  17712. (function (BABYLON) {
  17713. var BoundingSphere = /** @class */ (function () {
  17714. /**
  17715. * Creates a new bounding sphere
  17716. * @param min defines the minimum vector (in local space)
  17717. * @param max defines the maximum vector (in local space)
  17718. */
  17719. function BoundingSphere(min, max) {
  17720. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17721. this.reConstruct(min, max);
  17722. }
  17723. /**
  17724. * Recreates the entire bounding sphere from scratch
  17725. * @param min defines the new minimum vector (in local space)
  17726. * @param max defines the new maximum vector (in local space)
  17727. */
  17728. BoundingSphere.prototype.reConstruct = function (min, max) {
  17729. this.minimum = min.clone();
  17730. this.maximum = max.clone();
  17731. var distance = BABYLON.Vector3.Distance(min, max);
  17732. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17733. this.radius = distance * 0.5;
  17734. this.centerWorld = BABYLON.Vector3.Zero();
  17735. this._update(BABYLON.Matrix.Identity());
  17736. };
  17737. // Methods
  17738. BoundingSphere.prototype._update = function (world) {
  17739. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17740. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17741. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17742. };
  17743. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17744. for (var i = 0; i < 6; i++) {
  17745. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17746. return false;
  17747. }
  17748. return true;
  17749. };
  17750. BoundingSphere.prototype.intersectsPoint = function (point) {
  17751. var x = this.centerWorld.x - point.x;
  17752. var y = this.centerWorld.y - point.y;
  17753. var z = this.centerWorld.z - point.z;
  17754. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17755. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17756. return false;
  17757. return true;
  17758. };
  17759. // Statics
  17760. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17761. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17762. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17763. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17764. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17765. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17766. return false;
  17767. return true;
  17768. };
  17769. return BoundingSphere;
  17770. }());
  17771. BABYLON.BoundingSphere = BoundingSphere;
  17772. })(BABYLON || (BABYLON = {}));
  17773. //# sourceMappingURL=babylon.boundingSphere.js.map
  17774. var BABYLON;
  17775. (function (BABYLON) {
  17776. var BoundingBox = /** @class */ (function () {
  17777. /**
  17778. * Creates a new bounding box
  17779. * @param min defines the minimum vector (in local space)
  17780. * @param max defines the maximum vector (in local space)
  17781. */
  17782. function BoundingBox(min, max) {
  17783. this.vectorsWorld = new Array();
  17784. this.reConstruct(min, max);
  17785. }
  17786. // Methods
  17787. /**
  17788. * Recreates the entire bounding box from scratch
  17789. * @param min defines the new minimum vector (in local space)
  17790. * @param max defines the new maximum vector (in local space)
  17791. */
  17792. BoundingBox.prototype.reConstruct = function (min, max) {
  17793. this.minimum = min.clone();
  17794. this.maximum = max.clone();
  17795. // Bounding vectors
  17796. this.vectors = new Array();
  17797. this.vectors.push(this.minimum.clone());
  17798. this.vectors.push(this.maximum.clone());
  17799. this.vectors.push(this.minimum.clone());
  17800. this.vectors[2].x = this.maximum.x;
  17801. this.vectors.push(this.minimum.clone());
  17802. this.vectors[3].y = this.maximum.y;
  17803. this.vectors.push(this.minimum.clone());
  17804. this.vectors[4].z = this.maximum.z;
  17805. this.vectors.push(this.maximum.clone());
  17806. this.vectors[5].z = this.minimum.z;
  17807. this.vectors.push(this.maximum.clone());
  17808. this.vectors[6].x = this.minimum.x;
  17809. this.vectors.push(this.maximum.clone());
  17810. this.vectors[7].y = this.minimum.y;
  17811. // OBB
  17812. this.center = this.maximum.add(this.minimum).scale(0.5);
  17813. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17814. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17815. // World
  17816. for (var index = 0; index < this.vectors.length; index++) {
  17817. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  17818. }
  17819. this.minimumWorld = BABYLON.Vector3.Zero();
  17820. this.maximumWorld = BABYLON.Vector3.Zero();
  17821. this.centerWorld = BABYLON.Vector3.Zero();
  17822. this.extendSizeWorld = BABYLON.Vector3.Zero();
  17823. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  17824. };
  17825. BoundingBox.prototype.getWorldMatrix = function () {
  17826. return this._worldMatrix;
  17827. };
  17828. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  17829. this._worldMatrix.copyFrom(matrix);
  17830. return this;
  17831. };
  17832. BoundingBox.prototype._update = function (world) {
  17833. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  17834. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  17835. for (var index = 0; index < this.vectors.length; index++) {
  17836. var v = this.vectorsWorld[index];
  17837. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  17838. if (v.x < this.minimumWorld.x)
  17839. this.minimumWorld.x = v.x;
  17840. if (v.y < this.minimumWorld.y)
  17841. this.minimumWorld.y = v.y;
  17842. if (v.z < this.minimumWorld.z)
  17843. this.minimumWorld.z = v.z;
  17844. if (v.x > this.maximumWorld.x)
  17845. this.maximumWorld.x = v.x;
  17846. if (v.y > this.maximumWorld.y)
  17847. this.maximumWorld.y = v.y;
  17848. if (v.z > this.maximumWorld.z)
  17849. this.maximumWorld.z = v.z;
  17850. }
  17851. // Extend
  17852. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  17853. this.extendSizeWorld.scaleInPlace(0.5);
  17854. // OBB
  17855. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  17856. this.centerWorld.scaleInPlace(0.5);
  17857. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  17858. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  17859. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  17860. this._worldMatrix = world;
  17861. };
  17862. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  17863. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  17864. };
  17865. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17866. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  17867. };
  17868. BoundingBox.prototype.intersectsPoint = function (point) {
  17869. var delta = -BABYLON.Epsilon;
  17870. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  17871. return false;
  17872. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  17873. return false;
  17874. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  17875. return false;
  17876. return true;
  17877. };
  17878. BoundingBox.prototype.intersectsSphere = function (sphere) {
  17879. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  17880. };
  17881. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  17882. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  17883. return false;
  17884. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  17885. return false;
  17886. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  17887. return false;
  17888. return true;
  17889. };
  17890. // Statics
  17891. BoundingBox.Intersects = function (box0, box1) {
  17892. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  17893. return false;
  17894. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  17895. return false;
  17896. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  17897. return false;
  17898. return true;
  17899. };
  17900. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  17901. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  17902. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  17903. return (num <= (sphereRadius * sphereRadius));
  17904. };
  17905. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  17906. for (var p = 0; p < 6; p++) {
  17907. for (var i = 0; i < 8; i++) {
  17908. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17909. return false;
  17910. }
  17911. }
  17912. }
  17913. return true;
  17914. };
  17915. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  17916. for (var p = 0; p < 6; p++) {
  17917. var inCount = 8;
  17918. for (var i = 0; i < 8; i++) {
  17919. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  17920. --inCount;
  17921. }
  17922. else {
  17923. break;
  17924. }
  17925. }
  17926. if (inCount === 0)
  17927. return false;
  17928. }
  17929. return true;
  17930. };
  17931. return BoundingBox;
  17932. }());
  17933. BABYLON.BoundingBox = BoundingBox;
  17934. })(BABYLON || (BABYLON = {}));
  17935. //# sourceMappingURL=babylon.boundingBox.js.map
  17936. var BABYLON;
  17937. (function (BABYLON) {
  17938. var computeBoxExtents = function (axis, box) {
  17939. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  17940. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  17941. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  17942. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  17943. var r = r0 + r1 + r2;
  17944. return {
  17945. min: p - r,
  17946. max: p + r
  17947. };
  17948. };
  17949. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  17950. var axisOverlap = function (axis, box0, box1) {
  17951. var result0 = computeBoxExtents(axis, box0);
  17952. var result1 = computeBoxExtents(axis, box1);
  17953. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  17954. };
  17955. var BoundingInfo = /** @class */ (function () {
  17956. function BoundingInfo(minimum, maximum) {
  17957. this.minimum = minimum;
  17958. this.maximum = maximum;
  17959. this._isLocked = false;
  17960. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  17961. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  17962. }
  17963. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  17964. get: function () {
  17965. return this._isLocked;
  17966. },
  17967. set: function (value) {
  17968. this._isLocked = value;
  17969. },
  17970. enumerable: true,
  17971. configurable: true
  17972. });
  17973. // Methods
  17974. BoundingInfo.prototype.update = function (world) {
  17975. if (this._isLocked) {
  17976. return;
  17977. }
  17978. this.boundingBox._update(world);
  17979. this.boundingSphere._update(world);
  17980. };
  17981. /**
  17982. * Recreate the bounding info to be centered around a specific point given a specific extend.
  17983. * @param center New center of the bounding info
  17984. * @param extend New extend of the bounding info
  17985. */
  17986. BoundingInfo.prototype.centerOn = function (center, extend) {
  17987. this.minimum = center.subtract(extend);
  17988. this.maximum = center.add(extend);
  17989. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  17990. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  17991. return this;
  17992. };
  17993. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  17994. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  17995. return false;
  17996. return this.boundingBox.isInFrustum(frustumPlanes);
  17997. };
  17998. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  17999. /**
  18000. * Gets the world distance between the min and max points of the bounding box
  18001. */
  18002. get: function () {
  18003. var boundingBox = this.boundingBox;
  18004. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18005. return size.length();
  18006. },
  18007. enumerable: true,
  18008. configurable: true
  18009. });
  18010. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18011. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18012. };
  18013. BoundingInfo.prototype._checkCollision = function (collider) {
  18014. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18015. };
  18016. BoundingInfo.prototype.intersectsPoint = function (point) {
  18017. if (!this.boundingSphere.centerWorld) {
  18018. return false;
  18019. }
  18020. if (!this.boundingSphere.intersectsPoint(point)) {
  18021. return false;
  18022. }
  18023. if (!this.boundingBox.intersectsPoint(point)) {
  18024. return false;
  18025. }
  18026. return true;
  18027. };
  18028. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18029. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18030. return false;
  18031. }
  18032. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18033. return false;
  18034. }
  18035. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18036. return false;
  18037. }
  18038. if (!precise) {
  18039. return true;
  18040. }
  18041. var box0 = this.boundingBox;
  18042. var box1 = boundingInfo.boundingBox;
  18043. if (!axisOverlap(box0.directions[0], box0, box1))
  18044. return false;
  18045. if (!axisOverlap(box0.directions[1], box0, box1))
  18046. return false;
  18047. if (!axisOverlap(box0.directions[2], box0, box1))
  18048. return false;
  18049. if (!axisOverlap(box1.directions[0], box0, box1))
  18050. return false;
  18051. if (!axisOverlap(box1.directions[1], box0, box1))
  18052. return false;
  18053. if (!axisOverlap(box1.directions[2], box0, box1))
  18054. return false;
  18055. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18056. return false;
  18057. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18058. return false;
  18059. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18060. return false;
  18061. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18062. return false;
  18063. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18064. return false;
  18065. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18066. return false;
  18067. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18068. return false;
  18069. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18070. return false;
  18071. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18072. return false;
  18073. return true;
  18074. };
  18075. return BoundingInfo;
  18076. }());
  18077. BABYLON.BoundingInfo = BoundingInfo;
  18078. })(BABYLON || (BABYLON = {}));
  18079. //# sourceMappingURL=babylon.boundingInfo.js.map
  18080. var BABYLON;
  18081. (function (BABYLON) {
  18082. var TransformNode = /** @class */ (function (_super) {
  18083. __extends(TransformNode, _super);
  18084. function TransformNode(name, scene, isPure) {
  18085. if (scene === void 0) { scene = null; }
  18086. if (isPure === void 0) { isPure = true; }
  18087. var _this = _super.call(this, name, scene) || this;
  18088. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18089. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18090. _this._up = new BABYLON.Vector3(0, 1, 0);
  18091. _this._right = new BABYLON.Vector3(1, 0, 0);
  18092. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18093. // Properties
  18094. _this._rotation = BABYLON.Vector3.Zero();
  18095. _this._scaling = BABYLON.Vector3.One();
  18096. _this._isDirty = false;
  18097. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18098. _this.scalingDeterminant = 1;
  18099. _this.infiniteDistance = false;
  18100. _this.position = BABYLON.Vector3.Zero();
  18101. _this._localWorld = BABYLON.Matrix.Zero();
  18102. _this._worldMatrix = BABYLON.Matrix.Zero();
  18103. _this._worldMatrixDeterminant = 0;
  18104. _this._absolutePosition = BABYLON.Vector3.Zero();
  18105. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18106. _this._postMultiplyPivotMatrix = false;
  18107. _this._isWorldMatrixFrozen = false;
  18108. /**
  18109. * An event triggered after the world matrix is updated
  18110. */
  18111. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18112. _this._nonUniformScaling = false;
  18113. if (isPure) {
  18114. _this.getScene().addTransformNode(_this);
  18115. }
  18116. return _this;
  18117. }
  18118. /**
  18119. * Gets a string idenfifying the name of the class
  18120. * @returns "TransformNode" string
  18121. */
  18122. TransformNode.prototype.getClassName = function () {
  18123. return "TransformNode";
  18124. };
  18125. Object.defineProperty(TransformNode.prototype, "rotation", {
  18126. /**
  18127. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18128. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18129. * Default : (0.0, 0.0, 0.0)
  18130. */
  18131. get: function () {
  18132. return this._rotation;
  18133. },
  18134. set: function (newRotation) {
  18135. this._rotation = newRotation;
  18136. },
  18137. enumerable: true,
  18138. configurable: true
  18139. });
  18140. Object.defineProperty(TransformNode.prototype, "scaling", {
  18141. /**
  18142. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18143. * Default : (1.0, 1.0, 1.0)
  18144. */
  18145. get: function () {
  18146. return this._scaling;
  18147. },
  18148. /**
  18149. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18150. * Default : (1.0, 1.0, 1.0)
  18151. */
  18152. set: function (newScaling) {
  18153. this._scaling = newScaling;
  18154. },
  18155. enumerable: true,
  18156. configurable: true
  18157. });
  18158. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18159. /**
  18160. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18161. * It's null by default.
  18162. * 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)
  18163. */
  18164. get: function () {
  18165. return this._rotationQuaternion;
  18166. },
  18167. set: function (quaternion) {
  18168. this._rotationQuaternion = quaternion;
  18169. //reset the rotation vector.
  18170. if (quaternion && this.rotation.length()) {
  18171. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18172. }
  18173. },
  18174. enumerable: true,
  18175. configurable: true
  18176. });
  18177. Object.defineProperty(TransformNode.prototype, "forward", {
  18178. /**
  18179. * The forward direction of that transform in world space.
  18180. */
  18181. get: function () {
  18182. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18183. },
  18184. enumerable: true,
  18185. configurable: true
  18186. });
  18187. Object.defineProperty(TransformNode.prototype, "up", {
  18188. /**
  18189. * The up direction of that transform in world space.
  18190. */
  18191. get: function () {
  18192. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18193. },
  18194. enumerable: true,
  18195. configurable: true
  18196. });
  18197. Object.defineProperty(TransformNode.prototype, "right", {
  18198. /**
  18199. * The right direction of that transform in world space.
  18200. */
  18201. get: function () {
  18202. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18203. },
  18204. enumerable: true,
  18205. configurable: true
  18206. });
  18207. /**
  18208. * Returns the latest update of the World matrix
  18209. * Returns a Matrix.
  18210. */
  18211. TransformNode.prototype.getWorldMatrix = function () {
  18212. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18213. this.computeWorldMatrix();
  18214. }
  18215. return this._worldMatrix;
  18216. };
  18217. /**
  18218. * Returns the latest update of the World matrix determinant.
  18219. */
  18220. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18221. return this._worldMatrixDeterminant;
  18222. };
  18223. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18224. /**
  18225. * Returns directly the latest state of the mesh World matrix.
  18226. * A Matrix is returned.
  18227. */
  18228. get: function () {
  18229. return this._worldMatrix;
  18230. },
  18231. enumerable: true,
  18232. configurable: true
  18233. });
  18234. /**
  18235. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18236. * Returns the TransformNode.
  18237. */
  18238. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18239. this._poseMatrix.copyFrom(matrix);
  18240. return this;
  18241. };
  18242. /**
  18243. * Returns the mesh Pose matrix.
  18244. * Returned object : Matrix
  18245. */
  18246. TransformNode.prototype.getPoseMatrix = function () {
  18247. return this._poseMatrix;
  18248. };
  18249. TransformNode.prototype._isSynchronized = function () {
  18250. if (this._isDirty) {
  18251. return false;
  18252. }
  18253. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18254. return false;
  18255. if (this._cache.pivotMatrixUpdated) {
  18256. return false;
  18257. }
  18258. if (this.infiniteDistance) {
  18259. return false;
  18260. }
  18261. if (!this._cache.position.equals(this.position))
  18262. return false;
  18263. if (this.rotationQuaternion) {
  18264. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18265. return false;
  18266. }
  18267. if (!this._cache.rotation.equals(this.rotation))
  18268. return false;
  18269. if (!this._cache.scaling.equals(this.scaling))
  18270. return false;
  18271. return true;
  18272. };
  18273. TransformNode.prototype._initCache = function () {
  18274. _super.prototype._initCache.call(this);
  18275. this._cache.localMatrixUpdated = false;
  18276. this._cache.position = BABYLON.Vector3.Zero();
  18277. this._cache.scaling = BABYLON.Vector3.Zero();
  18278. this._cache.rotation = BABYLON.Vector3.Zero();
  18279. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18280. this._cache.billboardMode = -1;
  18281. };
  18282. TransformNode.prototype.markAsDirty = function (property) {
  18283. if (property === "rotation") {
  18284. this.rotationQuaternion = null;
  18285. }
  18286. this._currentRenderId = Number.MAX_VALUE;
  18287. this._isDirty = true;
  18288. return this;
  18289. };
  18290. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18291. /**
  18292. * Returns the current mesh absolute position.
  18293. * Retuns a Vector3.
  18294. */
  18295. get: function () {
  18296. return this._absolutePosition;
  18297. },
  18298. enumerable: true,
  18299. configurable: true
  18300. });
  18301. /**
  18302. * Sets a new matrix to apply before all other transformation
  18303. * @param matrix defines the transform matrix
  18304. * @returns the current TransformNode
  18305. */
  18306. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18307. return this.setPivotMatrix(matrix, false);
  18308. };
  18309. /**
  18310. * Sets a new pivot matrix to the current node
  18311. * @param matrix defines the new pivot matrix to use
  18312. * @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
  18313. * @returns the current TransformNode
  18314. */
  18315. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18316. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18317. this._pivotMatrix = matrix.clone();
  18318. this._cache.pivotMatrixUpdated = true;
  18319. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18320. if (this._postMultiplyPivotMatrix) {
  18321. if (!this._pivotMatrixInverse) {
  18322. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18323. }
  18324. else {
  18325. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18326. }
  18327. }
  18328. return this;
  18329. };
  18330. /**
  18331. * Returns the mesh pivot matrix.
  18332. * Default : Identity.
  18333. * A Matrix is returned.
  18334. */
  18335. TransformNode.prototype.getPivotMatrix = function () {
  18336. return this._pivotMatrix;
  18337. };
  18338. /**
  18339. * Prevents the World matrix to be computed any longer.
  18340. * Returns the TransformNode.
  18341. */
  18342. TransformNode.prototype.freezeWorldMatrix = function () {
  18343. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18344. this.computeWorldMatrix(true);
  18345. this._isWorldMatrixFrozen = true;
  18346. return this;
  18347. };
  18348. /**
  18349. * Allows back the World matrix computation.
  18350. * Returns the TransformNode.
  18351. */
  18352. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18353. this._isWorldMatrixFrozen = false;
  18354. this.computeWorldMatrix(true);
  18355. return this;
  18356. };
  18357. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18358. /**
  18359. * True if the World matrix has been frozen.
  18360. * Returns a boolean.
  18361. */
  18362. get: function () {
  18363. return this._isWorldMatrixFrozen;
  18364. },
  18365. enumerable: true,
  18366. configurable: true
  18367. });
  18368. /**
  18369. * Retuns the mesh absolute position in the World.
  18370. * Returns a Vector3.
  18371. */
  18372. TransformNode.prototype.getAbsolutePosition = function () {
  18373. this.computeWorldMatrix();
  18374. return this._absolutePosition;
  18375. };
  18376. /**
  18377. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18378. * Returns the TransformNode.
  18379. */
  18380. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18381. if (!absolutePosition) {
  18382. return this;
  18383. }
  18384. var absolutePositionX;
  18385. var absolutePositionY;
  18386. var absolutePositionZ;
  18387. if (absolutePosition.x === undefined) {
  18388. if (arguments.length < 3) {
  18389. return this;
  18390. }
  18391. absolutePositionX = arguments[0];
  18392. absolutePositionY = arguments[1];
  18393. absolutePositionZ = arguments[2];
  18394. }
  18395. else {
  18396. absolutePositionX = absolutePosition.x;
  18397. absolutePositionY = absolutePosition.y;
  18398. absolutePositionZ = absolutePosition.z;
  18399. }
  18400. if (this.parent) {
  18401. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18402. invertParentWorldMatrix.invert();
  18403. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18404. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18405. }
  18406. else {
  18407. this.position.x = absolutePositionX;
  18408. this.position.y = absolutePositionY;
  18409. this.position.z = absolutePositionZ;
  18410. }
  18411. return this;
  18412. };
  18413. /**
  18414. * Sets the mesh position in its local space.
  18415. * Returns the TransformNode.
  18416. */
  18417. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18418. this.computeWorldMatrix();
  18419. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18420. return this;
  18421. };
  18422. /**
  18423. * Returns the mesh position in the local space from the current World matrix values.
  18424. * Returns a new Vector3.
  18425. */
  18426. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18427. this.computeWorldMatrix();
  18428. var invLocalWorldMatrix = this._localWorld.clone();
  18429. invLocalWorldMatrix.invert();
  18430. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18431. };
  18432. /**
  18433. * Translates the mesh along the passed Vector3 in its local space.
  18434. * Returns the TransformNode.
  18435. */
  18436. TransformNode.prototype.locallyTranslate = function (vector3) {
  18437. this.computeWorldMatrix(true);
  18438. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18439. return this;
  18440. };
  18441. /**
  18442. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18443. * @param targetPoint the position (must be in same space as current mesh) to look at
  18444. * @param yawCor optional yaw (y-axis) correction in radians
  18445. * @param pitchCor optional pitch (x-axis) correction in radians
  18446. * @param rollCor optional roll (z-axis) correction in radians
  18447. * @param space the choosen space of the target
  18448. * @returns the TransformNode.
  18449. */
  18450. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18451. if (yawCor === void 0) { yawCor = 0; }
  18452. if (pitchCor === void 0) { pitchCor = 0; }
  18453. if (rollCor === void 0) { rollCor = 0; }
  18454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18455. var dv = TransformNode._lookAtVectorCache;
  18456. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18457. targetPoint.subtractToRef(pos, dv);
  18458. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18459. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18460. var pitch = Math.atan2(dv.y, len);
  18461. if (this.rotationQuaternion) {
  18462. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18463. }
  18464. else {
  18465. this.rotation.x = pitch + pitchCor;
  18466. this.rotation.y = yaw + yawCor;
  18467. this.rotation.z = rollCor;
  18468. }
  18469. return this;
  18470. };
  18471. /**
  18472. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18473. * This Vector3 is expressed in the World space.
  18474. */
  18475. TransformNode.prototype.getDirection = function (localAxis) {
  18476. var result = BABYLON.Vector3.Zero();
  18477. this.getDirectionToRef(localAxis, result);
  18478. return result;
  18479. };
  18480. /**
  18481. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18482. * localAxis is expressed in the mesh local space.
  18483. * result is computed in the Wordl space from the mesh World matrix.
  18484. * Returns the TransformNode.
  18485. */
  18486. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18487. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18488. return this;
  18489. };
  18490. /**
  18491. * Sets a new pivot point to the current node
  18492. * @param point defines the new pivot point to use
  18493. * @param space defines if the point is in world or local space (local by default)
  18494. * @returns the current TransformNode
  18495. */
  18496. TransformNode.prototype.setPivotPoint = function (point, space) {
  18497. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18498. if (this.getScene().getRenderId() == 0) {
  18499. this.computeWorldMatrix(true);
  18500. }
  18501. var wm = this.getWorldMatrix();
  18502. if (space == BABYLON.Space.WORLD) {
  18503. var tmat = BABYLON.Tmp.Matrix[0];
  18504. wm.invertToRef(tmat);
  18505. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18506. }
  18507. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18508. };
  18509. /**
  18510. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18511. */
  18512. TransformNode.prototype.getPivotPoint = function () {
  18513. var point = BABYLON.Vector3.Zero();
  18514. this.getPivotPointToRef(point);
  18515. return point;
  18516. };
  18517. /**
  18518. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18519. * Returns the TransformNode.
  18520. */
  18521. TransformNode.prototype.getPivotPointToRef = function (result) {
  18522. result.x = -this._pivotMatrix.m[12];
  18523. result.y = -this._pivotMatrix.m[13];
  18524. result.z = -this._pivotMatrix.m[14];
  18525. return this;
  18526. };
  18527. /**
  18528. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18529. */
  18530. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18531. var point = BABYLON.Vector3.Zero();
  18532. this.getAbsolutePivotPointToRef(point);
  18533. return point;
  18534. };
  18535. /**
  18536. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18537. * Returns the TransformNode.
  18538. */
  18539. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18540. result.x = this._pivotMatrix.m[12];
  18541. result.y = this._pivotMatrix.m[13];
  18542. result.z = this._pivotMatrix.m[14];
  18543. this.getPivotPointToRef(result);
  18544. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18545. return this;
  18546. };
  18547. /**
  18548. * Defines the passed node as the parent of the current node.
  18549. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18550. * Returns the TransformNode.
  18551. */
  18552. TransformNode.prototype.setParent = function (node) {
  18553. if (node === null) {
  18554. var rotation = BABYLON.Tmp.Quaternion[0];
  18555. var position = BABYLON.Tmp.Vector3[0];
  18556. var scale = BABYLON.Tmp.Vector3[1];
  18557. if (this.parent && this.parent.computeWorldMatrix) {
  18558. this.parent.computeWorldMatrix(true);
  18559. }
  18560. this.computeWorldMatrix(true);
  18561. this.getWorldMatrix().decompose(scale, rotation, position);
  18562. if (this.rotationQuaternion) {
  18563. this.rotationQuaternion.copyFrom(rotation);
  18564. }
  18565. else {
  18566. rotation.toEulerAnglesToRef(this.rotation);
  18567. }
  18568. this.scaling.x = scale.x;
  18569. this.scaling.y = scale.y;
  18570. this.scaling.z = scale.z;
  18571. this.position.x = position.x;
  18572. this.position.y = position.y;
  18573. this.position.z = position.z;
  18574. }
  18575. else {
  18576. var rotation = BABYLON.Tmp.Quaternion[0];
  18577. var position = BABYLON.Tmp.Vector3[0];
  18578. var scale = BABYLON.Tmp.Vector3[1];
  18579. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18580. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18581. this.computeWorldMatrix(true);
  18582. node.computeWorldMatrix(true);
  18583. node.getWorldMatrix().invertToRef(invParentMatrix);
  18584. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18585. diffMatrix.decompose(scale, rotation, position);
  18586. if (this.rotationQuaternion) {
  18587. this.rotationQuaternion.copyFrom(rotation);
  18588. }
  18589. else {
  18590. rotation.toEulerAnglesToRef(this.rotation);
  18591. }
  18592. this.position.x = position.x;
  18593. this.position.y = position.y;
  18594. this.position.z = position.z;
  18595. this.scaling.x = scale.x;
  18596. this.scaling.y = scale.y;
  18597. this.scaling.z = scale.z;
  18598. }
  18599. this.parent = node;
  18600. return this;
  18601. };
  18602. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18603. get: function () {
  18604. return this._nonUniformScaling;
  18605. },
  18606. enumerable: true,
  18607. configurable: true
  18608. });
  18609. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18610. if (this._nonUniformScaling === value) {
  18611. return false;
  18612. }
  18613. this._nonUniformScaling = true;
  18614. return true;
  18615. };
  18616. /**
  18617. * Attach the current TransformNode to another TransformNode associated with a bone
  18618. * @param bone Bone affecting the TransformNode
  18619. * @param affectedTransformNode TransformNode associated with the bone
  18620. */
  18621. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18622. this._transformToBoneReferal = affectedTransformNode;
  18623. this.parent = bone;
  18624. if (bone.getWorldMatrix().determinant() < 0) {
  18625. this.scalingDeterminant *= -1;
  18626. }
  18627. return this;
  18628. };
  18629. TransformNode.prototype.detachFromBone = function () {
  18630. if (!this.parent) {
  18631. return this;
  18632. }
  18633. if (this.parent.getWorldMatrix().determinant() < 0) {
  18634. this.scalingDeterminant *= -1;
  18635. }
  18636. this._transformToBoneReferal = null;
  18637. this.parent = null;
  18638. return this;
  18639. };
  18640. /**
  18641. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18642. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18643. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18644. * The passed axis is also normalized.
  18645. * Returns the TransformNode.
  18646. */
  18647. TransformNode.prototype.rotate = function (axis, amount, space) {
  18648. axis.normalize();
  18649. if (!this.rotationQuaternion) {
  18650. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18651. this.rotation = BABYLON.Vector3.Zero();
  18652. }
  18653. var rotationQuaternion;
  18654. if (!space || space === BABYLON.Space.LOCAL) {
  18655. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18656. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18657. }
  18658. else {
  18659. if (this.parent) {
  18660. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18661. invertParentWorldMatrix.invert();
  18662. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18663. }
  18664. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18665. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18666. }
  18667. return this;
  18668. };
  18669. /**
  18670. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18671. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18672. * The passed axis is also normalized.
  18673. * Returns the TransformNode.
  18674. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18675. */
  18676. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18677. axis.normalize();
  18678. if (!this.rotationQuaternion) {
  18679. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18680. this.rotation.copyFromFloats(0, 0, 0);
  18681. }
  18682. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18683. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18684. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18685. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18686. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18687. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18688. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18689. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18690. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18691. return this;
  18692. };
  18693. /**
  18694. * Translates the mesh along the axis vector for the passed distance in the given space.
  18695. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18696. * Returns the TransformNode.
  18697. */
  18698. TransformNode.prototype.translate = function (axis, distance, space) {
  18699. var displacementVector = axis.scale(distance);
  18700. if (!space || space === BABYLON.Space.LOCAL) {
  18701. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18702. this.setPositionWithLocalVector(tempV3);
  18703. }
  18704. else {
  18705. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18706. }
  18707. return this;
  18708. };
  18709. /**
  18710. * Adds a rotation step to the mesh current rotation.
  18711. * x, y, z are Euler angles expressed in radians.
  18712. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18713. * This means this rotation is made in the mesh local space only.
  18714. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18715. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18716. * ```javascript
  18717. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18718. * ```
  18719. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18720. * 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.
  18721. * Returns the TransformNode.
  18722. */
  18723. TransformNode.prototype.addRotation = function (x, y, z) {
  18724. var rotationQuaternion;
  18725. if (this.rotationQuaternion) {
  18726. rotationQuaternion = this.rotationQuaternion;
  18727. }
  18728. else {
  18729. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18730. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18731. }
  18732. var accumulation = BABYLON.Tmp.Quaternion[0];
  18733. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18734. rotationQuaternion.multiplyInPlace(accumulation);
  18735. if (!this.rotationQuaternion) {
  18736. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18737. }
  18738. return this;
  18739. };
  18740. /**
  18741. * Computes the mesh World matrix and returns it.
  18742. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18743. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18744. * If the parameter `force`is set to `true`, the actual computation is done.
  18745. * Returns the mesh World Matrix.
  18746. */
  18747. TransformNode.prototype.computeWorldMatrix = function (force) {
  18748. if (this._isWorldMatrixFrozen) {
  18749. return this._worldMatrix;
  18750. }
  18751. if (!force && this.isSynchronized(true)) {
  18752. this._currentRenderId = this.getScene().getRenderId();
  18753. return this._worldMatrix;
  18754. }
  18755. this._cache.position.copyFrom(this.position);
  18756. this._cache.scaling.copyFrom(this.scaling);
  18757. this._cache.pivotMatrixUpdated = false;
  18758. this._cache.billboardMode = this.billboardMode;
  18759. this._currentRenderId = this.getScene().getRenderId();
  18760. this._childRenderId = this.getScene().getRenderId();
  18761. this._isDirty = false;
  18762. // Scaling
  18763. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18764. // Rotation
  18765. //rotate, if quaternion is set and rotation was used
  18766. if (this.rotationQuaternion) {
  18767. var len = this.rotation.length();
  18768. if (len) {
  18769. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18770. this.rotation.copyFromFloats(0, 0, 0);
  18771. }
  18772. }
  18773. if (this.rotationQuaternion) {
  18774. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18775. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18776. }
  18777. else {
  18778. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18779. this._cache.rotation.copyFrom(this.rotation);
  18780. }
  18781. // Translation
  18782. var camera = this.getScene().activeCamera;
  18783. if (this.infiniteDistance && !this.parent && camera) {
  18784. var cameraWorldMatrix = camera.getWorldMatrix();
  18785. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18786. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18787. }
  18788. else {
  18789. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18790. }
  18791. // Composing transformations
  18792. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18793. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18794. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18795. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18796. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18797. // Need to decompose each rotation here
  18798. var currentPosition = BABYLON.Tmp.Vector3[3];
  18799. if (this.parent && this.parent.getWorldMatrix) {
  18800. if (this._transformToBoneReferal) {
  18801. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18802. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18803. }
  18804. else {
  18805. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18806. }
  18807. }
  18808. else {
  18809. currentPosition.copyFrom(this.position);
  18810. }
  18811. currentPosition.subtractInPlace(camera.globalPosition);
  18812. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18813. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18814. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18815. }
  18816. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18817. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  18818. }
  18819. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  18820. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  18821. }
  18822. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  18823. }
  18824. else {
  18825. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  18826. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  18827. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  18828. }
  18829. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  18830. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18831. }
  18832. // Local world
  18833. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  18834. // Parent
  18835. if (this.parent && this.parent.getWorldMatrix) {
  18836. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  18837. if (this._transformToBoneReferal) {
  18838. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18839. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  18840. }
  18841. else {
  18842. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  18843. }
  18844. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  18845. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  18846. this._worldMatrix.copyFrom(this._localWorld);
  18847. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  18848. }
  18849. else {
  18850. if (this._transformToBoneReferal) {
  18851. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18852. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  18853. }
  18854. else {
  18855. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  18856. }
  18857. }
  18858. this._markSyncedWithParent();
  18859. }
  18860. else {
  18861. this._worldMatrix.copyFrom(this._localWorld);
  18862. }
  18863. // Post multiply inverse of pivotMatrix
  18864. if (this._postMultiplyPivotMatrix) {
  18865. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  18866. }
  18867. // Normal matrix
  18868. if (this.scaling.isNonUniform) {
  18869. this._updateNonUniformScalingState(true);
  18870. }
  18871. else if (this.parent && this.parent._nonUniformScaling) {
  18872. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  18873. }
  18874. else {
  18875. this._updateNonUniformScalingState(false);
  18876. }
  18877. this._afterComputeWorldMatrix();
  18878. // Absolute position
  18879. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  18880. // Callbacks
  18881. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  18882. if (!this._poseMatrix) {
  18883. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  18884. }
  18885. // Cache the determinant
  18886. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  18887. return this._worldMatrix;
  18888. };
  18889. TransformNode.prototype._afterComputeWorldMatrix = function () {
  18890. };
  18891. /**
  18892. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  18893. * @param func: callback function to add
  18894. *
  18895. * Returns the TransformNode.
  18896. */
  18897. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  18898. this.onAfterWorldMatrixUpdateObservable.add(func);
  18899. return this;
  18900. };
  18901. /**
  18902. * Removes a registered callback function.
  18903. * Returns the TransformNode.
  18904. */
  18905. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  18906. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  18907. return this;
  18908. };
  18909. /**
  18910. * Clone the current transform node
  18911. * Returns the new transform node
  18912. * @param name Name of the new clone
  18913. * @param newParent New parent for the clone
  18914. * @param doNotCloneChildren Do not clone children hierarchy
  18915. */
  18916. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18917. var _this = this;
  18918. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  18919. result.name = name;
  18920. result.id = name;
  18921. if (newParent) {
  18922. result.parent = newParent;
  18923. }
  18924. if (!doNotCloneChildren) {
  18925. // Children
  18926. var directDescendants = this.getDescendants(true);
  18927. for (var index = 0; index < directDescendants.length; index++) {
  18928. var child = directDescendants[index];
  18929. if (child.clone) {
  18930. child.clone(name + "." + child.name, result);
  18931. }
  18932. }
  18933. }
  18934. return result;
  18935. };
  18936. TransformNode.prototype.serialize = function (currentSerializationObject) {
  18937. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  18938. serializationObject.type = this.getClassName();
  18939. // Parent
  18940. if (this.parent) {
  18941. serializationObject.parentId = this.parent.id;
  18942. }
  18943. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  18944. serializationObject.tags = BABYLON.Tags.GetTags(this);
  18945. }
  18946. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  18947. serializationObject.isEnabled = this.isEnabled();
  18948. // Parent
  18949. if (this.parent) {
  18950. serializationObject.parentId = this.parent.id;
  18951. }
  18952. return serializationObject;
  18953. };
  18954. // Statics
  18955. /**
  18956. * Returns a new TransformNode object parsed from the source provided.
  18957. * The parameter `parsedMesh` is the source.
  18958. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  18959. */
  18960. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  18961. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  18962. if (BABYLON.Tags) {
  18963. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  18964. }
  18965. if (parsedTransformNode.localMatrix) {
  18966. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  18967. }
  18968. else if (parsedTransformNode.pivotMatrix) {
  18969. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  18970. }
  18971. transformNode.setEnabled(parsedTransformNode.isEnabled);
  18972. // Parent
  18973. if (parsedTransformNode.parentId) {
  18974. transformNode._waitingParentId = parsedTransformNode.parentId;
  18975. }
  18976. return transformNode;
  18977. };
  18978. /**
  18979. * Releases resources associated with this transform node.
  18980. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18981. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18982. */
  18983. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18984. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18985. // Animations
  18986. this.getScene().stopAnimation(this);
  18987. // Remove from scene
  18988. this.getScene().removeTransformNode(this);
  18989. this.onAfterWorldMatrixUpdateObservable.clear();
  18990. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18991. };
  18992. // Statics
  18993. TransformNode.BILLBOARDMODE_NONE = 0;
  18994. TransformNode.BILLBOARDMODE_X = 1;
  18995. TransformNode.BILLBOARDMODE_Y = 2;
  18996. TransformNode.BILLBOARDMODE_Z = 4;
  18997. TransformNode.BILLBOARDMODE_ALL = 7;
  18998. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  18999. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19000. __decorate([
  19001. BABYLON.serializeAsVector3()
  19002. ], TransformNode.prototype, "_rotation", void 0);
  19003. __decorate([
  19004. BABYLON.serializeAsQuaternion()
  19005. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19006. __decorate([
  19007. BABYLON.serializeAsVector3()
  19008. ], TransformNode.prototype, "_scaling", void 0);
  19009. __decorate([
  19010. BABYLON.serialize()
  19011. ], TransformNode.prototype, "billboardMode", void 0);
  19012. __decorate([
  19013. BABYLON.serialize()
  19014. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19015. __decorate([
  19016. BABYLON.serialize()
  19017. ], TransformNode.prototype, "infiniteDistance", void 0);
  19018. __decorate([
  19019. BABYLON.serializeAsVector3()
  19020. ], TransformNode.prototype, "position", void 0);
  19021. return TransformNode;
  19022. }(BABYLON.Node));
  19023. BABYLON.TransformNode = TransformNode;
  19024. })(BABYLON || (BABYLON = {}));
  19025. //# sourceMappingURL=babylon.transformNode.js.map
  19026. var BABYLON;
  19027. (function (BABYLON) {
  19028. /**
  19029. * Class used to store all common mesh properties
  19030. */
  19031. var AbstractMesh = /** @class */ (function (_super) {
  19032. __extends(AbstractMesh, _super);
  19033. // Constructor
  19034. /**
  19035. * Creates a new AbstractMesh
  19036. * @param name defines the name of the mesh
  19037. * @param scene defines the hosting scene
  19038. */
  19039. function AbstractMesh(name, scene) {
  19040. if (scene === void 0) { scene = null; }
  19041. var _this = _super.call(this, name, scene, false) || this;
  19042. _this._facetNb = 0; // facet number
  19043. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19044. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19045. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19046. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19047. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19048. _this._subDiv = {
  19049. max: 1,
  19050. X: 1,
  19051. Y: 1,
  19052. Z: 1
  19053. };
  19054. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19055. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19056. // Events
  19057. /**
  19058. * An event triggered when this mesh collides with another one
  19059. */
  19060. _this.onCollideObservable = new BABYLON.Observable();
  19061. /**
  19062. * An event triggered when the collision's position changes
  19063. */
  19064. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19065. /**
  19066. * An event triggered when material is changed
  19067. */
  19068. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19069. // Properties
  19070. /**
  19071. * Gets or sets the orientation for POV movement & rotation
  19072. */
  19073. _this.definedFacingForward = true;
  19074. /**
  19075. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19076. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19077. * * 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.
  19078. * @see http://doc.babylonjs.com/features/occlusionquery
  19079. */
  19080. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19081. /**
  19082. * 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:
  19083. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19084. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19085. * * 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.
  19086. * @see http://doc.babylonjs.com/features/occlusionquery
  19087. */
  19088. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19089. /**
  19090. * 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.
  19091. * The default value is -1 which means don't break the query and wait till the result
  19092. * @see http://doc.babylonjs.com/features/occlusionquery
  19093. */
  19094. _this.occlusionRetryCount = -1;
  19095. _this._occlusionInternalRetryCounter = 0;
  19096. _this._isOccluded = false;
  19097. _this._isOcclusionQueryInProgress = false;
  19098. _this._visibility = 1.0;
  19099. /** Gets or sets the alpha index used to sort transparent meshes
  19100. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19101. */
  19102. _this.alphaIndex = Number.MAX_VALUE;
  19103. /**
  19104. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19105. */
  19106. _this.isVisible = true;
  19107. /**
  19108. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19109. */
  19110. _this.isPickable = true;
  19111. /**
  19112. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19113. */
  19114. _this.showBoundingBox = false;
  19115. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19116. _this.showSubMeshesBoundingBox = false;
  19117. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19118. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19119. */
  19120. _this.isBlocker = false;
  19121. /**
  19122. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19123. */
  19124. _this.enablePointerMoveEvents = false;
  19125. /**
  19126. * Specifies the rendering group id for this mesh (0 by default)
  19127. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19128. */
  19129. _this.renderingGroupId = 0;
  19130. _this._receiveShadows = false;
  19131. /**
  19132. * Gets or sets a boolean indicating if the outline must be rendered as well
  19133. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19134. */
  19135. _this.renderOutline = false;
  19136. /** Defines color to use when rendering outline */
  19137. _this.outlineColor = BABYLON.Color3.Red();
  19138. /** Define width to use when rendering outline */
  19139. _this.outlineWidth = 0.02;
  19140. /**
  19141. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19142. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19143. */
  19144. _this.renderOverlay = false;
  19145. /** Defines color to use when rendering overlay */
  19146. _this.overlayColor = BABYLON.Color3.Red();
  19147. /** Defines alpha to use when rendering overlay */
  19148. _this.overlayAlpha = 0.5;
  19149. _this._hasVertexAlpha = false;
  19150. _this._useVertexColors = true;
  19151. _this._computeBonesUsingShaders = true;
  19152. _this._numBoneInfluencers = 4;
  19153. _this._applyFog = true;
  19154. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19155. _this.useOctreeForRenderingSelection = true;
  19156. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19157. _this.useOctreeForPicking = true;
  19158. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19159. _this.useOctreeForCollisions = true;
  19160. _this._layerMask = 0x0FFFFFFF;
  19161. /**
  19162. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19163. */
  19164. _this.alwaysSelectAsActiveMesh = false;
  19165. /**
  19166. * Gets or sets the current action manager
  19167. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19168. */
  19169. _this.actionManager = null;
  19170. /**
  19171. * Gets or sets impostor used for physic simulation
  19172. * @see http://doc.babylonjs.com/features/physics_engine
  19173. */
  19174. _this.physicsImpostor = null;
  19175. // Collisions
  19176. _this._checkCollisions = false;
  19177. _this._collisionMask = -1;
  19178. _this._collisionGroup = -1;
  19179. /**
  19180. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19181. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19182. */
  19183. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19184. /**
  19185. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19186. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19187. */
  19188. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19189. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19190. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19191. // Edges
  19192. /**
  19193. * Defines edge width used when edgesRenderer is enabled
  19194. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19195. */
  19196. _this.edgesWidth = 1;
  19197. /**
  19198. * Defines edge color used when edgesRenderer is enabled
  19199. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19200. */
  19201. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19202. // Cache
  19203. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19204. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19205. /** @ignore */
  19206. _this._renderId = 0;
  19207. /** @ignore */
  19208. _this._intersectionsInProgress = new Array();
  19209. /** @ignore */
  19210. _this._unIndexed = false;
  19211. /** @ignore */
  19212. _this._lightSources = new Array();
  19213. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19214. if (collidedMesh === void 0) { collidedMesh = null; }
  19215. //TODO move this to the collision coordinator!
  19216. if (_this.getScene().workerCollisions)
  19217. newPosition.multiplyInPlace(_this._collider._radius);
  19218. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19219. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19220. _this.position.addInPlace(_this._diffPositionForCollisions);
  19221. }
  19222. if (collidedMesh) {
  19223. _this.onCollideObservable.notifyObservers(collidedMesh);
  19224. }
  19225. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19226. };
  19227. _this.getScene().addMesh(_this);
  19228. _this._resyncLightSources();
  19229. return _this;
  19230. }
  19231. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19232. /**
  19233. * No billboard
  19234. */
  19235. get: function () {
  19236. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19237. },
  19238. enumerable: true,
  19239. configurable: true
  19240. });
  19241. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19242. /** Billboard on X axis */
  19243. get: function () {
  19244. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19250. /** Billboard on Y axis */
  19251. get: function () {
  19252. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19253. },
  19254. enumerable: true,
  19255. configurable: true
  19256. });
  19257. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19258. /** Billboard on Z axis */
  19259. get: function () {
  19260. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19261. },
  19262. enumerable: true,
  19263. configurable: true
  19264. });
  19265. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19266. /** Billboard on all axes */
  19267. get: function () {
  19268. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19269. },
  19270. enumerable: true,
  19271. configurable: true
  19272. });
  19273. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19274. /**
  19275. * Gets the number of facets in the mesh
  19276. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19277. */
  19278. get: function () {
  19279. return this._facetNb;
  19280. },
  19281. enumerable: true,
  19282. configurable: true
  19283. });
  19284. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19285. /**
  19286. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19287. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19288. */
  19289. get: function () {
  19290. return this._partitioningSubdivisions;
  19291. },
  19292. set: function (nb) {
  19293. this._partitioningSubdivisions = nb;
  19294. },
  19295. enumerable: true,
  19296. configurable: true
  19297. });
  19298. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19299. /**
  19300. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19301. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19302. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19303. */
  19304. get: function () {
  19305. return this._partitioningBBoxRatio;
  19306. },
  19307. set: function (ratio) {
  19308. this._partitioningBBoxRatio = ratio;
  19309. },
  19310. enumerable: true,
  19311. configurable: true
  19312. });
  19313. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19314. /**
  19315. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19316. * Works only for updatable meshes.
  19317. * Doesn't work with multi-materials
  19318. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19319. */
  19320. get: function () {
  19321. return this._facetDepthSort;
  19322. },
  19323. set: function (sort) {
  19324. this._facetDepthSort = sort;
  19325. },
  19326. enumerable: true,
  19327. configurable: true
  19328. });
  19329. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19330. /**
  19331. * The location (Vector3) where the facet depth sort must be computed from.
  19332. * By default, the active camera position.
  19333. * Used only when facet depth sort is enabled
  19334. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19335. */
  19336. get: function () {
  19337. return this._facetDepthSortFrom;
  19338. },
  19339. set: function (location) {
  19340. this._facetDepthSortFrom = location;
  19341. },
  19342. enumerable: true,
  19343. configurable: true
  19344. });
  19345. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19346. /**
  19347. * gets a boolean indicating if facetData is enabled
  19348. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19349. */
  19350. get: function () {
  19351. return this._facetDataEnabled;
  19352. },
  19353. enumerable: true,
  19354. configurable: true
  19355. });
  19356. /** @ignore */
  19357. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19358. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19359. return false;
  19360. }
  19361. this._markSubMeshesAsMiscDirty();
  19362. return true;
  19363. };
  19364. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19365. /** Set a function to call when this mesh collides with another one */
  19366. set: function (callback) {
  19367. if (this._onCollideObserver) {
  19368. this.onCollideObservable.remove(this._onCollideObserver);
  19369. }
  19370. this._onCollideObserver = this.onCollideObservable.add(callback);
  19371. },
  19372. enumerable: true,
  19373. configurable: true
  19374. });
  19375. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19376. /** Set a function to call when the collision's position changes */
  19377. set: function (callback) {
  19378. if (this._onCollisionPositionChangeObserver) {
  19379. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19380. }
  19381. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19387. /**
  19388. * 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
  19389. * @see http://doc.babylonjs.com/features/occlusionquery
  19390. */
  19391. get: function () {
  19392. return this._isOccluded;
  19393. },
  19394. set: function (value) {
  19395. this._isOccluded = value;
  19396. },
  19397. enumerable: true,
  19398. configurable: true
  19399. });
  19400. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19401. /**
  19402. * Flag to check the progress status of the query
  19403. * @see http://doc.babylonjs.com/features/occlusionquery
  19404. */
  19405. get: function () {
  19406. return this._isOcclusionQueryInProgress;
  19407. },
  19408. enumerable: true,
  19409. configurable: true
  19410. });
  19411. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19412. /**
  19413. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19414. */
  19415. get: function () {
  19416. return this._visibility;
  19417. },
  19418. /**
  19419. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19420. */
  19421. set: function (value) {
  19422. if (this._visibility === value) {
  19423. return;
  19424. }
  19425. this._visibility = value;
  19426. this._markSubMeshesAsMiscDirty();
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(AbstractMesh.prototype, "material", {
  19432. /** Gets or sets current material */
  19433. get: function () {
  19434. return this._material;
  19435. },
  19436. set: function (value) {
  19437. if (this._material === value) {
  19438. return;
  19439. }
  19440. this._material = value;
  19441. if (this.onMaterialChangedObservable.hasObservers) {
  19442. this.onMaterialChangedObservable.notifyObservers(this);
  19443. }
  19444. if (!this.subMeshes) {
  19445. return;
  19446. }
  19447. this._unBindEffect();
  19448. },
  19449. enumerable: true,
  19450. configurable: true
  19451. });
  19452. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19453. /**
  19454. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19455. * @see http://doc.babylonjs.com/babylon101/shadows
  19456. */
  19457. get: function () {
  19458. return this._receiveShadows;
  19459. },
  19460. set: function (value) {
  19461. if (this._receiveShadows === value) {
  19462. return;
  19463. }
  19464. this._receiveShadows = value;
  19465. this._markSubMeshesAsLightDirty();
  19466. },
  19467. enumerable: true,
  19468. configurable: true
  19469. });
  19470. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19471. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19472. get: function () {
  19473. return this._hasVertexAlpha;
  19474. },
  19475. set: function (value) {
  19476. if (this._hasVertexAlpha === value) {
  19477. return;
  19478. }
  19479. this._hasVertexAlpha = value;
  19480. this._markSubMeshesAsAttributesDirty();
  19481. this._markSubMeshesAsMiscDirty();
  19482. },
  19483. enumerable: true,
  19484. configurable: true
  19485. });
  19486. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19487. /** 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) */
  19488. get: function () {
  19489. return this._useVertexColors;
  19490. },
  19491. set: function (value) {
  19492. if (this._useVertexColors === value) {
  19493. return;
  19494. }
  19495. this._useVertexColors = value;
  19496. this._markSubMeshesAsAttributesDirty();
  19497. },
  19498. enumerable: true,
  19499. configurable: true
  19500. });
  19501. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19502. /**
  19503. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19504. */
  19505. get: function () {
  19506. return this._computeBonesUsingShaders;
  19507. },
  19508. set: function (value) {
  19509. if (this._computeBonesUsingShaders === value) {
  19510. return;
  19511. }
  19512. this._computeBonesUsingShaders = value;
  19513. this._markSubMeshesAsAttributesDirty();
  19514. },
  19515. enumerable: true,
  19516. configurable: true
  19517. });
  19518. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19519. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19520. get: function () {
  19521. return this._numBoneInfluencers;
  19522. },
  19523. set: function (value) {
  19524. if (this._numBoneInfluencers === value) {
  19525. return;
  19526. }
  19527. this._numBoneInfluencers = value;
  19528. this._markSubMeshesAsAttributesDirty();
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19534. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19535. get: function () {
  19536. return this._applyFog;
  19537. },
  19538. set: function (value) {
  19539. if (this._applyFog === value) {
  19540. return;
  19541. }
  19542. this._applyFog = value;
  19543. this._markSubMeshesAsMiscDirty();
  19544. },
  19545. enumerable: true,
  19546. configurable: true
  19547. });
  19548. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19549. /**
  19550. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19551. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19552. */
  19553. get: function () {
  19554. return this._layerMask;
  19555. },
  19556. set: function (value) {
  19557. if (value === this._layerMask) {
  19558. return;
  19559. }
  19560. this._layerMask = value;
  19561. this._resyncLightSources();
  19562. },
  19563. enumerable: true,
  19564. configurable: true
  19565. });
  19566. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19567. /**
  19568. * Gets or sets a collision mask used to mask collisions (default is -1).
  19569. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19570. */
  19571. get: function () {
  19572. return this._collisionMask;
  19573. },
  19574. set: function (mask) {
  19575. this._collisionMask = !isNaN(mask) ? mask : -1;
  19576. },
  19577. enumerable: true,
  19578. configurable: true
  19579. });
  19580. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19581. /**
  19582. * Gets or sets the current collision group mask (-1 by default).
  19583. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19584. */
  19585. get: function () {
  19586. return this._collisionGroup;
  19587. },
  19588. set: function (mask) {
  19589. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19590. },
  19591. enumerable: true,
  19592. configurable: true
  19593. });
  19594. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19595. /** @ignore */
  19596. get: function () {
  19597. return null;
  19598. },
  19599. enumerable: true,
  19600. configurable: true
  19601. });
  19602. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19603. get: function () {
  19604. return this._skeleton;
  19605. },
  19606. /**
  19607. * Gets or sets a skeleton to apply skining transformations
  19608. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19609. */
  19610. set: function (value) {
  19611. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19612. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19613. }
  19614. if (value && value.needInitialSkinMatrix) {
  19615. value._registerMeshWithPoseMatrix(this);
  19616. }
  19617. this._skeleton = value;
  19618. if (!this._skeleton) {
  19619. this._bonesTransformMatrices = null;
  19620. }
  19621. this._markSubMeshesAsAttributesDirty();
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. /**
  19627. * Returns the string "AbstractMesh"
  19628. * @returns "AbstractMesh"
  19629. */
  19630. AbstractMesh.prototype.getClassName = function () {
  19631. return "AbstractMesh";
  19632. };
  19633. /**
  19634. * Gets a string representation of the current mesh
  19635. * @param fullDetails defines a boolean indicating if full details must be included
  19636. * @returns a string representation of the current mesh
  19637. */
  19638. AbstractMesh.prototype.toString = function (fullDetails) {
  19639. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19640. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19641. if (this._skeleton) {
  19642. ret += ", skeleton: " + this._skeleton.name;
  19643. }
  19644. if (fullDetails) {
  19645. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19646. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19647. }
  19648. return ret;
  19649. };
  19650. /** @ignore */
  19651. AbstractMesh.prototype._rebuild = function () {
  19652. if (this._occlusionQuery) {
  19653. this._occlusionQuery = null;
  19654. }
  19655. if (this._edgesRenderer) {
  19656. this._edgesRenderer._rebuild();
  19657. }
  19658. if (!this.subMeshes) {
  19659. return;
  19660. }
  19661. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19662. var subMesh = _a[_i];
  19663. subMesh._rebuild();
  19664. }
  19665. };
  19666. /** @ignore */
  19667. AbstractMesh.prototype._resyncLightSources = function () {
  19668. this._lightSources.length = 0;
  19669. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19670. var light = _a[_i];
  19671. if (!light.isEnabled()) {
  19672. continue;
  19673. }
  19674. if (light.canAffectMesh(this)) {
  19675. this._lightSources.push(light);
  19676. }
  19677. }
  19678. this._markSubMeshesAsLightDirty();
  19679. };
  19680. /** @ignore */
  19681. AbstractMesh.prototype._resyncLighSource = function (light) {
  19682. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19683. var index = this._lightSources.indexOf(light);
  19684. if (index === -1) {
  19685. if (!isIn) {
  19686. return;
  19687. }
  19688. this._lightSources.push(light);
  19689. }
  19690. else {
  19691. if (isIn) {
  19692. return;
  19693. }
  19694. this._lightSources.splice(index, 1);
  19695. }
  19696. this._markSubMeshesAsLightDirty();
  19697. };
  19698. /** @ignore */
  19699. AbstractMesh.prototype._unBindEffect = function () {
  19700. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19701. var subMesh = _a[_i];
  19702. subMesh.setEffect(null);
  19703. }
  19704. };
  19705. /** @ignore */
  19706. AbstractMesh.prototype._removeLightSource = function (light) {
  19707. var index = this._lightSources.indexOf(light);
  19708. if (index === -1) {
  19709. return;
  19710. }
  19711. this._lightSources.splice(index, 1);
  19712. this._markSubMeshesAsLightDirty();
  19713. };
  19714. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19715. if (!this.subMeshes) {
  19716. return;
  19717. }
  19718. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19719. var subMesh = _a[_i];
  19720. if (subMesh._materialDefines) {
  19721. func(subMesh._materialDefines);
  19722. }
  19723. }
  19724. };
  19725. /** @ignore */
  19726. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19727. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19728. };
  19729. /** @ignore */
  19730. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19731. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19732. };
  19733. /** @ignore */
  19734. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19735. if (!this.subMeshes) {
  19736. return;
  19737. }
  19738. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19739. var subMesh = _a[_i];
  19740. var material = subMesh.getMaterial();
  19741. if (material) {
  19742. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19743. }
  19744. }
  19745. };
  19746. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19747. /**
  19748. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19749. */
  19750. get: function () {
  19751. return this._scaling;
  19752. },
  19753. set: function (newScaling) {
  19754. this._scaling = newScaling;
  19755. if (this.physicsImpostor) {
  19756. this.physicsImpostor.forceUpdate();
  19757. }
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. // Methods
  19763. /**
  19764. * Disables the mesh edge rendering mode
  19765. * @returns the currentAbstractMesh
  19766. */
  19767. AbstractMesh.prototype.disableEdgesRendering = function () {
  19768. if (this._edgesRenderer) {
  19769. this._edgesRenderer.dispose();
  19770. this._edgesRenderer = null;
  19771. }
  19772. return this;
  19773. };
  19774. /**
  19775. * Enables the edge rendering mode on the mesh.
  19776. * This mode makes the mesh edges visible
  19777. * @param epsilon defines the maximal distance between two angles to detect a face
  19778. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19779. * @returns the currentAbstractMesh
  19780. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19781. */
  19782. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19783. if (epsilon === void 0) { epsilon = 0.95; }
  19784. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19785. this.disableEdgesRendering();
  19786. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19787. return this;
  19788. };
  19789. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19790. /**
  19791. * Returns true if the mesh is blocked. Implemented by child classes
  19792. */
  19793. get: function () {
  19794. return false;
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. /**
  19800. * Returns the mesh itself by default. Implemented by child classes
  19801. * @param camera defines the camera to use to pick the right LOD level
  19802. * @returns the currentAbstractMesh
  19803. */
  19804. AbstractMesh.prototype.getLOD = function (camera) {
  19805. return this;
  19806. };
  19807. /**
  19808. * Returns 0 by default. Implemented by child classes
  19809. * @returns an integer
  19810. */
  19811. AbstractMesh.prototype.getTotalVertices = function () {
  19812. return 0;
  19813. };
  19814. /**
  19815. * Returns null by default. Implemented by child classes
  19816. * @returns null
  19817. */
  19818. AbstractMesh.prototype.getIndices = function () {
  19819. return null;
  19820. };
  19821. /**
  19822. * Returns the array of the requested vertex data kind. Implemented by child classes
  19823. * @param kind defines the vertex data kind to use
  19824. * @returns null
  19825. */
  19826. AbstractMesh.prototype.getVerticesData = function (kind) {
  19827. return null;
  19828. };
  19829. /**
  19830. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19831. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19832. * Note that a new underlying VertexBuffer object is created each call.
  19833. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19834. * @param kind defines vertex data kind:
  19835. * * BABYLON.VertexBuffer.PositionKind
  19836. * * BABYLON.VertexBuffer.UVKind
  19837. * * BABYLON.VertexBuffer.UV2Kind
  19838. * * BABYLON.VertexBuffer.UV3Kind
  19839. * * BABYLON.VertexBuffer.UV4Kind
  19840. * * BABYLON.VertexBuffer.UV5Kind
  19841. * * BABYLON.VertexBuffer.UV6Kind
  19842. * * BABYLON.VertexBuffer.ColorKind
  19843. * * BABYLON.VertexBuffer.MatricesIndicesKind
  19844. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19845. * * BABYLON.VertexBuffer.MatricesWeightsKind
  19846. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19847. * @param data defines the data source
  19848. * @param updatable defines if the data must be flagged as updatable (or static)
  19849. * @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
  19850. * @returns the current mesh
  19851. */
  19852. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19853. return this;
  19854. };
  19855. /**
  19856. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19857. * If the mesh has no geometry, it is simply returned as it is.
  19858. * @param kind defines vertex data kind:
  19859. * * BABYLON.VertexBuffer.PositionKind
  19860. * * BABYLON.VertexBuffer.UVKind
  19861. * * BABYLON.VertexBuffer.UV2Kind
  19862. * * BABYLON.VertexBuffer.UV3Kind
  19863. * * BABYLON.VertexBuffer.UV4Kind
  19864. * * BABYLON.VertexBuffer.UV5Kind
  19865. * * BABYLON.VertexBuffer.UV6Kind
  19866. * * BABYLON.VertexBuffer.ColorKind
  19867. * * BABYLON.VertexBuffer.MatricesIndicesKind
  19868. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19869. * * BABYLON.VertexBuffer.MatricesWeightsKind
  19870. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19871. * @param data defines the data source
  19872. * @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
  19873. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  19874. * @returns the current mesh
  19875. */
  19876. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19877. return this;
  19878. };
  19879. /**
  19880. * Sets the mesh indices,
  19881. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19882. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  19883. * @param totalVertices Defines the total number of vertices
  19884. * @returns the current mesh
  19885. */
  19886. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  19887. return this;
  19888. };
  19889. /**
  19890. * Gets a boolean indicating if specific vertex data is present
  19891. * @param kind defines the vertex data kind to use
  19892. * @returns true is data kind is present
  19893. */
  19894. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  19895. return false;
  19896. };
  19897. /**
  19898. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  19899. * @returns a BoundingInfo
  19900. */
  19901. AbstractMesh.prototype.getBoundingInfo = function () {
  19902. if (this._masterMesh) {
  19903. return this._masterMesh.getBoundingInfo();
  19904. }
  19905. if (!this._boundingInfo) {
  19906. // this._boundingInfo is being created here
  19907. this._updateBoundingInfo();
  19908. }
  19909. // cannot be null.
  19910. return this._boundingInfo;
  19911. };
  19912. /**
  19913. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  19914. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  19915. * @returns the current mesh
  19916. */
  19917. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  19918. if (includeDescendants === void 0) { includeDescendants = true; }
  19919. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  19920. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  19921. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  19922. if (maxDimension === 0) {
  19923. return this;
  19924. }
  19925. var scale = 1 / maxDimension;
  19926. this.scaling.scaleInPlace(scale);
  19927. return this;
  19928. };
  19929. /**
  19930. * Overwrite the current bounding info
  19931. * @param boundingInfo defines the new bounding info
  19932. * @returns the current mesh
  19933. */
  19934. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  19935. this._boundingInfo = boundingInfo;
  19936. return this;
  19937. };
  19938. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  19939. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  19940. get: function () {
  19941. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  19942. },
  19943. enumerable: true,
  19944. configurable: true
  19945. });
  19946. /** @ignore */
  19947. AbstractMesh.prototype._preActivate = function () {
  19948. };
  19949. /** @ignore */
  19950. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19951. };
  19952. /** @ignore */
  19953. AbstractMesh.prototype._activate = function (renderId) {
  19954. this._renderId = renderId;
  19955. };
  19956. /**
  19957. * Gets the current world matrix
  19958. * @returns a Matrix
  19959. */
  19960. AbstractMesh.prototype.getWorldMatrix = function () {
  19961. if (this._masterMesh) {
  19962. return this._masterMesh.getWorldMatrix();
  19963. }
  19964. return _super.prototype.getWorldMatrix.call(this);
  19965. };
  19966. /** @ignore */
  19967. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  19968. if (this._masterMesh) {
  19969. return this._masterMesh._getWorldMatrixDeterminant();
  19970. }
  19971. return _super.prototype._getWorldMatrixDeterminant.call(this);
  19972. };
  19973. // ================================== Point of View Movement =================================
  19974. /**
  19975. * Perform relative position change from the point of view of behind the front of the mesh.
  19976. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19977. * Supports definition of mesh facing forward or backward
  19978. * @param amountRight defines the distance on the right axis
  19979. * @param amountUp defines the distance on the up axis
  19980. * @param amountForward defines the distance on the forward axis
  19981. * @returns the current mesh
  19982. */
  19983. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  19984. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  19985. return this;
  19986. };
  19987. /**
  19988. * Calculate relative position change from the point of view of behind the front of the mesh.
  19989. * This is performed taking into account the meshes current rotation, so you do not have to care.
  19990. * Supports definition of mesh facing forward or backward
  19991. * @param amountRight defines the distance on the right axis
  19992. * @param amountUp defines the distance on the up axis
  19993. * @param amountForward defines the distance on the forward axis
  19994. * @returns the new displacement vector
  19995. */
  19996. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  19997. var rotMatrix = new BABYLON.Matrix();
  19998. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19999. rotQuaternion.toRotationMatrix(rotMatrix);
  20000. var translationDelta = BABYLON.Vector3.Zero();
  20001. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20002. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20003. return translationDelta;
  20004. };
  20005. // ================================== Point of View Rotation =================================
  20006. /**
  20007. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20008. * Supports definition of mesh facing forward or backward
  20009. * @param flipBack defines the flip
  20010. * @param twirlClockwise defines the twirl
  20011. * @param tiltRight defines the tilt
  20012. * @returns the current mesh
  20013. */
  20014. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20015. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20016. return this;
  20017. };
  20018. /**
  20019. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20020. * Supports definition of mesh facing forward or backward.
  20021. * @param flipBack defines the flip
  20022. * @param twirlClockwise defines the twirl
  20023. * @param tiltRight defines the tilt
  20024. * @returns the new rotation vector
  20025. */
  20026. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20027. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20028. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20029. };
  20030. /**
  20031. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20032. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20033. * @returns the new bounding vectors
  20034. */
  20035. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20036. if (includeDescendants === void 0) { includeDescendants = true; }
  20037. this.computeWorldMatrix(true);
  20038. var min;
  20039. var max;
  20040. var boundingInfo = this.getBoundingInfo();
  20041. if (!this.subMeshes) {
  20042. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20043. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20044. }
  20045. else {
  20046. min = boundingInfo.boundingBox.minimumWorld;
  20047. max = boundingInfo.boundingBox.maximumWorld;
  20048. }
  20049. if (includeDescendants) {
  20050. var descendants = this.getDescendants(false);
  20051. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20052. var descendant = descendants_1[_i];
  20053. var childMesh = descendant;
  20054. childMesh.computeWorldMatrix(true);
  20055. //make sure we have the needed params to get mix and max
  20056. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20057. continue;
  20058. }
  20059. var childBoundingInfo = childMesh.getBoundingInfo();
  20060. var boundingBox = childBoundingInfo.boundingBox;
  20061. var minBox = boundingBox.minimumWorld;
  20062. var maxBox = boundingBox.maximumWorld;
  20063. BABYLON.Tools.CheckExtends(minBox, min, max);
  20064. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20065. }
  20066. }
  20067. return {
  20068. min: min,
  20069. max: max
  20070. };
  20071. };
  20072. /** @ignore */
  20073. AbstractMesh.prototype._updateBoundingInfo = function () {
  20074. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20075. this._boundingInfo.update(this.worldMatrixFromCache);
  20076. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20077. return this;
  20078. };
  20079. /** @ignore */
  20080. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20081. if (!this.subMeshes) {
  20082. return this;
  20083. }
  20084. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20085. var subMesh = this.subMeshes[subIndex];
  20086. if (!subMesh.IsGlobal) {
  20087. subMesh.updateBoundingInfo(matrix);
  20088. }
  20089. }
  20090. return this;
  20091. };
  20092. /** @ignore */
  20093. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20094. // Bounding info
  20095. this._updateBoundingInfo();
  20096. };
  20097. /**
  20098. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20099. * A mesh is in the frustum if its bounding box intersects the frustum
  20100. * @param frustumPlanes defines the frustum to test
  20101. * @returns true if the mesh is in the frustum planes
  20102. */
  20103. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20104. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20105. };
  20106. /**
  20107. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20108. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20109. * @param frustumPlanes defines the frustum to test
  20110. * @returns true if the mesh is completely in the frustum planes
  20111. */
  20112. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20113. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20114. ;
  20115. };
  20116. /**
  20117. * True if the mesh intersects another mesh or a SolidParticle object
  20118. * @param mesh defines a target mesh or SolidParticle to test
  20119. * @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)
  20120. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20121. * @returns true if there is an intersection
  20122. */
  20123. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20124. if (precise === void 0) { precise = false; }
  20125. if (!this._boundingInfo || !mesh._boundingInfo) {
  20126. return false;
  20127. }
  20128. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20129. return true;
  20130. }
  20131. if (includeDescendants) {
  20132. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20133. var child = _a[_i];
  20134. if (child.intersectsMesh(mesh, precise, true)) {
  20135. return true;
  20136. }
  20137. }
  20138. }
  20139. return false;
  20140. };
  20141. /**
  20142. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20143. * @param point defines the point to test
  20144. * @returns true if there is an intersection
  20145. */
  20146. AbstractMesh.prototype.intersectsPoint = function (point) {
  20147. if (!this._boundingInfo) {
  20148. return false;
  20149. }
  20150. return this._boundingInfo.intersectsPoint(point);
  20151. };
  20152. /**
  20153. * Gets the current physics impostor
  20154. * @see http://doc.babylonjs.com/features/physics_engine
  20155. * @returns a physics impostor or null
  20156. */
  20157. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20158. return this.physicsImpostor;
  20159. };
  20160. /**
  20161. * Gets the position of the current mesh in camera space
  20162. * @param camera defines the camera to use
  20163. * @returns a position
  20164. */
  20165. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20166. if (camera === void 0) { camera = null; }
  20167. if (!camera) {
  20168. camera = this.getScene().activeCamera;
  20169. }
  20170. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20171. };
  20172. /**
  20173. * Returns the distance from the mesh to the active camera
  20174. * @param camera defines the camera to use
  20175. * @returns the distance
  20176. */
  20177. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20178. if (camera === void 0) { camera = null; }
  20179. if (!camera) {
  20180. camera = this.getScene().activeCamera;
  20181. }
  20182. return this.absolutePosition.subtract(camera.position).length();
  20183. };
  20184. /**
  20185. * Apply a physic impulse to the mesh
  20186. * @param force defines the force to apply
  20187. * @param contactPoint defines where to apply the force
  20188. * @returns the current mesh
  20189. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20190. */
  20191. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20192. if (!this.physicsImpostor) {
  20193. return this;
  20194. }
  20195. this.physicsImpostor.applyImpulse(force, contactPoint);
  20196. return this;
  20197. };
  20198. /**
  20199. * Creates a physic joint between two meshes
  20200. * @param otherMesh defines the other mesh to use
  20201. * @param pivot1 defines the pivot to use on this mesh
  20202. * @param pivot2 defines the pivot to use on the other mesh
  20203. * @param options defines additional options (can be plugin dependent)
  20204. * @returns the current mesh
  20205. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20206. */
  20207. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20208. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20209. return this;
  20210. }
  20211. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20212. mainPivot: pivot1,
  20213. connectedPivot: pivot2,
  20214. nativeParams: options
  20215. });
  20216. return this;
  20217. };
  20218. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20219. // Collisions
  20220. /**
  20221. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20222. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20223. */
  20224. get: function () {
  20225. return this._checkCollisions;
  20226. },
  20227. set: function (collisionEnabled) {
  20228. this._checkCollisions = collisionEnabled;
  20229. if (this.getScene().workerCollisions) {
  20230. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20231. }
  20232. },
  20233. enumerable: true,
  20234. configurable: true
  20235. });
  20236. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20237. /**
  20238. * Gets Collider object used to compute collisions (not physics)
  20239. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20240. */
  20241. get: function () {
  20242. return this._collider;
  20243. },
  20244. enumerable: true,
  20245. configurable: true
  20246. });
  20247. /**
  20248. * Move the mesh using collision engine
  20249. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20250. * @param displacement defines the requested displacement vector
  20251. * @returns the current mesh
  20252. */
  20253. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20254. var globalPosition = this.getAbsolutePosition();
  20255. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20256. if (!this._collider) {
  20257. this._collider = new BABYLON.Collider();
  20258. }
  20259. this._collider._radius = this.ellipsoid;
  20260. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20261. return this;
  20262. };
  20263. // Submeshes octree
  20264. /**
  20265. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20266. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20267. * @param maxCapacity defines the maximum size of each block (64 by default)
  20268. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20269. * @returns the new octree
  20270. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20271. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20272. */
  20273. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20274. if (maxCapacity === void 0) { maxCapacity = 64; }
  20275. if (maxDepth === void 0) { maxDepth = 2; }
  20276. if (!this._submeshesOctree) {
  20277. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20278. }
  20279. this.computeWorldMatrix(true);
  20280. var boundingInfo = this.getBoundingInfo();
  20281. // Update octree
  20282. var bbox = boundingInfo.boundingBox;
  20283. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20284. return this._submeshesOctree;
  20285. };
  20286. // Collisions
  20287. /** @ignore */
  20288. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20289. this._generatePointsArray();
  20290. if (!this._positions) {
  20291. return this;
  20292. }
  20293. // Transformation
  20294. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20295. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20296. subMesh._lastColliderWorldVertices = [];
  20297. subMesh._trianglePlanes = [];
  20298. var start = subMesh.verticesStart;
  20299. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20300. for (var i = start; i < end; i++) {
  20301. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20302. }
  20303. }
  20304. // Collide
  20305. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20306. if (collider.collisionFound) {
  20307. collider.collidedMesh = this;
  20308. }
  20309. return this;
  20310. };
  20311. /** @ignore */
  20312. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20313. var subMeshes;
  20314. var len;
  20315. // Octrees
  20316. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20317. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20318. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20319. len = intersections.length;
  20320. subMeshes = intersections.data;
  20321. }
  20322. else {
  20323. subMeshes = this.subMeshes;
  20324. len = subMeshes.length;
  20325. }
  20326. for (var index = 0; index < len; index++) {
  20327. var subMesh = subMeshes[index];
  20328. // Bounding test
  20329. if (len > 1 && !subMesh._checkCollision(collider))
  20330. continue;
  20331. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20332. }
  20333. return this;
  20334. };
  20335. /** @ignore */
  20336. AbstractMesh.prototype._checkCollision = function (collider) {
  20337. // Bounding box test
  20338. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20339. return this;
  20340. // Transformation matrix
  20341. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20342. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20343. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20344. return this;
  20345. };
  20346. // Picking
  20347. /** @ignore */
  20348. AbstractMesh.prototype._generatePointsArray = function () {
  20349. return false;
  20350. };
  20351. /**
  20352. * Checks if the passed Ray intersects with the mesh
  20353. * @param ray defines the ray to use
  20354. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20355. * @returns the picking info
  20356. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20357. */
  20358. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20359. var pickingInfo = new BABYLON.PickingInfo();
  20360. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20361. return pickingInfo;
  20362. }
  20363. if (!this._generatePointsArray()) {
  20364. return pickingInfo;
  20365. }
  20366. var intersectInfo = null;
  20367. // Octrees
  20368. var subMeshes;
  20369. var len;
  20370. if (this._submeshesOctree && this.useOctreeForPicking) {
  20371. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20372. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20373. len = intersections.length;
  20374. subMeshes = intersections.data;
  20375. }
  20376. else {
  20377. subMeshes = this.subMeshes;
  20378. len = subMeshes.length;
  20379. }
  20380. for (var index = 0; index < len; index++) {
  20381. var subMesh = subMeshes[index];
  20382. // Bounding test
  20383. if (len > 1 && !subMesh.canIntersects(ray))
  20384. continue;
  20385. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20386. if (currentIntersectInfo) {
  20387. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20388. intersectInfo = currentIntersectInfo;
  20389. intersectInfo.subMeshId = index;
  20390. if (fastCheck) {
  20391. break;
  20392. }
  20393. }
  20394. }
  20395. }
  20396. if (intersectInfo) {
  20397. // Get picked point
  20398. var world = this.getWorldMatrix();
  20399. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20400. var direction = ray.direction.clone();
  20401. direction = direction.scale(intersectInfo.distance);
  20402. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20403. var pickedPoint = worldOrigin.add(worldDirection);
  20404. // Return result
  20405. pickingInfo.hit = true;
  20406. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20407. pickingInfo.pickedPoint = pickedPoint;
  20408. pickingInfo.pickedMesh = this;
  20409. pickingInfo.bu = intersectInfo.bu || 0;
  20410. pickingInfo.bv = intersectInfo.bv || 0;
  20411. pickingInfo.faceId = intersectInfo.faceId;
  20412. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20413. return pickingInfo;
  20414. }
  20415. return pickingInfo;
  20416. };
  20417. /**
  20418. * Clones the current mesh
  20419. * @param name defines the mesh name
  20420. * @param newParent defines the new mesh parent
  20421. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20422. * @returns the new mesh
  20423. */
  20424. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20425. return null;
  20426. };
  20427. /**
  20428. * Disposes all the submeshes of the current meshnp
  20429. * @returns the current mesh
  20430. */
  20431. AbstractMesh.prototype.releaseSubMeshes = function () {
  20432. if (this.subMeshes) {
  20433. while (this.subMeshes.length) {
  20434. this.subMeshes[0].dispose();
  20435. }
  20436. }
  20437. else {
  20438. this.subMeshes = new Array();
  20439. }
  20440. return this;
  20441. };
  20442. /**
  20443. * Releases resources associated with this abstract mesh.
  20444. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20445. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20446. */
  20447. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20448. var _this = this;
  20449. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20450. var index;
  20451. // Smart Array Retainers.
  20452. this.getScene().freeActiveMeshes();
  20453. this.getScene().freeRenderingGroups();
  20454. // Action manager
  20455. if (this.actionManager !== undefined && this.actionManager !== null) {
  20456. this.actionManager.dispose();
  20457. this.actionManager = null;
  20458. }
  20459. // Skeleton
  20460. this._skeleton = null;
  20461. // Physics
  20462. if (this.physicsImpostor) {
  20463. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20464. }
  20465. // Intersections in progress
  20466. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20467. var other = this._intersectionsInProgress[index];
  20468. var pos = other._intersectionsInProgress.indexOf(this);
  20469. other._intersectionsInProgress.splice(pos, 1);
  20470. }
  20471. this._intersectionsInProgress = [];
  20472. // Lights
  20473. var lights = this.getScene().lights;
  20474. lights.forEach(function (light) {
  20475. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20476. if (meshIndex !== -1) {
  20477. light.includedOnlyMeshes.splice(meshIndex, 1);
  20478. }
  20479. meshIndex = light.excludedMeshes.indexOf(_this);
  20480. if (meshIndex !== -1) {
  20481. light.excludedMeshes.splice(meshIndex, 1);
  20482. }
  20483. // Shadow generators
  20484. var generator = light.getShadowGenerator();
  20485. if (generator) {
  20486. var shadowMap = generator.getShadowMap();
  20487. if (shadowMap && shadowMap.renderList) {
  20488. meshIndex = shadowMap.renderList.indexOf(_this);
  20489. if (meshIndex !== -1) {
  20490. shadowMap.renderList.splice(meshIndex, 1);
  20491. }
  20492. }
  20493. }
  20494. });
  20495. // Edges
  20496. if (this._edgesRenderer) {
  20497. this._edgesRenderer.dispose();
  20498. this._edgesRenderer = null;
  20499. }
  20500. // SubMeshes
  20501. if (this.getClassName() !== "InstancedMesh") {
  20502. this.releaseSubMeshes();
  20503. }
  20504. // Octree
  20505. var sceneOctree = this.getScene().selectionOctree;
  20506. if (sceneOctree !== undefined && sceneOctree !== null) {
  20507. var index = sceneOctree.dynamicContent.indexOf(this);
  20508. if (index !== -1) {
  20509. sceneOctree.dynamicContent.splice(index, 1);
  20510. }
  20511. }
  20512. // Query
  20513. var engine = this.getScene().getEngine();
  20514. if (this._occlusionQuery) {
  20515. this._isOcclusionQueryInProgress = false;
  20516. engine.deleteQuery(this._occlusionQuery);
  20517. this._occlusionQuery = null;
  20518. }
  20519. // Engine
  20520. engine.wipeCaches();
  20521. // Remove from scene
  20522. this.getScene().removeMesh(this);
  20523. if (disposeMaterialAndTextures) {
  20524. if (this.material) {
  20525. this.material.dispose(false, true);
  20526. }
  20527. }
  20528. if (!doNotRecurse) {
  20529. // Particles
  20530. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20531. if (this.getScene().particleSystems[index].emitter === this) {
  20532. this.getScene().particleSystems[index].dispose();
  20533. index--;
  20534. }
  20535. }
  20536. }
  20537. // facet data
  20538. if (this._facetDataEnabled) {
  20539. this.disableFacetData();
  20540. }
  20541. this.onAfterWorldMatrixUpdateObservable.clear();
  20542. this.onCollideObservable.clear();
  20543. this.onCollisionPositionChangeObservable.clear();
  20544. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20545. };
  20546. /**
  20547. * Adds the passed mesh as a child to the current mesh
  20548. * @param mesh defines the child mesh
  20549. * @returns the current mesh
  20550. */
  20551. AbstractMesh.prototype.addChild = function (mesh) {
  20552. mesh.setParent(this);
  20553. return this;
  20554. };
  20555. /**
  20556. * Removes the passed mesh from the current mesh children list
  20557. * @param mesh defines the child mesh
  20558. * @returns the current mesh
  20559. */
  20560. AbstractMesh.prototype.removeChild = function (mesh) {
  20561. mesh.setParent(null);
  20562. return this;
  20563. };
  20564. // Facet data
  20565. /** @ignore */
  20566. AbstractMesh.prototype._initFacetData = function () {
  20567. if (!this._facetNormals) {
  20568. this._facetNormals = new Array();
  20569. }
  20570. if (!this._facetPositions) {
  20571. this._facetPositions = new Array();
  20572. }
  20573. if (!this._facetPartitioning) {
  20574. this._facetPartitioning = new Array();
  20575. }
  20576. this._facetNb = (this.getIndices().length / 3) | 0;
  20577. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20578. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20579. for (var f = 0; f < this._facetNb; f++) {
  20580. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20581. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20582. }
  20583. this._facetDataEnabled = true;
  20584. return this;
  20585. };
  20586. /**
  20587. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20588. * This method can be called within the render loop.
  20589. * 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
  20590. * @returns the current mesh
  20591. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20592. */
  20593. AbstractMesh.prototype.updateFacetData = function () {
  20594. if (!this._facetDataEnabled) {
  20595. this._initFacetData();
  20596. }
  20597. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20598. var indices = this.getIndices();
  20599. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20600. var bInfo = this.getBoundingInfo();
  20601. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20602. // init arrays, matrix and sort function on first call
  20603. this._facetDepthSortEnabled = true;
  20604. if (indices instanceof Uint16Array) {
  20605. this._depthSortedIndices = new Uint16Array(indices);
  20606. }
  20607. else if (indices instanceof Uint32Array) {
  20608. this._depthSortedIndices = new Uint32Array(indices);
  20609. }
  20610. else {
  20611. var needs32bits = false;
  20612. for (var i = 0; i < indices.length; i++) {
  20613. if (indices[i] > 65535) {
  20614. needs32bits = true;
  20615. break;
  20616. }
  20617. }
  20618. if (needs32bits) {
  20619. this._depthSortedIndices = new Uint32Array(indices);
  20620. }
  20621. else {
  20622. this._depthSortedIndices = new Uint16Array(indices);
  20623. }
  20624. }
  20625. this._facetDepthSortFunction = function (f1, f2) {
  20626. return (f2.sqDistance - f1.sqDistance);
  20627. };
  20628. if (!this._facetDepthSortFrom) {
  20629. var camera = this.getScene().activeCamera;
  20630. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20631. }
  20632. this._depthSortedFacets = [];
  20633. for (var f = 0; f < this._facetNb; f++) {
  20634. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20635. this._depthSortedFacets.push(depthSortedFacet);
  20636. }
  20637. this._invertedMatrix = BABYLON.Matrix.Identity();
  20638. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20639. }
  20640. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20641. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20642. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20643. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20644. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20645. this._subDiv.max = this._partitioningSubdivisions;
  20646. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20647. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20648. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20649. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20650. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20651. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20652. // set the parameters for ComputeNormals()
  20653. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20654. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20655. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20656. this._facetParameters.bInfo = bInfo;
  20657. this._facetParameters.bbSize = this._bbSize;
  20658. this._facetParameters.subDiv = this._subDiv;
  20659. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20660. this._facetParameters.depthSort = this._facetDepthSort;
  20661. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20662. this.computeWorldMatrix(true);
  20663. this._worldMatrix.invertToRef(this._invertedMatrix);
  20664. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20665. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20666. }
  20667. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20668. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20669. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20670. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20671. var l = (this._depthSortedIndices.length / 3) | 0;
  20672. for (var f = 0; f < l; f++) {
  20673. var sind = this._depthSortedFacets[f].ind;
  20674. this._depthSortedIndices[f * 3] = indices[sind];
  20675. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20676. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20677. }
  20678. this.updateIndices(this._depthSortedIndices);
  20679. }
  20680. return this;
  20681. };
  20682. /**
  20683. * Returns the facetLocalNormals array.
  20684. * The normals are expressed in the mesh local spac
  20685. * @returns an array of Vector3
  20686. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20687. */
  20688. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20689. if (!this._facetNormals) {
  20690. this.updateFacetData();
  20691. }
  20692. return this._facetNormals;
  20693. };
  20694. /**
  20695. * Returns the facetLocalPositions array.
  20696. * The facet positions are expressed in the mesh local space
  20697. * @returns an array of Vector3
  20698. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20699. */
  20700. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20701. if (!this._facetPositions) {
  20702. this.updateFacetData();
  20703. }
  20704. return this._facetPositions;
  20705. };
  20706. /**
  20707. * Returns the facetLocalPartioning array
  20708. * @returns an array of array of numbers
  20709. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20710. */
  20711. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20712. if (!this._facetPartitioning) {
  20713. this.updateFacetData();
  20714. }
  20715. return this._facetPartitioning;
  20716. };
  20717. /**
  20718. * Returns the i-th facet position in the world system.
  20719. * This method allocates a new Vector3 per call
  20720. * @param i defines the facet index
  20721. * @returns a new Vector3
  20722. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20723. */
  20724. AbstractMesh.prototype.getFacetPosition = function (i) {
  20725. var pos = BABYLON.Vector3.Zero();
  20726. this.getFacetPositionToRef(i, pos);
  20727. return pos;
  20728. };
  20729. /**
  20730. * Sets the reference Vector3 with the i-th facet position in the world system
  20731. * @param i defines the facet index
  20732. * @param ref defines the target vector
  20733. * @returns the current mesh
  20734. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20735. */
  20736. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20737. var localPos = (this.getFacetLocalPositions())[i];
  20738. var world = this.getWorldMatrix();
  20739. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20740. return this;
  20741. };
  20742. /**
  20743. * Returns the i-th facet normal in the world system.
  20744. * This method allocates a new Vector3 per call
  20745. * @param i defines the facet index
  20746. * @returns a new Vector3
  20747. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20748. */
  20749. AbstractMesh.prototype.getFacetNormal = function (i) {
  20750. var norm = BABYLON.Vector3.Zero();
  20751. this.getFacetNormalToRef(i, norm);
  20752. return norm;
  20753. };
  20754. /**
  20755. * Sets the reference Vector3 with the i-th facet normal in the world system
  20756. * @param i defines the facet index
  20757. * @param ref defines the target vector
  20758. * @returns the current mesh
  20759. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20760. */
  20761. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20762. var localNorm = (this.getFacetLocalNormals())[i];
  20763. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20764. return this;
  20765. };
  20766. /**
  20767. * 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)
  20768. * @param x defines x coordinate
  20769. * @param y defines y coordinate
  20770. * @param z defines z coordinate
  20771. * @returns the array of facet indexes
  20772. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20773. */
  20774. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20775. var bInfo = this.getBoundingInfo();
  20776. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20777. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20778. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20779. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20780. return null;
  20781. }
  20782. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20783. };
  20784. /**
  20785. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20786. * @param projected sets as the (x,y,z) world projection on the facet
  20787. * @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
  20788. * @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
  20789. * @param x defines x coordinate
  20790. * @param y defines y coordinate
  20791. * @param z defines z coordinate
  20792. * @returns the face index if found (or null instead)
  20793. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20794. */
  20795. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20796. if (checkFace === void 0) { checkFace = false; }
  20797. if (facing === void 0) { facing = true; }
  20798. var world = this.getWorldMatrix();
  20799. var invMat = BABYLON.Tmp.Matrix[5];
  20800. world.invertToRef(invMat);
  20801. var invVect = BABYLON.Tmp.Vector3[8];
  20802. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20803. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20804. if (projected) {
  20805. // tranform the local computed projected vector to world coordinates
  20806. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20807. }
  20808. return closest;
  20809. };
  20810. /**
  20811. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  20812. * @param projected sets as the (x,y,z) local projection on the facet
  20813. * @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
  20814. * @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
  20815. * @param x defines x coordinate
  20816. * @param y defines y coordinate
  20817. * @param z defines z coordinate
  20818. * @returns the face index if found (or null instead)
  20819. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20820. */
  20821. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  20822. if (checkFace === void 0) { checkFace = false; }
  20823. if (facing === void 0) { facing = true; }
  20824. var closest = null;
  20825. var tmpx = 0.0;
  20826. var tmpy = 0.0;
  20827. var tmpz = 0.0;
  20828. var d = 0.0; // tmp dot facet normal * facet position
  20829. var t0 = 0.0;
  20830. var projx = 0.0;
  20831. var projy = 0.0;
  20832. var projz = 0.0;
  20833. // Get all the facets in the same partitioning block than (x, y, z)
  20834. var facetPositions = this.getFacetLocalPositions();
  20835. var facetNormals = this.getFacetLocalNormals();
  20836. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  20837. if (!facetsInBlock) {
  20838. return null;
  20839. }
  20840. // Get the closest facet to (x, y, z)
  20841. var shortest = Number.MAX_VALUE; // init distance vars
  20842. var tmpDistance = shortest;
  20843. var fib; // current facet in the block
  20844. var norm; // current facet normal
  20845. var p0; // current facet barycenter position
  20846. // loop on all the facets in the current partitioning block
  20847. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  20848. fib = facetsInBlock[idx];
  20849. norm = facetNormals[fib];
  20850. p0 = facetPositions[fib];
  20851. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  20852. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  20853. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  20854. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  20855. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  20856. projx = x + norm.x * t0;
  20857. projy = y + norm.y * t0;
  20858. projz = z + norm.z * t0;
  20859. tmpx = projx - x;
  20860. tmpy = projy - y;
  20861. tmpz = projz - z;
  20862. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  20863. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  20864. shortest = tmpDistance;
  20865. closest = fib;
  20866. if (projected) {
  20867. projected.x = projx;
  20868. projected.y = projy;
  20869. projected.z = projz;
  20870. }
  20871. }
  20872. }
  20873. }
  20874. return closest;
  20875. };
  20876. /**
  20877. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  20878. * @returns the parameters
  20879. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20880. */
  20881. AbstractMesh.prototype.getFacetDataParameters = function () {
  20882. return this._facetParameters;
  20883. };
  20884. /**
  20885. * Disables the feature FacetData and frees the related memory
  20886. * @returns the current mesh
  20887. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20888. */
  20889. AbstractMesh.prototype.disableFacetData = function () {
  20890. if (this._facetDataEnabled) {
  20891. this._facetDataEnabled = false;
  20892. this._facetPositions = new Array();
  20893. this._facetNormals = new Array();
  20894. this._facetPartitioning = new Array();
  20895. this._facetParameters = null;
  20896. this._depthSortedIndices = new Uint32Array(0);
  20897. }
  20898. return this;
  20899. };
  20900. /**
  20901. * Updates the AbstractMesh indices array
  20902. * @param indices defines the data source
  20903. * @returns the current mesh
  20904. */
  20905. AbstractMesh.prototype.updateIndices = function (indices) {
  20906. return this;
  20907. };
  20908. /**
  20909. * Creates new normals data for the mesh
  20910. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  20911. * @returns the current mesh
  20912. */
  20913. AbstractMesh.prototype.createNormals = function (updatable) {
  20914. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20915. var indices = this.getIndices();
  20916. var normals;
  20917. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20918. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20919. }
  20920. else {
  20921. normals = [];
  20922. }
  20923. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  20924. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  20925. return this;
  20926. };
  20927. /**
  20928. * Align the mesh with a normal
  20929. * @param normal defines the normal to use
  20930. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  20931. * @returns the current mesh
  20932. */
  20933. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  20934. if (!upDirection) {
  20935. upDirection = BABYLON.Axis.Y;
  20936. }
  20937. var axisX = BABYLON.Tmp.Vector3[0];
  20938. var axisZ = BABYLON.Tmp.Vector3[1];
  20939. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  20940. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  20941. if (this.rotationQuaternion) {
  20942. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  20943. }
  20944. else {
  20945. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  20946. }
  20947. return this;
  20948. };
  20949. /** @ignore */
  20950. AbstractMesh.prototype._checkOcclusionQuery = function () {
  20951. var engine = this.getEngine();
  20952. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  20953. this._isOccluded = false;
  20954. return;
  20955. }
  20956. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  20957. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  20958. if (isOcclusionQueryAvailable) {
  20959. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  20960. this._isOcclusionQueryInProgress = false;
  20961. this._occlusionInternalRetryCounter = 0;
  20962. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  20963. }
  20964. else {
  20965. this._occlusionInternalRetryCounter++;
  20966. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  20967. this._isOcclusionQueryInProgress = false;
  20968. this._occlusionInternalRetryCounter = 0;
  20969. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  20970. // if strict continue the last state of the object.
  20971. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  20972. }
  20973. else {
  20974. return;
  20975. }
  20976. }
  20977. }
  20978. var scene = this.getScene();
  20979. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  20980. if (!this._occlusionQuery) {
  20981. this._occlusionQuery = engine.createQuery();
  20982. }
  20983. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  20984. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  20985. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  20986. this._isOcclusionQueryInProgress = true;
  20987. };
  20988. /** No occlusion */
  20989. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  20990. /** Occlusion set to optimisitic */
  20991. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  20992. /** Occlusion set to strict */
  20993. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  20994. /** Use an accurante occlusion algorithm */
  20995. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  20996. /** Use a conservative occlusion algorithm */
  20997. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  20998. return AbstractMesh;
  20999. }(BABYLON.TransformNode));
  21000. BABYLON.AbstractMesh = AbstractMesh;
  21001. })(BABYLON || (BABYLON = {}));
  21002. //# sourceMappingURL=babylon.abstractMesh.js.map
  21003. var BABYLON;
  21004. (function (BABYLON) {
  21005. /**
  21006. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21007. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21008. * 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.
  21009. */
  21010. var Light = /** @class */ (function (_super) {
  21011. __extends(Light, _super);
  21012. /**
  21013. * Creates a Light object in the scene.
  21014. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21015. * @param name The firendly name of the light
  21016. * @param scene The scene the light belongs too
  21017. */
  21018. function Light(name, scene) {
  21019. var _this = _super.call(this, name, scene) || this;
  21020. /**
  21021. * Diffuse gives the basic color to an object.
  21022. */
  21023. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21024. /**
  21025. * Specular produces a highlight color on an object.
  21026. * Note: This is note affecting PBR materials.
  21027. */
  21028. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21029. /**
  21030. * Strength of the light.
  21031. * Note: By default it is define in the framework own unit.
  21032. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21033. */
  21034. _this.intensity = 1.0;
  21035. /**
  21036. * Defines how far from the source the light is impacting in scene units.
  21037. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21038. */
  21039. _this.range = Number.MAX_VALUE;
  21040. /**
  21041. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21042. * of light.
  21043. */
  21044. _this._photometricScale = 1.0;
  21045. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21046. _this._radius = 0.00001;
  21047. /**
  21048. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21049. * exceeding the number allowed of the materials.
  21050. */
  21051. _this.renderPriority = 0;
  21052. /**
  21053. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21054. * the current shadow generator.
  21055. */
  21056. _this.shadowEnabled = true;
  21057. _this._excludeWithLayerMask = 0;
  21058. _this._includeOnlyWithLayerMask = 0;
  21059. _this._lightmapMode = 0;
  21060. /**
  21061. * @ignore Internal use only.
  21062. */
  21063. _this._excludedMeshesIds = new Array();
  21064. /**
  21065. * @ignore Internal use only.
  21066. */
  21067. _this._includedOnlyMeshesIds = new Array();
  21068. _this.getScene().addLight(_this);
  21069. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21070. _this._buildUniformLayout();
  21071. _this.includedOnlyMeshes = new Array();
  21072. _this.excludedMeshes = new Array();
  21073. _this._resyncMeshes();
  21074. return _this;
  21075. }
  21076. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21077. /**
  21078. * If every light affecting the material is in this lightmapMode,
  21079. * material.lightmapTexture adds or multiplies
  21080. * (depends on material.useLightmapAsShadowmap)
  21081. * after every other light calculations.
  21082. */
  21083. get: function () {
  21084. return Light._LIGHTMAP_DEFAULT;
  21085. },
  21086. enumerable: true,
  21087. configurable: true
  21088. });
  21089. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21090. /**
  21091. * material.lightmapTexture as only diffuse lighting from this light
  21092. * adds only specular lighting from this light
  21093. * adds dynamic shadows
  21094. */
  21095. get: function () {
  21096. return Light._LIGHTMAP_SPECULAR;
  21097. },
  21098. enumerable: true,
  21099. configurable: true
  21100. });
  21101. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21102. /**
  21103. * material.lightmapTexture as only lighting
  21104. * no light calculation from this light
  21105. * only adds dynamic shadows from this light
  21106. */
  21107. get: function () {
  21108. return Light._LIGHTMAP_SHADOWSONLY;
  21109. },
  21110. enumerable: true,
  21111. configurable: true
  21112. });
  21113. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21114. /**
  21115. * Each light type uses the default quantity according to its type:
  21116. * point/spot lights use luminous intensity
  21117. * directional lights use illuminance
  21118. */
  21119. get: function () {
  21120. return Light._INTENSITYMODE_AUTOMATIC;
  21121. },
  21122. enumerable: true,
  21123. configurable: true
  21124. });
  21125. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21126. /**
  21127. * lumen (lm)
  21128. */
  21129. get: function () {
  21130. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21131. },
  21132. enumerable: true,
  21133. configurable: true
  21134. });
  21135. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21136. /**
  21137. * candela (lm/sr)
  21138. */
  21139. get: function () {
  21140. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21141. },
  21142. enumerable: true,
  21143. configurable: true
  21144. });
  21145. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21146. /**
  21147. * lux (lm/m^2)
  21148. */
  21149. get: function () {
  21150. return Light._INTENSITYMODE_ILLUMINANCE;
  21151. },
  21152. enumerable: true,
  21153. configurable: true
  21154. });
  21155. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21156. /**
  21157. * nit (cd/m^2)
  21158. */
  21159. get: function () {
  21160. return Light._INTENSITYMODE_LUMINANCE;
  21161. },
  21162. enumerable: true,
  21163. configurable: true
  21164. });
  21165. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21166. /**
  21167. * Light type const id of the point light.
  21168. */
  21169. get: function () {
  21170. return Light._LIGHTTYPEID_POINTLIGHT;
  21171. },
  21172. enumerable: true,
  21173. configurable: true
  21174. });
  21175. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21176. /**
  21177. * Light type const id of the directional light.
  21178. */
  21179. get: function () {
  21180. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21181. },
  21182. enumerable: true,
  21183. configurable: true
  21184. });
  21185. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21186. /**
  21187. * Light type const id of the spot light.
  21188. */
  21189. get: function () {
  21190. return Light._LIGHTTYPEID_SPOTLIGHT;
  21191. },
  21192. enumerable: true,
  21193. configurable: true
  21194. });
  21195. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21196. /**
  21197. * Light type const id of the hemispheric light.
  21198. */
  21199. get: function () {
  21200. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21201. },
  21202. enumerable: true,
  21203. configurable: true
  21204. });
  21205. Object.defineProperty(Light.prototype, "intensityMode", {
  21206. /**
  21207. * Gets the photometric scale used to interpret the intensity.
  21208. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21209. */
  21210. get: function () {
  21211. return this._intensityMode;
  21212. },
  21213. /**
  21214. * Sets the photometric scale used to interpret the intensity.
  21215. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21216. */
  21217. set: function (value) {
  21218. this._intensityMode = value;
  21219. this._computePhotometricScale();
  21220. },
  21221. enumerable: true,
  21222. configurable: true
  21223. });
  21224. ;
  21225. ;
  21226. Object.defineProperty(Light.prototype, "radius", {
  21227. /**
  21228. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21229. */
  21230. get: function () {
  21231. return this._radius;
  21232. },
  21233. /**
  21234. * sets the light radius used by PBR Materials to simulate soft area lights.
  21235. */
  21236. set: function (value) {
  21237. this._radius = value;
  21238. this._computePhotometricScale();
  21239. },
  21240. enumerable: true,
  21241. configurable: true
  21242. });
  21243. ;
  21244. ;
  21245. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21246. /**
  21247. * Gets the only meshes impacted by this light.
  21248. */
  21249. get: function () {
  21250. return this._includedOnlyMeshes;
  21251. },
  21252. /**
  21253. * Sets the only meshes impacted by this light.
  21254. */
  21255. set: function (value) {
  21256. this._includedOnlyMeshes = value;
  21257. this._hookArrayForIncludedOnly(value);
  21258. },
  21259. enumerable: true,
  21260. configurable: true
  21261. });
  21262. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21263. /**
  21264. * Gets the meshes not impacted by this light.
  21265. */
  21266. get: function () {
  21267. return this._excludedMeshes;
  21268. },
  21269. /**
  21270. * Sets the meshes not impacted by this light.
  21271. */
  21272. set: function (value) {
  21273. this._excludedMeshes = value;
  21274. this._hookArrayForExcluded(value);
  21275. },
  21276. enumerable: true,
  21277. configurable: true
  21278. });
  21279. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21280. /**
  21281. * Gets the layer id use to find what meshes are not impacted by the light.
  21282. * Inactive if 0
  21283. */
  21284. get: function () {
  21285. return this._excludeWithLayerMask;
  21286. },
  21287. /**
  21288. * Sets the layer id use to find what meshes are not impacted by the light.
  21289. * Inactive if 0
  21290. */
  21291. set: function (value) {
  21292. this._excludeWithLayerMask = value;
  21293. this._resyncMeshes();
  21294. },
  21295. enumerable: true,
  21296. configurable: true
  21297. });
  21298. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21299. /**
  21300. * Gets the layer id use to find what meshes are impacted by the light.
  21301. * Inactive if 0
  21302. */
  21303. get: function () {
  21304. return this._includeOnlyWithLayerMask;
  21305. },
  21306. /**
  21307. * Sets the layer id use to find what meshes are impacted by the light.
  21308. * Inactive if 0
  21309. */
  21310. set: function (value) {
  21311. this._includeOnlyWithLayerMask = value;
  21312. this._resyncMeshes();
  21313. },
  21314. enumerable: true,
  21315. configurable: true
  21316. });
  21317. Object.defineProperty(Light.prototype, "lightmapMode", {
  21318. /**
  21319. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21320. */
  21321. get: function () {
  21322. return this._lightmapMode;
  21323. },
  21324. /**
  21325. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21326. */
  21327. set: function (value) {
  21328. if (this._lightmapMode === value) {
  21329. return;
  21330. }
  21331. this._lightmapMode = value;
  21332. this._markMeshesAsLightDirty();
  21333. },
  21334. enumerable: true,
  21335. configurable: true
  21336. });
  21337. /**
  21338. * Returns the string "Light".
  21339. * @returns the class name
  21340. */
  21341. Light.prototype.getClassName = function () {
  21342. return "Light";
  21343. };
  21344. /**
  21345. * Converts the light information to a readable string for debug purpose.
  21346. * @param fullDetails Supports for multiple levels of logging within scene loading
  21347. * @returns the human readable light info
  21348. */
  21349. Light.prototype.toString = function (fullDetails) {
  21350. var ret = "Name: " + this.name;
  21351. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21352. if (this.animations) {
  21353. for (var i = 0; i < this.animations.length; i++) {
  21354. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21355. }
  21356. }
  21357. if (fullDetails) {
  21358. }
  21359. return ret;
  21360. };
  21361. /**
  21362. * Set the enabled state of this node.
  21363. * @param value - the new enabled state
  21364. */
  21365. Light.prototype.setEnabled = function (value) {
  21366. _super.prototype.setEnabled.call(this, value);
  21367. this._resyncMeshes();
  21368. };
  21369. /**
  21370. * Returns the Light associated shadow generator if any.
  21371. * @return the associated shadow generator.
  21372. */
  21373. Light.prototype.getShadowGenerator = function () {
  21374. return this._shadowGenerator;
  21375. };
  21376. /**
  21377. * Returns a Vector3, the absolute light position in the World.
  21378. * @returns the world space position of the light
  21379. */
  21380. Light.prototype.getAbsolutePosition = function () {
  21381. return BABYLON.Vector3.Zero();
  21382. };
  21383. /**
  21384. * Specifies if the light will affect the passed mesh.
  21385. * @param mesh The mesh to test against the light
  21386. * @return true the mesh is affected otherwise, false.
  21387. */
  21388. Light.prototype.canAffectMesh = function (mesh) {
  21389. if (!mesh) {
  21390. return true;
  21391. }
  21392. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21393. return false;
  21394. }
  21395. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21396. return false;
  21397. }
  21398. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21399. return false;
  21400. }
  21401. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21402. return false;
  21403. }
  21404. return true;
  21405. };
  21406. /**
  21407. * Computes and Returns the light World matrix.
  21408. * @returns the world matrix
  21409. */
  21410. Light.prototype.getWorldMatrix = function () {
  21411. this._currentRenderId = this.getScene().getRenderId();
  21412. this._childRenderId = this._currentRenderId;
  21413. var worldMatrix = this._getWorldMatrix();
  21414. if (this.parent && this.parent.getWorldMatrix) {
  21415. if (!this._parentedWorldMatrix) {
  21416. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21417. }
  21418. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21419. this._markSyncedWithParent();
  21420. return this._parentedWorldMatrix;
  21421. }
  21422. return worldMatrix;
  21423. };
  21424. /**
  21425. * Sort function to order lights for rendering.
  21426. * @param a First Light object to compare to second.
  21427. * @param b Second Light object to compare first.
  21428. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21429. */
  21430. Light.CompareLightsPriority = function (a, b) {
  21431. //shadow-casting lights have priority over non-shadow-casting lights
  21432. //the renderPrioirty is a secondary sort criterion
  21433. if (a.shadowEnabled !== b.shadowEnabled) {
  21434. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21435. }
  21436. return b.renderPriority - a.renderPriority;
  21437. };
  21438. /**
  21439. * Releases resources associated with this node.
  21440. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21441. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21442. */
  21443. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21444. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21445. if (this._shadowGenerator) {
  21446. this._shadowGenerator.dispose();
  21447. this._shadowGenerator = null;
  21448. }
  21449. // Animations
  21450. this.getScene().stopAnimation(this);
  21451. // Remove from meshes
  21452. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21453. var mesh = _a[_i];
  21454. mesh._removeLightSource(this);
  21455. }
  21456. this._uniformBuffer.dispose();
  21457. // Remove from scene
  21458. this.getScene().removeLight(this);
  21459. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21460. };
  21461. /**
  21462. * Returns the light type ID (integer).
  21463. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21464. */
  21465. Light.prototype.getTypeID = function () {
  21466. return 0;
  21467. };
  21468. /**
  21469. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21470. * @returns the scaled intensity in intensity mode unit
  21471. */
  21472. Light.prototype.getScaledIntensity = function () {
  21473. return this._photometricScale * this.intensity;
  21474. };
  21475. /**
  21476. * Returns a new Light object, named "name", from the current one.
  21477. * @param name The name of the cloned light
  21478. * @returns the new created light
  21479. */
  21480. Light.prototype.clone = function (name) {
  21481. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21482. if (!constructor) {
  21483. return null;
  21484. }
  21485. return BABYLON.SerializationHelper.Clone(constructor, this);
  21486. };
  21487. /**
  21488. * Serializes the current light into a Serialization object.
  21489. * @returns the serialized object.
  21490. */
  21491. Light.prototype.serialize = function () {
  21492. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21493. // Type
  21494. serializationObject.type = this.getTypeID();
  21495. // Parent
  21496. if (this.parent) {
  21497. serializationObject.parentId = this.parent.id;
  21498. }
  21499. // Inclusion / exclusions
  21500. if (this.excludedMeshes.length > 0) {
  21501. serializationObject.excludedMeshesIds = [];
  21502. this.excludedMeshes.forEach(function (mesh) {
  21503. serializationObject.excludedMeshesIds.push(mesh.id);
  21504. });
  21505. }
  21506. if (this.includedOnlyMeshes.length > 0) {
  21507. serializationObject.includedOnlyMeshesIds = [];
  21508. this.includedOnlyMeshes.forEach(function (mesh) {
  21509. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21510. });
  21511. }
  21512. // Animations
  21513. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21514. serializationObject.ranges = this.serializeAnimationRanges();
  21515. return serializationObject;
  21516. };
  21517. /**
  21518. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21519. * This new light is named "name" and added to the passed scene.
  21520. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21521. * @param name The friendly name of the light
  21522. * @param scene The scene the new light will belong to
  21523. * @returns the constructor function
  21524. */
  21525. Light.GetConstructorFromName = function (type, name, scene) {
  21526. switch (type) {
  21527. case 0:
  21528. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21529. case 1:
  21530. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21531. case 2:
  21532. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21533. case 3:
  21534. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21535. }
  21536. return null;
  21537. };
  21538. /**
  21539. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21540. * @param parsedLight The JSON representation of the light
  21541. * @param scene The scene to create the parsed light in
  21542. * @returns the created light after parsing
  21543. */
  21544. Light.Parse = function (parsedLight, scene) {
  21545. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21546. if (!constructor) {
  21547. return null;
  21548. }
  21549. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21550. // Inclusion / exclusions
  21551. if (parsedLight.excludedMeshesIds) {
  21552. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21553. }
  21554. if (parsedLight.includedOnlyMeshesIds) {
  21555. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21556. }
  21557. // Parent
  21558. if (parsedLight.parentId) {
  21559. light._waitingParentId = parsedLight.parentId;
  21560. }
  21561. // Animations
  21562. if (parsedLight.animations) {
  21563. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21564. var parsedAnimation = parsedLight.animations[animationIndex];
  21565. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21566. }
  21567. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21568. }
  21569. if (parsedLight.autoAnimate) {
  21570. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21571. }
  21572. return light;
  21573. };
  21574. Light.prototype._hookArrayForExcluded = function (array) {
  21575. var _this = this;
  21576. var oldPush = array.push;
  21577. array.push = function () {
  21578. var items = [];
  21579. for (var _i = 0; _i < arguments.length; _i++) {
  21580. items[_i] = arguments[_i];
  21581. }
  21582. var result = oldPush.apply(array, items);
  21583. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21584. var item = items_1[_a];
  21585. item._resyncLighSource(_this);
  21586. }
  21587. return result;
  21588. };
  21589. var oldSplice = array.splice;
  21590. array.splice = function (index, deleteCount) {
  21591. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21592. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21593. var item = deleted_1[_i];
  21594. item._resyncLighSource(_this);
  21595. }
  21596. return deleted;
  21597. };
  21598. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21599. var item = array_1[_i];
  21600. item._resyncLighSource(this);
  21601. }
  21602. };
  21603. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21604. var _this = this;
  21605. var oldPush = array.push;
  21606. array.push = function () {
  21607. var items = [];
  21608. for (var _i = 0; _i < arguments.length; _i++) {
  21609. items[_i] = arguments[_i];
  21610. }
  21611. var result = oldPush.apply(array, items);
  21612. _this._resyncMeshes();
  21613. return result;
  21614. };
  21615. var oldSplice = array.splice;
  21616. array.splice = function (index, deleteCount) {
  21617. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21618. _this._resyncMeshes();
  21619. return deleted;
  21620. };
  21621. this._resyncMeshes();
  21622. };
  21623. Light.prototype._resyncMeshes = function () {
  21624. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21625. var mesh = _a[_i];
  21626. mesh._resyncLighSource(this);
  21627. }
  21628. };
  21629. /**
  21630. * Forces the meshes to update their light related information in their rendering used effects
  21631. * @ignore Internal Use Only
  21632. */
  21633. Light.prototype._markMeshesAsLightDirty = function () {
  21634. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21635. var mesh = _a[_i];
  21636. if (mesh._lightSources.indexOf(this) !== -1) {
  21637. mesh._markSubMeshesAsLightDirty();
  21638. }
  21639. }
  21640. };
  21641. /**
  21642. * Recomputes the cached photometric scale if needed.
  21643. */
  21644. Light.prototype._computePhotometricScale = function () {
  21645. this._photometricScale = this._getPhotometricScale();
  21646. this.getScene().resetCachedMaterial();
  21647. };
  21648. /**
  21649. * Returns the Photometric Scale according to the light type and intensity mode.
  21650. */
  21651. Light.prototype._getPhotometricScale = function () {
  21652. var photometricScale = 0.0;
  21653. var lightTypeID = this.getTypeID();
  21654. //get photometric mode
  21655. var photometricMode = this.intensityMode;
  21656. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21657. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21658. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21659. }
  21660. else {
  21661. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21662. }
  21663. }
  21664. //compute photometric scale
  21665. switch (lightTypeID) {
  21666. case Light.LIGHTTYPEID_POINTLIGHT:
  21667. case Light.LIGHTTYPEID_SPOTLIGHT:
  21668. switch (photometricMode) {
  21669. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21670. photometricScale = 1.0 / (4.0 * Math.PI);
  21671. break;
  21672. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21673. photometricScale = 1.0;
  21674. break;
  21675. case Light.INTENSITYMODE_LUMINANCE:
  21676. photometricScale = this.radius * this.radius;
  21677. break;
  21678. }
  21679. break;
  21680. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21681. switch (photometricMode) {
  21682. case Light.INTENSITYMODE_ILLUMINANCE:
  21683. photometricScale = 1.0;
  21684. break;
  21685. case Light.INTENSITYMODE_LUMINANCE:
  21686. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21687. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21688. var apexAngleRadians = this.radius;
  21689. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21690. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21691. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21692. photometricScale = solidAngle;
  21693. break;
  21694. }
  21695. break;
  21696. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21697. // No fall off in hemisperic light.
  21698. photometricScale = 1.0;
  21699. break;
  21700. }
  21701. return photometricScale;
  21702. };
  21703. /**
  21704. * Reorder the light in the scene according to their defined priority.
  21705. * @ignore Internal Use Only
  21706. */
  21707. Light.prototype._reorderLightsInScene = function () {
  21708. var scene = this.getScene();
  21709. if (this._renderPriority != 0) {
  21710. scene.requireLightSorting = true;
  21711. }
  21712. this.getScene().sortLightsByPriority();
  21713. };
  21714. //lightmapMode Consts
  21715. Light._LIGHTMAP_DEFAULT = 0;
  21716. Light._LIGHTMAP_SPECULAR = 1;
  21717. Light._LIGHTMAP_SHADOWSONLY = 2;
  21718. // Intensity Mode Consts
  21719. Light._INTENSITYMODE_AUTOMATIC = 0;
  21720. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21721. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21722. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21723. Light._INTENSITYMODE_LUMINANCE = 4;
  21724. // Light types ids const.
  21725. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21726. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21727. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21728. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21729. __decorate([
  21730. BABYLON.serializeAsColor3()
  21731. ], Light.prototype, "diffuse", void 0);
  21732. __decorate([
  21733. BABYLON.serializeAsColor3()
  21734. ], Light.prototype, "specular", void 0);
  21735. __decorate([
  21736. BABYLON.serialize()
  21737. ], Light.prototype, "intensity", void 0);
  21738. __decorate([
  21739. BABYLON.serialize()
  21740. ], Light.prototype, "range", void 0);
  21741. __decorate([
  21742. BABYLON.serialize()
  21743. ], Light.prototype, "intensityMode", null);
  21744. __decorate([
  21745. BABYLON.serialize()
  21746. ], Light.prototype, "radius", null);
  21747. __decorate([
  21748. BABYLON.serialize()
  21749. ], Light.prototype, "_renderPriority", void 0);
  21750. __decorate([
  21751. BABYLON.expandToProperty("_reorderLightsInScene")
  21752. ], Light.prototype, "renderPriority", void 0);
  21753. __decorate([
  21754. BABYLON.serialize()
  21755. ], Light.prototype, "shadowEnabled", void 0);
  21756. __decorate([
  21757. BABYLON.serialize("excludeWithLayerMask")
  21758. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21759. __decorate([
  21760. BABYLON.serialize("includeOnlyWithLayerMask")
  21761. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21762. __decorate([
  21763. BABYLON.serialize("lightmapMode")
  21764. ], Light.prototype, "_lightmapMode", void 0);
  21765. return Light;
  21766. }(BABYLON.Node));
  21767. BABYLON.Light = Light;
  21768. })(BABYLON || (BABYLON = {}));
  21769. //# sourceMappingURL=babylon.light.js.map
  21770. var BABYLON;
  21771. (function (BABYLON) {
  21772. var Camera = /** @class */ (function (_super) {
  21773. __extends(Camera, _super);
  21774. function Camera(name, position, scene) {
  21775. var _this = _super.call(this, name, scene) || this;
  21776. /**
  21777. * The vector the camera should consider as up.
  21778. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21779. */
  21780. _this.upVector = BABYLON.Vector3.Up();
  21781. _this.orthoLeft = null;
  21782. _this.orthoRight = null;
  21783. _this.orthoBottom = null;
  21784. _this.orthoTop = null;
  21785. /**
  21786. * FOV is set in Radians. (default is 0.8)
  21787. */
  21788. _this.fov = 0.8;
  21789. _this.minZ = 1;
  21790. _this.maxZ = 10000.0;
  21791. _this.inertia = 0.9;
  21792. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21793. _this.isIntermediate = false;
  21794. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21795. /**
  21796. * Restricts the camera to viewing objects with the same layerMask.
  21797. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21798. */
  21799. _this.layerMask = 0x0FFFFFFF;
  21800. /**
  21801. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21802. */
  21803. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21804. // Camera rig members
  21805. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21806. _this._rigCameras = new Array();
  21807. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21808. _this._skipRendering = false;
  21809. _this.customRenderTargets = new Array();
  21810. // Observables
  21811. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21812. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21813. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21814. _this.onRestoreStateObservable = new BABYLON.Observable();
  21815. // Cache
  21816. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  21817. _this._projectionMatrix = new BABYLON.Matrix();
  21818. _this._doNotComputeProjectionMatrix = false;
  21819. _this._postProcesses = new Array();
  21820. _this._transformMatrix = BABYLON.Matrix.Zero();
  21821. _this._activeMeshes = new BABYLON.SmartArray(256);
  21822. _this._globalPosition = BABYLON.Vector3.Zero();
  21823. _this._refreshFrustumPlanes = true;
  21824. _this.getScene().addCamera(_this);
  21825. if (!_this.getScene().activeCamera) {
  21826. _this.getScene().activeCamera = _this;
  21827. }
  21828. _this.position = position;
  21829. return _this;
  21830. }
  21831. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  21832. get: function () {
  21833. return Camera._PERSPECTIVE_CAMERA;
  21834. },
  21835. enumerable: true,
  21836. configurable: true
  21837. });
  21838. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  21839. get: function () {
  21840. return Camera._ORTHOGRAPHIC_CAMERA;
  21841. },
  21842. enumerable: true,
  21843. configurable: true
  21844. });
  21845. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  21846. /**
  21847. * This is the default FOV mode for perspective cameras.
  21848. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  21849. *
  21850. */
  21851. get: function () {
  21852. return Camera._FOVMODE_VERTICAL_FIXED;
  21853. },
  21854. enumerable: true,
  21855. configurable: true
  21856. });
  21857. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  21858. /**
  21859. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  21860. *
  21861. */
  21862. get: function () {
  21863. return Camera._FOVMODE_HORIZONTAL_FIXED;
  21864. },
  21865. enumerable: true,
  21866. configurable: true
  21867. });
  21868. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  21869. get: function () {
  21870. return Camera._RIG_MODE_NONE;
  21871. },
  21872. enumerable: true,
  21873. configurable: true
  21874. });
  21875. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  21876. get: function () {
  21877. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  21878. },
  21879. enumerable: true,
  21880. configurable: true
  21881. });
  21882. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  21883. get: function () {
  21884. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  21885. },
  21886. enumerable: true,
  21887. configurable: true
  21888. });
  21889. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  21890. get: function () {
  21891. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  21892. },
  21893. enumerable: true,
  21894. configurable: true
  21895. });
  21896. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  21897. get: function () {
  21898. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  21899. },
  21900. enumerable: true,
  21901. configurable: true
  21902. });
  21903. Object.defineProperty(Camera, "RIG_MODE_VR", {
  21904. get: function () {
  21905. return Camera._RIG_MODE_VR;
  21906. },
  21907. enumerable: true,
  21908. configurable: true
  21909. });
  21910. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  21911. get: function () {
  21912. return Camera._RIG_MODE_WEBVR;
  21913. },
  21914. enumerable: true,
  21915. configurable: true
  21916. });
  21917. /**
  21918. * Store current camera state (fov, position, etc..)
  21919. */
  21920. Camera.prototype.storeState = function () {
  21921. this._stateStored = true;
  21922. this._storedFov = this.fov;
  21923. return this;
  21924. };
  21925. /**
  21926. * Restores the camera state values if it has been stored. You must call storeState() first
  21927. */
  21928. Camera.prototype._restoreStateValues = function () {
  21929. if (!this._stateStored) {
  21930. return false;
  21931. }
  21932. this.fov = this._storedFov;
  21933. return true;
  21934. };
  21935. /**
  21936. * Restored camera state. You must call storeState() first
  21937. */
  21938. Camera.prototype.restoreState = function () {
  21939. if (this._restoreStateValues()) {
  21940. this.onRestoreStateObservable.notifyObservers(this);
  21941. return true;
  21942. }
  21943. return false;
  21944. };
  21945. Camera.prototype.getClassName = function () {
  21946. return "Camera";
  21947. };
  21948. /**
  21949. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21950. */
  21951. Camera.prototype.toString = function (fullDetails) {
  21952. var ret = "Name: " + this.name;
  21953. ret += ", type: " + this.getClassName();
  21954. if (this.animations) {
  21955. for (var i = 0; i < this.animations.length; i++) {
  21956. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21957. }
  21958. }
  21959. if (fullDetails) {
  21960. }
  21961. return ret;
  21962. };
  21963. Object.defineProperty(Camera.prototype, "globalPosition", {
  21964. get: function () {
  21965. return this._globalPosition;
  21966. },
  21967. enumerable: true,
  21968. configurable: true
  21969. });
  21970. Camera.prototype.getActiveMeshes = function () {
  21971. return this._activeMeshes;
  21972. };
  21973. Camera.prototype.isActiveMesh = function (mesh) {
  21974. return (this._activeMeshes.indexOf(mesh) !== -1);
  21975. };
  21976. /**
  21977. * Is this camera ready to be used/rendered
  21978. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  21979. * @return true if the camera is ready
  21980. */
  21981. Camera.prototype.isReady = function (completeCheck) {
  21982. if (completeCheck === void 0) { completeCheck = false; }
  21983. if (completeCheck) {
  21984. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  21985. var pp = _a[_i];
  21986. if (pp && !pp.isReady()) {
  21987. return false;
  21988. }
  21989. }
  21990. }
  21991. return _super.prototype.isReady.call(this, completeCheck);
  21992. };
  21993. //Cache
  21994. Camera.prototype._initCache = function () {
  21995. _super.prototype._initCache.call(this);
  21996. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21997. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21998. this._cache.mode = undefined;
  21999. this._cache.minZ = undefined;
  22000. this._cache.maxZ = undefined;
  22001. this._cache.fov = undefined;
  22002. this._cache.fovMode = undefined;
  22003. this._cache.aspectRatio = undefined;
  22004. this._cache.orthoLeft = undefined;
  22005. this._cache.orthoRight = undefined;
  22006. this._cache.orthoBottom = undefined;
  22007. this._cache.orthoTop = undefined;
  22008. this._cache.renderWidth = undefined;
  22009. this._cache.renderHeight = undefined;
  22010. };
  22011. Camera.prototype._updateCache = function (ignoreParentClass) {
  22012. if (!ignoreParentClass) {
  22013. _super.prototype._updateCache.call(this);
  22014. }
  22015. this._cache.position.copyFrom(this.position);
  22016. this._cache.upVector.copyFrom(this.upVector);
  22017. };
  22018. // Synchronized
  22019. Camera.prototype._isSynchronized = function () {
  22020. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22021. };
  22022. Camera.prototype._isSynchronizedViewMatrix = function () {
  22023. if (!_super.prototype._isSynchronized.call(this))
  22024. return false;
  22025. return this._cache.position.equals(this.position)
  22026. && this._cache.upVector.equals(this.upVector)
  22027. && this.isSynchronizedWithParent();
  22028. };
  22029. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22030. var check = this._cache.mode === this.mode
  22031. && this._cache.minZ === this.minZ
  22032. && this._cache.maxZ === this.maxZ;
  22033. if (!check) {
  22034. return false;
  22035. }
  22036. var engine = this.getEngine();
  22037. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22038. check = this._cache.fov === this.fov
  22039. && this._cache.fovMode === this.fovMode
  22040. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22041. }
  22042. else {
  22043. check = this._cache.orthoLeft === this.orthoLeft
  22044. && this._cache.orthoRight === this.orthoRight
  22045. && this._cache.orthoBottom === this.orthoBottom
  22046. && this._cache.orthoTop === this.orthoTop
  22047. && this._cache.renderWidth === engine.getRenderWidth()
  22048. && this._cache.renderHeight === engine.getRenderHeight();
  22049. }
  22050. return check;
  22051. };
  22052. // Controls
  22053. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22054. };
  22055. Camera.prototype.detachControl = function (element) {
  22056. };
  22057. Camera.prototype.update = function () {
  22058. this._checkInputs();
  22059. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22060. this._updateRigCameras();
  22061. }
  22062. };
  22063. Camera.prototype._checkInputs = function () {
  22064. this.onAfterCheckInputsObservable.notifyObservers(this);
  22065. };
  22066. Object.defineProperty(Camera.prototype, "rigCameras", {
  22067. get: function () {
  22068. return this._rigCameras;
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22074. get: function () {
  22075. return this._rigPostProcess;
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. /**
  22081. * Internal, gets the first post proces.
  22082. * @returns the first post process to be run on this camera.
  22083. */
  22084. Camera.prototype._getFirstPostProcess = function () {
  22085. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22086. if (this._postProcesses[ppIndex] !== null) {
  22087. return this._postProcesses[ppIndex];
  22088. }
  22089. }
  22090. return null;
  22091. };
  22092. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22093. // invalidate framebuffer
  22094. var firstPostProcess = this._getFirstPostProcess();
  22095. if (firstPostProcess) {
  22096. firstPostProcess.markTextureDirty();
  22097. }
  22098. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22099. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22100. var cam = this._rigCameras[i];
  22101. var rigPostProcess = cam._rigPostProcess;
  22102. // for VR rig, there does not have to be a post process
  22103. if (rigPostProcess) {
  22104. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22105. if (isPass) {
  22106. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22107. cam.isIntermediate = this._postProcesses.length === 0;
  22108. }
  22109. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22110. rigPostProcess.markTextureDirty();
  22111. }
  22112. else {
  22113. cam._postProcesses = this._postProcesses.slice(0);
  22114. }
  22115. }
  22116. };
  22117. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22118. if (insertAt === void 0) { insertAt = null; }
  22119. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22120. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22121. return 0;
  22122. }
  22123. if (insertAt == null || insertAt < 0) {
  22124. this._postProcesses.push(postProcess);
  22125. }
  22126. else if (this._postProcesses[insertAt] === null) {
  22127. this._postProcesses[insertAt] = postProcess;
  22128. }
  22129. else {
  22130. this._postProcesses.splice(insertAt, 0, postProcess);
  22131. }
  22132. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22133. return this._postProcesses.indexOf(postProcess);
  22134. };
  22135. Camera.prototype.detachPostProcess = function (postProcess) {
  22136. var idx = this._postProcesses.indexOf(postProcess);
  22137. if (idx !== -1) {
  22138. this._postProcesses[idx] = null;
  22139. }
  22140. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22141. };
  22142. Camera.prototype.getWorldMatrix = function () {
  22143. if (!this._worldMatrix) {
  22144. this._worldMatrix = BABYLON.Matrix.Identity();
  22145. }
  22146. var viewMatrix = this.getViewMatrix();
  22147. viewMatrix.invertToRef(this._worldMatrix);
  22148. return this._worldMatrix;
  22149. };
  22150. Camera.prototype._getViewMatrix = function () {
  22151. return BABYLON.Matrix.Identity();
  22152. };
  22153. Camera.prototype.getViewMatrix = function (force) {
  22154. if (!force && this._isSynchronizedViewMatrix()) {
  22155. return this._computedViewMatrix;
  22156. }
  22157. this.updateCache();
  22158. this._computedViewMatrix = this._getViewMatrix();
  22159. this._currentRenderId = this.getScene().getRenderId();
  22160. this._childRenderId = this._currentRenderId;
  22161. this._refreshFrustumPlanes = true;
  22162. if (!this.parent || !this.parent.getWorldMatrix) {
  22163. this._globalPosition.copyFrom(this.position);
  22164. }
  22165. else {
  22166. if (!this._worldMatrix) {
  22167. this._worldMatrix = BABYLON.Matrix.Identity();
  22168. }
  22169. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22170. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  22171. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  22172. this._computedViewMatrix.invert();
  22173. this._markSyncedWithParent();
  22174. }
  22175. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22176. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22177. }
  22178. this.onViewMatrixChangedObservable.notifyObservers(this);
  22179. return this._computedViewMatrix;
  22180. };
  22181. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22182. this._doNotComputeProjectionMatrix = true;
  22183. if (projection !== undefined) {
  22184. this._projectionMatrix = projection;
  22185. }
  22186. };
  22187. ;
  22188. Camera.prototype.unfreezeProjectionMatrix = function () {
  22189. this._doNotComputeProjectionMatrix = false;
  22190. };
  22191. ;
  22192. Camera.prototype.getProjectionMatrix = function (force) {
  22193. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22194. return this._projectionMatrix;
  22195. }
  22196. // Cache
  22197. this._cache.mode = this.mode;
  22198. this._cache.minZ = this.minZ;
  22199. this._cache.maxZ = this.maxZ;
  22200. // Matrix
  22201. this._refreshFrustumPlanes = true;
  22202. var engine = this.getEngine();
  22203. var scene = this.getScene();
  22204. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22205. this._cache.fov = this.fov;
  22206. this._cache.fovMode = this.fovMode;
  22207. this._cache.aspectRatio = engine.getAspectRatio(this);
  22208. if (this.minZ <= 0) {
  22209. this.minZ = 0.1;
  22210. }
  22211. if (scene.useRightHandedSystem) {
  22212. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22213. }
  22214. else {
  22215. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22216. }
  22217. }
  22218. else {
  22219. var halfWidth = engine.getRenderWidth() / 2.0;
  22220. var halfHeight = engine.getRenderHeight() / 2.0;
  22221. if (scene.useRightHandedSystem) {
  22222. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22223. }
  22224. else {
  22225. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22226. }
  22227. this._cache.orthoLeft = this.orthoLeft;
  22228. this._cache.orthoRight = this.orthoRight;
  22229. this._cache.orthoBottom = this.orthoBottom;
  22230. this._cache.orthoTop = this.orthoTop;
  22231. this._cache.renderWidth = engine.getRenderWidth();
  22232. this._cache.renderHeight = engine.getRenderHeight();
  22233. }
  22234. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22235. return this._projectionMatrix;
  22236. };
  22237. Camera.prototype.getTranformationMatrix = function () {
  22238. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22239. return this._transformMatrix;
  22240. };
  22241. Camera.prototype.updateFrustumPlanes = function () {
  22242. if (!this._refreshFrustumPlanes) {
  22243. return;
  22244. }
  22245. this.getTranformationMatrix();
  22246. if (!this._frustumPlanes) {
  22247. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22248. }
  22249. else {
  22250. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22251. }
  22252. this._refreshFrustumPlanes = false;
  22253. };
  22254. Camera.prototype.isInFrustum = function (target) {
  22255. this.updateFrustumPlanes();
  22256. return target.isInFrustum(this._frustumPlanes);
  22257. };
  22258. Camera.prototype.isCompletelyInFrustum = function (target) {
  22259. this.updateFrustumPlanes();
  22260. return target.isCompletelyInFrustum(this._frustumPlanes);
  22261. };
  22262. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22263. if (length === void 0) { length = 100; }
  22264. if (!transform) {
  22265. transform = this.getWorldMatrix();
  22266. }
  22267. if (!origin) {
  22268. origin = this.position;
  22269. }
  22270. var forward = new BABYLON.Vector3(0, 0, 1);
  22271. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22272. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22273. return new BABYLON.Ray(origin, direction, length);
  22274. };
  22275. /**
  22276. * Releases resources associated with this node.
  22277. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22278. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22279. */
  22280. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22281. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22282. // Observables
  22283. this.onViewMatrixChangedObservable.clear();
  22284. this.onProjectionMatrixChangedObservable.clear();
  22285. this.onAfterCheckInputsObservable.clear();
  22286. this.onRestoreStateObservable.clear();
  22287. // Inputs
  22288. if (this.inputs) {
  22289. this.inputs.clear();
  22290. }
  22291. // Animations
  22292. this.getScene().stopAnimation(this);
  22293. // Remove from scene
  22294. this.getScene().removeCamera(this);
  22295. while (this._rigCameras.length > 0) {
  22296. var camera = this._rigCameras.pop();
  22297. if (camera) {
  22298. camera.dispose();
  22299. }
  22300. }
  22301. // Postprocesses
  22302. if (this._rigPostProcess) {
  22303. this._rigPostProcess.dispose(this);
  22304. this._rigPostProcess = null;
  22305. this._postProcesses = [];
  22306. }
  22307. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22308. this._rigPostProcess = null;
  22309. this._postProcesses = [];
  22310. }
  22311. else {
  22312. var i = this._postProcesses.length;
  22313. while (--i >= 0) {
  22314. var postProcess = this._postProcesses[i];
  22315. if (postProcess) {
  22316. postProcess.dispose(this);
  22317. }
  22318. }
  22319. }
  22320. // Render targets
  22321. var i = this.customRenderTargets.length;
  22322. while (--i >= 0) {
  22323. this.customRenderTargets[i].dispose();
  22324. }
  22325. this.customRenderTargets = [];
  22326. // Active Meshes
  22327. this._activeMeshes.dispose();
  22328. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22329. };
  22330. Object.defineProperty(Camera.prototype, "leftCamera", {
  22331. // ---- Camera rigs section ----
  22332. get: function () {
  22333. if (this._rigCameras.length < 1) {
  22334. return null;
  22335. }
  22336. return this._rigCameras[0];
  22337. },
  22338. enumerable: true,
  22339. configurable: true
  22340. });
  22341. Object.defineProperty(Camera.prototype, "rightCamera", {
  22342. get: function () {
  22343. if (this._rigCameras.length < 2) {
  22344. return null;
  22345. }
  22346. return this._rigCameras[1];
  22347. },
  22348. enumerable: true,
  22349. configurable: true
  22350. });
  22351. Camera.prototype.getLeftTarget = function () {
  22352. if (this._rigCameras.length < 1) {
  22353. return null;
  22354. }
  22355. return this._rigCameras[0].getTarget();
  22356. };
  22357. Camera.prototype.getRightTarget = function () {
  22358. if (this._rigCameras.length < 2) {
  22359. return null;
  22360. }
  22361. return this._rigCameras[1].getTarget();
  22362. };
  22363. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22364. if (this.cameraRigMode === mode) {
  22365. return;
  22366. }
  22367. while (this._rigCameras.length > 0) {
  22368. var camera = this._rigCameras.pop();
  22369. if (camera) {
  22370. camera.dispose();
  22371. }
  22372. }
  22373. this.cameraRigMode = mode;
  22374. this._cameraRigParams = {};
  22375. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22376. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22377. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22378. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22379. // create the rig cameras, unless none
  22380. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22381. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22382. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22383. if (leftCamera && rightCamera) {
  22384. this._rigCameras.push(leftCamera);
  22385. this._rigCameras.push(rightCamera);
  22386. }
  22387. }
  22388. switch (this.cameraRigMode) {
  22389. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22390. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22391. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22392. break;
  22393. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22394. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22395. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22396. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22397. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22398. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22399. break;
  22400. case Camera.RIG_MODE_VR:
  22401. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22402. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22403. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22404. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22405. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22406. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22407. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22408. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22409. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22410. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22411. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22412. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22413. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22414. if (metrics.compensateDistortion) {
  22415. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22416. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22417. }
  22418. break;
  22419. case Camera.RIG_MODE_WEBVR:
  22420. if (rigParams.vrDisplay) {
  22421. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22422. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22423. //Left eye
  22424. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22425. this._rigCameras[0].setCameraRigParameter("left", true);
  22426. //leaving this for future reference
  22427. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22428. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22429. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22430. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22431. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22432. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22433. this._rigCameras[0].parent = this;
  22434. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22435. //Right eye
  22436. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22437. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22438. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22439. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22440. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22441. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22442. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22443. this._rigCameras[1].parent = this;
  22444. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22445. if (Camera.UseAlternateWebVRRendering) {
  22446. this._rigCameras[1]._skipRendering = true;
  22447. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22448. }
  22449. }
  22450. break;
  22451. }
  22452. this._cascadePostProcessesToRigCams();
  22453. this.update();
  22454. };
  22455. Camera.prototype._getVRProjectionMatrix = function () {
  22456. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22457. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22458. return this._projectionMatrix;
  22459. };
  22460. Camera.prototype._updateCameraRotationMatrix = function () {
  22461. //Here for WebVR
  22462. };
  22463. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22464. //Here for WebVR
  22465. };
  22466. /**
  22467. * This function MUST be overwritten by the different WebVR cameras available.
  22468. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22469. */
  22470. Camera.prototype._getWebVRProjectionMatrix = function () {
  22471. return BABYLON.Matrix.Identity();
  22472. };
  22473. /**
  22474. * This function MUST be overwritten by the different WebVR cameras available.
  22475. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22476. */
  22477. Camera.prototype._getWebVRViewMatrix = function () {
  22478. return BABYLON.Matrix.Identity();
  22479. };
  22480. Camera.prototype.setCameraRigParameter = function (name, value) {
  22481. if (!this._cameraRigParams) {
  22482. this._cameraRigParams = {};
  22483. }
  22484. this._cameraRigParams[name] = value;
  22485. //provisionnally:
  22486. if (name === "interaxialDistance") {
  22487. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22488. }
  22489. };
  22490. /**
  22491. * needs to be overridden by children so sub has required properties to be copied
  22492. */
  22493. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22494. return null;
  22495. };
  22496. /**
  22497. * May need to be overridden by children
  22498. */
  22499. Camera.prototype._updateRigCameras = function () {
  22500. for (var i = 0; i < this._rigCameras.length; i++) {
  22501. this._rigCameras[i].minZ = this.minZ;
  22502. this._rigCameras[i].maxZ = this.maxZ;
  22503. this._rigCameras[i].fov = this.fov;
  22504. }
  22505. // only update viewport when ANAGLYPH
  22506. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22507. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22508. }
  22509. };
  22510. Camera.prototype._setupInputs = function () {
  22511. };
  22512. Camera.prototype.serialize = function () {
  22513. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22514. // Type
  22515. serializationObject.type = this.getClassName();
  22516. // Parent
  22517. if (this.parent) {
  22518. serializationObject.parentId = this.parent.id;
  22519. }
  22520. if (this.inputs) {
  22521. this.inputs.serialize(serializationObject);
  22522. }
  22523. // Animations
  22524. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22525. serializationObject.ranges = this.serializeAnimationRanges();
  22526. return serializationObject;
  22527. };
  22528. Camera.prototype.clone = function (name) {
  22529. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22530. };
  22531. Camera.prototype.getDirection = function (localAxis) {
  22532. var result = BABYLON.Vector3.Zero();
  22533. this.getDirectionToRef(localAxis, result);
  22534. return result;
  22535. };
  22536. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22537. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22538. };
  22539. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22540. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22541. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22542. switch (type) {
  22543. case "ArcRotateCamera":
  22544. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22545. case "DeviceOrientationCamera":
  22546. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22547. case "FollowCamera":
  22548. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22549. case "ArcFollowCamera":
  22550. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22551. case "GamepadCamera":
  22552. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22553. case "TouchCamera":
  22554. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22555. case "VirtualJoysticksCamera":
  22556. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22557. case "WebVRFreeCamera":
  22558. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22559. case "WebVRGamepadCamera":
  22560. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22561. case "VRDeviceOrientationFreeCamera":
  22562. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22563. case "VRDeviceOrientationGamepadCamera":
  22564. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22565. case "AnaglyphArcRotateCamera":
  22566. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22567. case "AnaglyphFreeCamera":
  22568. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22569. case "AnaglyphGamepadCamera":
  22570. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22571. case "AnaglyphUniversalCamera":
  22572. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22573. case "StereoscopicArcRotateCamera":
  22574. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22575. case "StereoscopicFreeCamera":
  22576. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22577. case "StereoscopicGamepadCamera":
  22578. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22579. case "StereoscopicUniversalCamera":
  22580. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22581. case "FreeCamera": // Forcing Universal here
  22582. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22583. default: // Universal Camera is the default value
  22584. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22585. }
  22586. };
  22587. Camera.prototype.computeWorldMatrix = function () {
  22588. return this.getWorldMatrix();
  22589. };
  22590. Camera.Parse = function (parsedCamera, scene) {
  22591. var type = parsedCamera.type;
  22592. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22593. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22594. // Parent
  22595. if (parsedCamera.parentId) {
  22596. camera._waitingParentId = parsedCamera.parentId;
  22597. }
  22598. //If camera has an input manager, let it parse inputs settings
  22599. if (camera.inputs) {
  22600. camera.inputs.parse(parsedCamera);
  22601. camera._setupInputs();
  22602. }
  22603. if (camera.setPosition) { // need to force position
  22604. camera.position.copyFromFloats(0, 0, 0);
  22605. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22606. }
  22607. // Target
  22608. if (parsedCamera.target) {
  22609. if (camera.setTarget) {
  22610. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22611. }
  22612. }
  22613. // Apply 3d rig, when found
  22614. if (parsedCamera.cameraRigMode) {
  22615. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22616. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22617. }
  22618. // Animations
  22619. if (parsedCamera.animations) {
  22620. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22621. var parsedAnimation = parsedCamera.animations[animationIndex];
  22622. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22623. }
  22624. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22625. }
  22626. if (parsedCamera.autoAnimate) {
  22627. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22628. }
  22629. return camera;
  22630. };
  22631. // Statics
  22632. Camera._PERSPECTIVE_CAMERA = 0;
  22633. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22634. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22635. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22636. Camera._RIG_MODE_NONE = 0;
  22637. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22638. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22639. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22640. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22641. Camera._RIG_MODE_VR = 20;
  22642. Camera._RIG_MODE_WEBVR = 21;
  22643. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22644. Camera.UseAlternateWebVRRendering = false;
  22645. __decorate([
  22646. BABYLON.serializeAsVector3()
  22647. ], Camera.prototype, "position", void 0);
  22648. __decorate([
  22649. BABYLON.serializeAsVector3()
  22650. ], Camera.prototype, "upVector", void 0);
  22651. __decorate([
  22652. BABYLON.serialize()
  22653. ], Camera.prototype, "orthoLeft", void 0);
  22654. __decorate([
  22655. BABYLON.serialize()
  22656. ], Camera.prototype, "orthoRight", void 0);
  22657. __decorate([
  22658. BABYLON.serialize()
  22659. ], Camera.prototype, "orthoBottom", void 0);
  22660. __decorate([
  22661. BABYLON.serialize()
  22662. ], Camera.prototype, "orthoTop", void 0);
  22663. __decorate([
  22664. BABYLON.serialize()
  22665. ], Camera.prototype, "fov", void 0);
  22666. __decorate([
  22667. BABYLON.serialize()
  22668. ], Camera.prototype, "minZ", void 0);
  22669. __decorate([
  22670. BABYLON.serialize()
  22671. ], Camera.prototype, "maxZ", void 0);
  22672. __decorate([
  22673. BABYLON.serialize()
  22674. ], Camera.prototype, "inertia", void 0);
  22675. __decorate([
  22676. BABYLON.serialize()
  22677. ], Camera.prototype, "mode", void 0);
  22678. __decorate([
  22679. BABYLON.serialize()
  22680. ], Camera.prototype, "layerMask", void 0);
  22681. __decorate([
  22682. BABYLON.serialize()
  22683. ], Camera.prototype, "fovMode", void 0);
  22684. __decorate([
  22685. BABYLON.serialize()
  22686. ], Camera.prototype, "cameraRigMode", void 0);
  22687. __decorate([
  22688. BABYLON.serialize()
  22689. ], Camera.prototype, "interaxialDistance", void 0);
  22690. __decorate([
  22691. BABYLON.serialize()
  22692. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22693. return Camera;
  22694. }(BABYLON.Node));
  22695. BABYLON.Camera = Camera;
  22696. })(BABYLON || (BABYLON = {}));
  22697. //# sourceMappingURL=babylon.camera.js.map
  22698. var BABYLON;
  22699. (function (BABYLON) {
  22700. var RenderingManager = /** @class */ (function () {
  22701. function RenderingManager(scene) {
  22702. this._renderingGroups = new Array();
  22703. this._autoClearDepthStencil = {};
  22704. this._customOpaqueSortCompareFn = {};
  22705. this._customAlphaTestSortCompareFn = {};
  22706. this._customTransparentSortCompareFn = {};
  22707. this._renderinGroupInfo = null;
  22708. this._scene = scene;
  22709. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22710. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22711. }
  22712. }
  22713. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22714. if (depth === void 0) { depth = true; }
  22715. if (stencil === void 0) { stencil = true; }
  22716. if (this._depthStencilBufferAlreadyCleaned) {
  22717. return;
  22718. }
  22719. this._scene.getEngine().clear(null, false, depth, stencil);
  22720. this._depthStencilBufferAlreadyCleaned = true;
  22721. };
  22722. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22723. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22724. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22725. var info = null;
  22726. if (observable) {
  22727. if (!this._renderinGroupInfo) {
  22728. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22729. }
  22730. info = this._renderinGroupInfo;
  22731. info.scene = this._scene;
  22732. info.camera = this._scene.activeCamera;
  22733. }
  22734. // Dispatch sprites
  22735. if (renderSprites) {
  22736. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22737. var manager = this._scene.spriteManagers[index];
  22738. this.dispatchSprites(manager);
  22739. }
  22740. }
  22741. // Render
  22742. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22743. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22744. var renderingGroup = this._renderingGroups[index];
  22745. if (!renderingGroup && !observable)
  22746. continue;
  22747. var renderingGroupMask = 0;
  22748. // Fire PRECLEAR stage
  22749. if (observable && info) {
  22750. renderingGroupMask = Math.pow(2, index);
  22751. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22752. info.renderingGroupId = index;
  22753. observable.notifyObservers(info, renderingGroupMask);
  22754. }
  22755. // Clear depth/stencil if needed
  22756. if (RenderingManager.AUTOCLEAR) {
  22757. var autoClear = this._autoClearDepthStencil[index];
  22758. if (autoClear && autoClear.autoClear) {
  22759. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22760. }
  22761. }
  22762. if (observable && info) {
  22763. // Fire PREOPAQUE stage
  22764. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22765. observable.notifyObservers(info, renderingGroupMask);
  22766. // Fire PRETRANSPARENT stage
  22767. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22768. observable.notifyObservers(info, renderingGroupMask);
  22769. }
  22770. if (renderingGroup)
  22771. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22772. // Fire POSTTRANSPARENT stage
  22773. if (observable && info) {
  22774. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22775. observable.notifyObservers(info, renderingGroupMask);
  22776. }
  22777. }
  22778. };
  22779. RenderingManager.prototype.reset = function () {
  22780. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22781. var renderingGroup = this._renderingGroups[index];
  22782. if (renderingGroup) {
  22783. renderingGroup.prepare();
  22784. }
  22785. }
  22786. };
  22787. RenderingManager.prototype.dispose = function () {
  22788. this.freeRenderingGroups();
  22789. this._renderingGroups.length = 0;
  22790. };
  22791. /**
  22792. * Clear the info related to rendering groups preventing retention points during dispose.
  22793. */
  22794. RenderingManager.prototype.freeRenderingGroups = function () {
  22795. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22796. var renderingGroup = this._renderingGroups[index];
  22797. if (renderingGroup) {
  22798. renderingGroup.dispose();
  22799. }
  22800. }
  22801. };
  22802. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22803. if (this._renderingGroups[renderingGroupId] === undefined) {
  22804. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22805. }
  22806. };
  22807. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22808. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22809. this._prepareRenderingGroup(renderingGroupId);
  22810. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22811. };
  22812. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22813. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22814. this._prepareRenderingGroup(renderingGroupId);
  22815. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22816. };
  22817. /**
  22818. * @param subMesh The submesh to dispatch
  22819. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22820. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22821. */
  22822. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22823. if (mesh === undefined) {
  22824. mesh = subMesh.getMesh();
  22825. }
  22826. var renderingGroupId = mesh.renderingGroupId || 0;
  22827. this._prepareRenderingGroup(renderingGroupId);
  22828. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  22829. };
  22830. /**
  22831. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  22832. * This allowed control for front to back rendering or reversly depending of the special needs.
  22833. *
  22834. * @param renderingGroupId The rendering group id corresponding to its index
  22835. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  22836. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  22837. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  22838. */
  22839. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22840. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22841. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22842. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22843. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  22844. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  22845. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  22846. if (this._renderingGroups[renderingGroupId]) {
  22847. var group = this._renderingGroups[renderingGroupId];
  22848. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  22849. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  22850. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  22851. }
  22852. };
  22853. /**
  22854. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  22855. *
  22856. * @param renderingGroupId The rendering group id corresponding to its index
  22857. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  22858. * @param depth Automatically clears depth between groups if true and autoClear is true.
  22859. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  22860. */
  22861. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  22862. if (depth === void 0) { depth = true; }
  22863. if (stencil === void 0) { stencil = true; }
  22864. this._autoClearDepthStencil[renderingGroupId] = {
  22865. autoClear: autoClearDepthStencil,
  22866. depth: depth,
  22867. stencil: stencil
  22868. };
  22869. };
  22870. /**
  22871. * The max id used for rendering groups (not included)
  22872. */
  22873. RenderingManager.MAX_RENDERINGGROUPS = 4;
  22874. /**
  22875. * The min id used for rendering groups (included)
  22876. */
  22877. RenderingManager.MIN_RENDERINGGROUPS = 0;
  22878. /**
  22879. * Used to globally prevent autoclearing scenes.
  22880. */
  22881. RenderingManager.AUTOCLEAR = true;
  22882. return RenderingManager;
  22883. }());
  22884. BABYLON.RenderingManager = RenderingManager;
  22885. })(BABYLON || (BABYLON = {}));
  22886. //# sourceMappingURL=babylon.renderingManager.js.map
  22887. var BABYLON;
  22888. (function (BABYLON) {
  22889. var RenderingGroup = /** @class */ (function () {
  22890. /**
  22891. * Creates a new rendering group.
  22892. * @param index The rendering group index
  22893. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  22894. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  22895. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  22896. */
  22897. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  22898. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  22899. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  22900. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  22901. this.index = index;
  22902. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  22903. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  22904. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  22905. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  22906. this._particleSystems = new BABYLON.SmartArray(256);
  22907. this._spriteManagers = new BABYLON.SmartArray(256);
  22908. this._edgesRenderers = new BABYLON.SmartArray(16);
  22909. this._scene = scene;
  22910. this.opaqueSortCompareFn = opaqueSortCompareFn;
  22911. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  22912. this.transparentSortCompareFn = transparentSortCompareFn;
  22913. }
  22914. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  22915. /**
  22916. * Set the opaque sort comparison function.
  22917. * If null the sub meshes will be render in the order they were created
  22918. */
  22919. set: function (value) {
  22920. this._opaqueSortCompareFn = value;
  22921. if (value) {
  22922. this._renderOpaque = this.renderOpaqueSorted;
  22923. }
  22924. else {
  22925. this._renderOpaque = RenderingGroup.renderUnsorted;
  22926. }
  22927. },
  22928. enumerable: true,
  22929. configurable: true
  22930. });
  22931. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  22932. /**
  22933. * Set the alpha test sort comparison function.
  22934. * If null the sub meshes will be render in the order they were created
  22935. */
  22936. set: function (value) {
  22937. this._alphaTestSortCompareFn = value;
  22938. if (value) {
  22939. this._renderAlphaTest = this.renderAlphaTestSorted;
  22940. }
  22941. else {
  22942. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  22943. }
  22944. },
  22945. enumerable: true,
  22946. configurable: true
  22947. });
  22948. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  22949. /**
  22950. * Set the transparent sort comparison function.
  22951. * If null the sub meshes will be render in the order they were created
  22952. */
  22953. set: function (value) {
  22954. if (value) {
  22955. this._transparentSortCompareFn = value;
  22956. }
  22957. else {
  22958. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  22959. }
  22960. this._renderTransparent = this.renderTransparentSorted;
  22961. },
  22962. enumerable: true,
  22963. configurable: true
  22964. });
  22965. /**
  22966. * Render all the sub meshes contained in the group.
  22967. * @param customRenderFunction Used to override the default render behaviour of the group.
  22968. * @returns true if rendered some submeshes.
  22969. */
  22970. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  22971. if (customRenderFunction) {
  22972. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  22973. return;
  22974. }
  22975. var engine = this._scene.getEngine();
  22976. // Depth only
  22977. if (this._depthOnlySubMeshes.length !== 0) {
  22978. engine.setColorWrite(false);
  22979. this._renderAlphaTest(this._depthOnlySubMeshes);
  22980. engine.setColorWrite(true);
  22981. }
  22982. // Opaque
  22983. if (this._opaqueSubMeshes.length !== 0) {
  22984. this._renderOpaque(this._opaqueSubMeshes);
  22985. }
  22986. // Alpha test
  22987. if (this._alphaTestSubMeshes.length !== 0) {
  22988. this._renderAlphaTest(this._alphaTestSubMeshes);
  22989. }
  22990. var stencilState = engine.getStencilBuffer();
  22991. engine.setStencilBuffer(false);
  22992. // Sprites
  22993. if (renderSprites) {
  22994. this._renderSprites();
  22995. }
  22996. // Particles
  22997. if (renderParticles) {
  22998. this._renderParticles(activeMeshes);
  22999. }
  23000. if (this.onBeforeTransparentRendering) {
  23001. this.onBeforeTransparentRendering();
  23002. }
  23003. // Transparent
  23004. if (this._transparentSubMeshes.length !== 0) {
  23005. this._renderTransparent(this._transparentSubMeshes);
  23006. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23007. }
  23008. // Set back stencil to false in case it changes before the edge renderer.
  23009. engine.setStencilBuffer(false);
  23010. // Edges
  23011. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23012. this._edgesRenderers.data[edgesRendererIndex].render();
  23013. }
  23014. // Restore Stencil state.
  23015. engine.setStencilBuffer(stencilState);
  23016. };
  23017. /**
  23018. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23019. * @param subMeshes The submeshes to render
  23020. */
  23021. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23022. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23023. };
  23024. /**
  23025. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23026. * @param subMeshes The submeshes to render
  23027. */
  23028. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23029. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23030. };
  23031. /**
  23032. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23033. * @param subMeshes The submeshes to render
  23034. */
  23035. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23036. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23037. };
  23038. /**
  23039. * Renders the submeshes in a specified order.
  23040. * @param subMeshes The submeshes to sort before render
  23041. * @param sortCompareFn The comparison function use to sort
  23042. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23043. * @param transparent Specifies to activate blending if true
  23044. */
  23045. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23046. var subIndex = 0;
  23047. var subMesh;
  23048. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23049. for (; subIndex < subMeshes.length; subIndex++) {
  23050. subMesh = subMeshes.data[subIndex];
  23051. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23052. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23053. }
  23054. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23055. if (sortCompareFn) {
  23056. sortedArray.sort(sortCompareFn);
  23057. }
  23058. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23059. subMesh = sortedArray[subIndex];
  23060. if (transparent) {
  23061. var material = subMesh.getMaterial();
  23062. if (material && material.needDepthPrePass) {
  23063. var engine = material.getScene().getEngine();
  23064. engine.setColorWrite(false);
  23065. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23066. subMesh.render(false);
  23067. engine.setColorWrite(true);
  23068. }
  23069. }
  23070. subMesh.render(transparent);
  23071. }
  23072. };
  23073. /**
  23074. * Renders the submeshes in the order they were dispatched (no sort applied).
  23075. * @param subMeshes The submeshes to render
  23076. */
  23077. RenderingGroup.renderUnsorted = function (subMeshes) {
  23078. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23079. var submesh = subMeshes.data[subIndex];
  23080. submesh.render(false);
  23081. }
  23082. };
  23083. /**
  23084. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23085. * are rendered back to front if in the same alpha index.
  23086. *
  23087. * @param a The first submesh
  23088. * @param b The second submesh
  23089. * @returns The result of the comparison
  23090. */
  23091. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23092. // Alpha index first
  23093. if (a._alphaIndex > b._alphaIndex) {
  23094. return 1;
  23095. }
  23096. if (a._alphaIndex < b._alphaIndex) {
  23097. return -1;
  23098. }
  23099. // Then distance to camera
  23100. return RenderingGroup.backToFrontSortCompare(a, b);
  23101. };
  23102. /**
  23103. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23104. * are rendered back to front.
  23105. *
  23106. * @param a The first submesh
  23107. * @param b The second submesh
  23108. * @returns The result of the comparison
  23109. */
  23110. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23111. // Then distance to camera
  23112. if (a._distanceToCamera < b._distanceToCamera) {
  23113. return 1;
  23114. }
  23115. if (a._distanceToCamera > b._distanceToCamera) {
  23116. return -1;
  23117. }
  23118. return 0;
  23119. };
  23120. /**
  23121. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23122. * are rendered front to back (prevent overdraw).
  23123. *
  23124. * @param a The first submesh
  23125. * @param b The second submesh
  23126. * @returns The result of the comparison
  23127. */
  23128. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23129. // Then distance to camera
  23130. if (a._distanceToCamera < b._distanceToCamera) {
  23131. return -1;
  23132. }
  23133. if (a._distanceToCamera > b._distanceToCamera) {
  23134. return 1;
  23135. }
  23136. return 0;
  23137. };
  23138. /**
  23139. * Resets the different lists of submeshes to prepare a new frame.
  23140. */
  23141. RenderingGroup.prototype.prepare = function () {
  23142. this._opaqueSubMeshes.reset();
  23143. this._transparentSubMeshes.reset();
  23144. this._alphaTestSubMeshes.reset();
  23145. this._depthOnlySubMeshes.reset();
  23146. this._particleSystems.reset();
  23147. this._spriteManagers.reset();
  23148. this._edgesRenderers.reset();
  23149. };
  23150. RenderingGroup.prototype.dispose = function () {
  23151. this._opaqueSubMeshes.dispose();
  23152. this._transparentSubMeshes.dispose();
  23153. this._alphaTestSubMeshes.dispose();
  23154. this._depthOnlySubMeshes.dispose();
  23155. this._particleSystems.dispose();
  23156. this._spriteManagers.dispose();
  23157. this._edgesRenderers.dispose();
  23158. };
  23159. /**
  23160. * Inserts the submesh in its correct queue depending on its material.
  23161. * @param subMesh The submesh to dispatch
  23162. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23163. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23164. */
  23165. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23166. // Get mesh and materials if not provided
  23167. if (mesh === undefined) {
  23168. mesh = subMesh.getMesh();
  23169. }
  23170. if (material === undefined) {
  23171. material = subMesh.getMaterial();
  23172. }
  23173. if (material === null || material === undefined) {
  23174. return;
  23175. }
  23176. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23177. this._transparentSubMeshes.push(subMesh);
  23178. }
  23179. else if (material.needAlphaTesting()) { // Alpha test
  23180. if (material.needDepthPrePass) {
  23181. this._depthOnlySubMeshes.push(subMesh);
  23182. }
  23183. this._alphaTestSubMeshes.push(subMesh);
  23184. }
  23185. else {
  23186. if (material.needDepthPrePass) {
  23187. this._depthOnlySubMeshes.push(subMesh);
  23188. }
  23189. this._opaqueSubMeshes.push(subMesh); // Opaque
  23190. }
  23191. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23192. this._edgesRenderers.push(mesh._edgesRenderer);
  23193. }
  23194. };
  23195. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23196. this._spriteManagers.push(spriteManager);
  23197. };
  23198. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23199. this._particleSystems.push(particleSystem);
  23200. };
  23201. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23202. if (this._particleSystems.length === 0) {
  23203. return;
  23204. }
  23205. // Particles
  23206. var activeCamera = this._scene.activeCamera;
  23207. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23208. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23209. var particleSystem = this._particleSystems.data[particleIndex];
  23210. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23211. continue;
  23212. }
  23213. var emitter = particleSystem.emitter;
  23214. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23215. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23216. }
  23217. }
  23218. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23219. };
  23220. RenderingGroup.prototype._renderSprites = function () {
  23221. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23222. return;
  23223. }
  23224. // Sprites
  23225. var activeCamera = this._scene.activeCamera;
  23226. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23227. for (var id = 0; id < this._spriteManagers.length; id++) {
  23228. var spriteManager = this._spriteManagers.data[id];
  23229. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23230. spriteManager.render();
  23231. }
  23232. }
  23233. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23234. };
  23235. return RenderingGroup;
  23236. }());
  23237. BABYLON.RenderingGroup = RenderingGroup;
  23238. })(BABYLON || (BABYLON = {}));
  23239. //# sourceMappingURL=babylon.renderingGroup.js.map
  23240. var BABYLON;
  23241. (function (BABYLON) {
  23242. /** @ignore */
  23243. var ClickInfo = /** @class */ (function () {
  23244. function ClickInfo() {
  23245. this._singleClick = false;
  23246. this._doubleClick = false;
  23247. this._hasSwiped = false;
  23248. this._ignore = false;
  23249. }
  23250. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23251. get: function () {
  23252. return this._singleClick;
  23253. },
  23254. set: function (b) {
  23255. this._singleClick = b;
  23256. },
  23257. enumerable: true,
  23258. configurable: true
  23259. });
  23260. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23261. get: function () {
  23262. return this._doubleClick;
  23263. },
  23264. set: function (b) {
  23265. this._doubleClick = b;
  23266. },
  23267. enumerable: true,
  23268. configurable: true
  23269. });
  23270. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23271. get: function () {
  23272. return this._hasSwiped;
  23273. },
  23274. set: function (b) {
  23275. this._hasSwiped = b;
  23276. },
  23277. enumerable: true,
  23278. configurable: true
  23279. });
  23280. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23281. get: function () {
  23282. return this._ignore;
  23283. },
  23284. set: function (b) {
  23285. this._ignore = b;
  23286. },
  23287. enumerable: true,
  23288. configurable: true
  23289. });
  23290. return ClickInfo;
  23291. }());
  23292. /**
  23293. * This class is used by the onRenderingGroupObservable
  23294. */
  23295. var RenderingGroupInfo = /** @class */ (function () {
  23296. function RenderingGroupInfo() {
  23297. }
  23298. /**
  23299. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23300. * This stage will be fired no matter what
  23301. */
  23302. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23303. /**
  23304. * Called before opaque object are rendered.
  23305. * This stage will be fired only if there's 3D Opaque content to render
  23306. */
  23307. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23308. /**
  23309. * Called after the opaque objects are rendered and before the transparent ones
  23310. * This stage will be fired only if there's 3D transparent content to render
  23311. */
  23312. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23313. /**
  23314. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23315. * This stage will be fired no matter what
  23316. */
  23317. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23318. return RenderingGroupInfo;
  23319. }());
  23320. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23321. /**
  23322. * Represents a scene to be rendered by the engine.
  23323. * @see http://doc.babylonjs.com/features/scene
  23324. */
  23325. var Scene = /** @class */ (function () {
  23326. /**
  23327. * Creates a new Scene
  23328. * @param engine defines the engine to use to render this scene
  23329. */
  23330. function Scene(engine) {
  23331. // Members
  23332. /**
  23333. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23334. */
  23335. this.autoClear = true;
  23336. /**
  23337. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23338. */
  23339. this.autoClearDepthAndStencil = true;
  23340. /**
  23341. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23342. */
  23343. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23344. /**
  23345. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23346. */
  23347. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23348. this._forceWireframe = false;
  23349. this._forcePointsCloud = false;
  23350. /**
  23351. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23352. */
  23353. this.forceShowBoundingBoxes = false;
  23354. /**
  23355. * Gets or sets a boolean indicating if animations are enabled
  23356. */
  23357. this.animationsEnabled = true;
  23358. this._animationPropertiesOverride = null;
  23359. /**
  23360. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23361. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23362. */
  23363. this.useConstantAnimationDeltaTime = false;
  23364. /**
  23365. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23366. * Please note that it requires to run a ray cast through the scene on every frame
  23367. */
  23368. this.constantlyUpdateMeshUnderPointer = false;
  23369. /**
  23370. * Defines the HTML cursor to use when hovering over interactive elements
  23371. */
  23372. this.hoverCursor = "pointer";
  23373. /**
  23374. * Defines the HTML default cursor to use (empty by default)
  23375. */
  23376. this.defaultCursor = "";
  23377. /**
  23378. * This is used to call preventDefault() on pointer down
  23379. * in order to block unwanted artifacts like system double clicks
  23380. */
  23381. this.preventDefaultOnPointerDown = true;
  23382. // Metadata
  23383. /**
  23384. * Gets or sets user defined metadata
  23385. */
  23386. this.metadata = null;
  23387. /**
  23388. * Use this array to add regular expressions used to disable offline support for specific urls
  23389. */
  23390. this.disableOfflineSupportExceptionRules = new Array();
  23391. /**
  23392. * An event triggered when the scene is disposed.
  23393. */
  23394. this.onDisposeObservable = new BABYLON.Observable();
  23395. this._onDisposeObserver = null;
  23396. /**
  23397. * An event triggered before rendering the scene (right after animations and physics)
  23398. */
  23399. this.onBeforeRenderObservable = new BABYLON.Observable();
  23400. this._onBeforeRenderObserver = null;
  23401. /**
  23402. * An event triggered after rendering the scene
  23403. */
  23404. this.onAfterRenderObservable = new BABYLON.Observable();
  23405. this._onAfterRenderObserver = null;
  23406. /**
  23407. * An event triggered before animating the scene
  23408. */
  23409. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23410. /**
  23411. * An event triggered after animations processing
  23412. */
  23413. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23414. /**
  23415. * An event triggered before draw calls are ready to be sent
  23416. */
  23417. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23418. /**
  23419. * An event triggered after draw calls have been sent
  23420. */
  23421. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23422. /**
  23423. * An event triggered when physic simulation is about to be run
  23424. */
  23425. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23426. /**
  23427. * An event triggered when physic simulation has been done
  23428. */
  23429. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23430. /**
  23431. * An event triggered when the scene is ready
  23432. */
  23433. this.onReadyObservable = new BABYLON.Observable();
  23434. /**
  23435. * An event triggered before rendering a camera
  23436. */
  23437. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23438. this._onBeforeCameraRenderObserver = null;
  23439. /**
  23440. * An event triggered after rendering a camera
  23441. */
  23442. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23443. this._onAfterCameraRenderObserver = null;
  23444. /**
  23445. * An event triggered when active meshes evaluation is about to start
  23446. */
  23447. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23448. /**
  23449. * An event triggered when active meshes evaluation is done
  23450. */
  23451. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23452. /**
  23453. * An event triggered when particles rendering is about to start
  23454. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23455. */
  23456. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23457. /**
  23458. * An event triggered when particles rendering is done
  23459. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23460. */
  23461. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23462. /**
  23463. * An event triggered when sprites rendering is about to start
  23464. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23465. */
  23466. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23467. /**
  23468. * An event triggered when sprites rendering is done
  23469. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23470. */
  23471. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23472. /**
  23473. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23474. */
  23475. this.onDataLoadedObservable = new BABYLON.Observable();
  23476. /**
  23477. * An event triggered when a camera is created
  23478. */
  23479. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23480. /**
  23481. * An event triggered when a camera is removed
  23482. */
  23483. this.onCameraRemovedObservable = new BABYLON.Observable();
  23484. /**
  23485. * An event triggered when a light is created
  23486. */
  23487. this.onNewLightAddedObservable = new BABYLON.Observable();
  23488. /**
  23489. * An event triggered when a light is removed
  23490. */
  23491. this.onLightRemovedObservable = new BABYLON.Observable();
  23492. /**
  23493. * An event triggered when a geometry is created
  23494. */
  23495. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23496. /**
  23497. * An event triggered when a geometry is removed
  23498. */
  23499. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23500. /**
  23501. * An event triggered when a transform node is created
  23502. */
  23503. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23504. /**
  23505. * An event triggered when a transform node is removed
  23506. */
  23507. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23508. /**
  23509. * An event triggered when a mesh is created
  23510. */
  23511. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23512. /**
  23513. * An event triggered when a mesh is removed
  23514. */
  23515. this.onMeshRemovedObservable = new BABYLON.Observable();
  23516. /**
  23517. * An event triggered when render targets are about to be rendered
  23518. * Can happen multiple times per frame.
  23519. */
  23520. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23521. /**
  23522. * An event triggered when render targets were rendered.
  23523. * Can happen multiple times per frame.
  23524. */
  23525. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23526. /**
  23527. * An event triggered before calculating deterministic simulation step
  23528. */
  23529. this.onBeforeStepObservable = new BABYLON.Observable();
  23530. /**
  23531. * An event triggered after calculating deterministic simulation step
  23532. */
  23533. this.onAfterStepObservable = new BABYLON.Observable();
  23534. /**
  23535. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23536. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23537. * 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)
  23538. */
  23539. this.onRenderingGroupObservable = new BABYLON.Observable();
  23540. // Animations
  23541. /**
  23542. * Gets a list of Animations associated with the scene
  23543. */
  23544. this.animations = [];
  23545. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23546. /**
  23547. * 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).
  23548. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23549. */
  23550. this.onPrePointerObservable = new BABYLON.Observable();
  23551. /**
  23552. * Observable event triggered each time an input event is received from the rendering canvas
  23553. */
  23554. this.onPointerObservable = new BABYLON.Observable();
  23555. this._meshPickProceed = false;
  23556. this._currentPickResult = null;
  23557. this._previousPickResult = null;
  23558. this._totalPointersPressed = 0;
  23559. this._doubleClickOccured = false;
  23560. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23561. this.cameraToUseForPointers = null;
  23562. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23563. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23564. this._startingPointerTime = 0;
  23565. this._previousStartingPointerTime = 0;
  23566. // Deterministic lockstep
  23567. this._timeAccumulator = 0;
  23568. this._currentStepId = 0;
  23569. this._currentInternalStep = 0;
  23570. // Keyboard
  23571. /**
  23572. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23573. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23574. */
  23575. this.onPreKeyboardObservable = new BABYLON.Observable();
  23576. /**
  23577. * Observable event triggered each time an keyboard event is received from the hosting window
  23578. */
  23579. this.onKeyboardObservable = new BABYLON.Observable();
  23580. // Coordinates system
  23581. this._useRightHandedSystem = false;
  23582. // Fog
  23583. this._fogEnabled = true;
  23584. this._fogMode = Scene.FOGMODE_NONE;
  23585. /**
  23586. * Gets or sets the fog color to use
  23587. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23588. */
  23589. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23590. /**
  23591. * Gets or sets the fog density to use
  23592. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23593. */
  23594. this.fogDensity = 0.1;
  23595. /**
  23596. * Gets or sets the fog start distance to use
  23597. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23598. */
  23599. this.fogStart = 0;
  23600. /**
  23601. * Gets or sets the fog end distance to use
  23602. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23603. */
  23604. this.fogEnd = 1000.0;
  23605. // Lights
  23606. this._shadowsEnabled = true;
  23607. this._lightsEnabled = true;
  23608. /**
  23609. * All of the lights added to this scene
  23610. * @see http://doc.babylonjs.com/babylon101/lights
  23611. */
  23612. this.lights = new Array();
  23613. // Cameras
  23614. /** All of the cameras added to this scene.
  23615. * @see http://doc.babylonjs.com/babylon101/cameras
  23616. */
  23617. this.cameras = new Array();
  23618. /** All of the active cameras added to this scene. */
  23619. this.activeCameras = new Array();
  23620. // Meshes
  23621. /**
  23622. * All of the tranform nodes added to this scene
  23623. * @see http://doc.babylonjs.com/how_to/transformnode
  23624. */
  23625. this.transformNodes = new Array();
  23626. /**
  23627. * All of the (abstract) meshes added to this scene
  23628. */
  23629. this.meshes = new Array();
  23630. /**
  23631. * All of the animation groups added to this scene
  23632. * @see http://doc.babylonjs.com/how_to/group
  23633. */
  23634. this.animationGroups = new Array();
  23635. // Geometries
  23636. this._geometries = new Array();
  23637. /**
  23638. * All of the materials added to this scene
  23639. * @see http://doc.babylonjs.com/babylon101/materials
  23640. */
  23641. this.materials = new Array();
  23642. /**
  23643. * All of the multi-materials added to this scene
  23644. * @see http://doc.babylonjs.com/how_to/multi_materials
  23645. */
  23646. this.multiMaterials = new Array();
  23647. // Textures
  23648. this._texturesEnabled = true;
  23649. /**
  23650. * All of the textures added to this scene
  23651. */
  23652. this.textures = new Array();
  23653. // Particles
  23654. /**
  23655. * Gets or sets a boolean indicating if particles are enabled on this scene
  23656. */
  23657. this.particlesEnabled = true;
  23658. /**
  23659. * All of the particle systems added to this scene
  23660. * @see http://doc.babylonjs.com/babylon101/particles
  23661. */
  23662. this.particleSystems = new Array();
  23663. // Sprites
  23664. /**
  23665. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23666. */
  23667. this.spritesEnabled = true;
  23668. /**
  23669. * All of the sprite managers added to this scene
  23670. * @see http://doc.babylonjs.com/babylon101/sprites
  23671. */
  23672. this.spriteManagers = new Array();
  23673. /**
  23674. * The list of layers (background and foreground) of the scene
  23675. */
  23676. this.layers = new Array();
  23677. /**
  23678. * The list of effect layers (highlights/glow) added to the scene
  23679. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23680. * @see http://doc.babylonjs.com/how_to/glow_layer
  23681. */
  23682. this.effectLayers = new Array();
  23683. // Skeletons
  23684. this._skeletonsEnabled = true;
  23685. /**
  23686. * The list of skeletons added to the scene
  23687. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23688. */
  23689. this.skeletons = new Array();
  23690. // Morph targets
  23691. /**
  23692. * The list of morph target managers added to the scene
  23693. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23694. */
  23695. this.morphTargetManagers = new Array();
  23696. // Lens flares
  23697. /**
  23698. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23699. */
  23700. this.lensFlaresEnabled = true;
  23701. /**
  23702. * The list of lens flare system added to the scene
  23703. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23704. */
  23705. this.lensFlareSystems = new Array();
  23706. // Collisions
  23707. /**
  23708. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23709. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23710. */
  23711. this.collisionsEnabled = true;
  23712. /**
  23713. * Defines the gravity applied to this scene (used only for collisions)
  23714. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23715. */
  23716. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23717. // Postprocesses
  23718. /**
  23719. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23720. */
  23721. this.postProcessesEnabled = true;
  23722. /**
  23723. * The list of postprocesses added to the scene
  23724. */
  23725. this.postProcesses = new Array();
  23726. // Customs render targets
  23727. /**
  23728. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23729. */
  23730. this.renderTargetsEnabled = true;
  23731. /**
  23732. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23733. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23734. */
  23735. this.dumpNextRenderTargets = false;
  23736. /**
  23737. * The list of user defined render targets added to the scene
  23738. */
  23739. this.customRenderTargets = new Array();
  23740. /**
  23741. * Gets the list of meshes imported to the scene through SceneLoader
  23742. */
  23743. this.importedMeshesFiles = new Array();
  23744. // Probes
  23745. /**
  23746. * Gets or sets a boolean indicating if probes are enabled on this scene
  23747. */
  23748. this.probesEnabled = true;
  23749. /**
  23750. * The list of reflection probes added to the scene
  23751. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23752. */
  23753. this.reflectionProbes = new Array();
  23754. /** @ignore */
  23755. this._actionManagers = new Array();
  23756. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23757. // Procedural textures
  23758. /**
  23759. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23760. */
  23761. this.proceduralTexturesEnabled = true;
  23762. /**
  23763. * The list of procedural textures added to the scene
  23764. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23765. */
  23766. this.proceduralTextures = new Array();
  23767. /**
  23768. * The list of sound tracks added to the scene
  23769. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23770. */
  23771. this.soundTracks = new Array();
  23772. this._audioEnabled = true;
  23773. this._headphone = false;
  23774. // Performance counters
  23775. this._totalVertices = new BABYLON.PerfCounter();
  23776. /** @ignore */
  23777. this._activeIndices = new BABYLON.PerfCounter();
  23778. /** @ignore */
  23779. this._activeParticles = new BABYLON.PerfCounter();
  23780. /** @ignore */
  23781. this._activeBones = new BABYLON.PerfCounter();
  23782. this._animationTime = 0;
  23783. /**
  23784. * Gets or sets a general scale for animation speed
  23785. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23786. */
  23787. this.animationTimeScale = 1;
  23788. this._renderId = 0;
  23789. this._executeWhenReadyTimeoutId = -1;
  23790. this._intermediateRendering = false;
  23791. this._viewUpdateFlag = -1;
  23792. this._projectionUpdateFlag = -1;
  23793. this._alternateViewUpdateFlag = -1;
  23794. this._alternateProjectionUpdateFlag = -1;
  23795. /** @ignore */
  23796. this._toBeDisposed = new BABYLON.SmartArray(256);
  23797. this._activeRequests = new Array();
  23798. this._pendingData = new Array();
  23799. this._isDisposed = false;
  23800. /**
  23801. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23802. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23803. */
  23804. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23805. this._activeMeshes = new BABYLON.SmartArray(256);
  23806. this._processedMaterials = new BABYLON.SmartArray(256);
  23807. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23808. /** @ignore */
  23809. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23810. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23811. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23812. /** @ignore */
  23813. this._activeAnimatables = new Array();
  23814. this._transformMatrix = BABYLON.Matrix.Zero();
  23815. this._useAlternateCameraConfiguration = false;
  23816. this._alternateRendering = false;
  23817. /**
  23818. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23819. * This is useful if there are more lights that the maximum simulteanous authorized
  23820. */
  23821. this.requireLightSorting = false;
  23822. this._depthRenderer = {};
  23823. this._activeMeshesFrozen = false;
  23824. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23825. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  23826. this._engine.scenes.push(this);
  23827. this._uid = null;
  23828. this._renderingManager = new BABYLON.RenderingManager(this);
  23829. this.postProcessManager = new BABYLON.PostProcessManager(this);
  23830. if (BABYLON.OutlineRenderer) {
  23831. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  23832. }
  23833. if (BABYLON.Tools.IsWindowObjectExist()) {
  23834. this.attachControl();
  23835. }
  23836. //simplification queue
  23837. if (BABYLON.SimplificationQueue) {
  23838. this.simplificationQueue = new BABYLON.SimplificationQueue();
  23839. }
  23840. //collision coordinator initialization. For now legacy per default.
  23841. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  23842. // Uniform Buffer
  23843. this._createUbo();
  23844. // Default Image processing definition.
  23845. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  23846. }
  23847. Object.defineProperty(Scene, "FOGMODE_NONE", {
  23848. /** The fog is deactivated */
  23849. get: function () {
  23850. return Scene._FOGMODE_NONE;
  23851. },
  23852. enumerable: true,
  23853. configurable: true
  23854. });
  23855. Object.defineProperty(Scene, "FOGMODE_EXP", {
  23856. /** The fog density is following an exponential function */
  23857. get: function () {
  23858. return Scene._FOGMODE_EXP;
  23859. },
  23860. enumerable: true,
  23861. configurable: true
  23862. });
  23863. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  23864. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  23865. get: function () {
  23866. return Scene._FOGMODE_EXP2;
  23867. },
  23868. enumerable: true,
  23869. configurable: true
  23870. });
  23871. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  23872. /** The fog density is following a linear function. */
  23873. get: function () {
  23874. return Scene._FOGMODE_LINEAR;
  23875. },
  23876. enumerable: true,
  23877. configurable: true
  23878. });
  23879. Object.defineProperty(Scene.prototype, "environmentTexture", {
  23880. /**
  23881. * Texture used in all pbr material as the reflection texture.
  23882. * As in the majority of the scene they are the same (exception for multi room and so on),
  23883. * this is easier to reference from here than from all the materials.
  23884. */
  23885. get: function () {
  23886. return this._environmentTexture;
  23887. },
  23888. /**
  23889. * Texture used in all pbr material as the reflection texture.
  23890. * As in the majority of the scene they are the same (exception for multi room and so on),
  23891. * this is easier to set here than in all the materials.
  23892. */
  23893. set: function (value) {
  23894. if (this._environmentTexture === value) {
  23895. return;
  23896. }
  23897. this._environmentTexture = value;
  23898. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  23899. },
  23900. enumerable: true,
  23901. configurable: true
  23902. });
  23903. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  23904. /**
  23905. * Default image processing configuration used either in the rendering
  23906. * Forward main pass or through the imageProcessingPostProcess if present.
  23907. * As in the majority of the scene they are the same (exception for multi camera),
  23908. * this is easier to reference from here than from all the materials and post process.
  23909. *
  23910. * No setter as we it is a shared configuration, you can set the values instead.
  23911. */
  23912. get: function () {
  23913. return this._imageProcessingConfiguration;
  23914. },
  23915. enumerable: true,
  23916. configurable: true
  23917. });
  23918. Object.defineProperty(Scene.prototype, "forceWireframe", {
  23919. get: function () {
  23920. return this._forceWireframe;
  23921. },
  23922. /**
  23923. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  23924. */
  23925. set: function (value) {
  23926. if (this._forceWireframe === value) {
  23927. return;
  23928. }
  23929. this._forceWireframe = value;
  23930. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23931. },
  23932. enumerable: true,
  23933. configurable: true
  23934. });
  23935. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  23936. get: function () {
  23937. return this._forcePointsCloud;
  23938. },
  23939. /**
  23940. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  23941. */
  23942. set: function (value) {
  23943. if (this._forcePointsCloud === value) {
  23944. return;
  23945. }
  23946. this._forcePointsCloud = value;
  23947. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  23953. /**
  23954. * Gets or sets the animation properties override
  23955. */
  23956. get: function () {
  23957. return this._animationPropertiesOverride;
  23958. },
  23959. set: function (value) {
  23960. this._animationPropertiesOverride = value;
  23961. },
  23962. enumerable: true,
  23963. configurable: true
  23964. });
  23965. Object.defineProperty(Scene.prototype, "onDispose", {
  23966. /** Sets a function to be executed when this scene is disposed. */
  23967. set: function (callback) {
  23968. if (this._onDisposeObserver) {
  23969. this.onDisposeObservable.remove(this._onDisposeObserver);
  23970. }
  23971. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23972. },
  23973. enumerable: true,
  23974. configurable: true
  23975. });
  23976. Object.defineProperty(Scene.prototype, "beforeRender", {
  23977. /** Sets a function to be executed before rendering this scene */
  23978. set: function (callback) {
  23979. if (this._onBeforeRenderObserver) {
  23980. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23981. }
  23982. if (callback) {
  23983. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23984. }
  23985. },
  23986. enumerable: true,
  23987. configurable: true
  23988. });
  23989. Object.defineProperty(Scene.prototype, "afterRender", {
  23990. /** Sets a function to be executed after rendering this scene */
  23991. set: function (callback) {
  23992. if (this._onAfterRenderObserver) {
  23993. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23994. }
  23995. if (callback) {
  23996. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23997. }
  23998. },
  23999. enumerable: true,
  24000. configurable: true
  24001. });
  24002. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24003. /** Sets a function to be executed before rendering a camera*/
  24004. set: function (callback) {
  24005. if (this._onBeforeCameraRenderObserver) {
  24006. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24007. }
  24008. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24009. },
  24010. enumerable: true,
  24011. configurable: true
  24012. });
  24013. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24014. /** Sets a function to be executed after rendering a camera*/
  24015. set: function (callback) {
  24016. if (this._onAfterCameraRenderObserver) {
  24017. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24018. }
  24019. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24020. },
  24021. enumerable: true,
  24022. configurable: true
  24023. });
  24024. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24025. /**
  24026. * Gets the gamepad manager associated with the scene
  24027. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24028. */
  24029. get: function () {
  24030. if (!this._gamepadManager) {
  24031. this._gamepadManager = new BABYLON.GamepadManager(this);
  24032. }
  24033. return this._gamepadManager;
  24034. },
  24035. enumerable: true,
  24036. configurable: true
  24037. });
  24038. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24039. /**
  24040. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24041. */
  24042. get: function () {
  24043. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24044. },
  24045. enumerable: true,
  24046. configurable: true
  24047. });
  24048. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24049. get: function () {
  24050. return this._useRightHandedSystem;
  24051. },
  24052. /**
  24053. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24054. */
  24055. set: function (value) {
  24056. if (this._useRightHandedSystem === value) {
  24057. return;
  24058. }
  24059. this._useRightHandedSystem = value;
  24060. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24061. },
  24062. enumerable: true,
  24063. configurable: true
  24064. });
  24065. /**
  24066. * Sets the step Id used by deterministic lock step
  24067. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24068. * @param newStepId defines the step Id
  24069. */
  24070. Scene.prototype.setStepId = function (newStepId) {
  24071. this._currentStepId = newStepId;
  24072. };
  24073. ;
  24074. /**
  24075. * Gets the step Id used by deterministic lock step
  24076. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24077. * @returns the step Id
  24078. */
  24079. Scene.prototype.getStepId = function () {
  24080. return this._currentStepId;
  24081. };
  24082. ;
  24083. /**
  24084. * Gets the internal step used by deterministic lock step
  24085. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24086. * @returns the internal step
  24087. */
  24088. Scene.prototype.getInternalStep = function () {
  24089. return this._currentInternalStep;
  24090. };
  24091. ;
  24092. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24093. get: function () {
  24094. return this._fogEnabled;
  24095. },
  24096. /**
  24097. * Gets or sets a boolean indicating if fog is enabled on this scene
  24098. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24099. */
  24100. set: function (value) {
  24101. if (this._fogEnabled === value) {
  24102. return;
  24103. }
  24104. this._fogEnabled = value;
  24105. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24106. },
  24107. enumerable: true,
  24108. configurable: true
  24109. });
  24110. Object.defineProperty(Scene.prototype, "fogMode", {
  24111. get: function () {
  24112. return this._fogMode;
  24113. },
  24114. /**
  24115. * Gets or sets the fog mode to use
  24116. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24117. */
  24118. set: function (value) {
  24119. if (this._fogMode === value) {
  24120. return;
  24121. }
  24122. this._fogMode = value;
  24123. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24124. },
  24125. enumerable: true,
  24126. configurable: true
  24127. });
  24128. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24129. get: function () {
  24130. return this._shadowsEnabled;
  24131. },
  24132. /**
  24133. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24134. */
  24135. set: function (value) {
  24136. if (this._shadowsEnabled === value) {
  24137. return;
  24138. }
  24139. this._shadowsEnabled = value;
  24140. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24141. },
  24142. enumerable: true,
  24143. configurable: true
  24144. });
  24145. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24146. get: function () {
  24147. return this._lightsEnabled;
  24148. },
  24149. /**
  24150. * Gets or sets a boolean indicating if lights are enabled on this scene
  24151. */
  24152. set: function (value) {
  24153. if (this._lightsEnabled === value) {
  24154. return;
  24155. }
  24156. this._lightsEnabled = value;
  24157. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24158. },
  24159. enumerable: true,
  24160. configurable: true
  24161. });
  24162. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24163. /** The default material used on meshes when no material is affected */
  24164. get: function () {
  24165. if (!this._defaultMaterial) {
  24166. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24167. }
  24168. return this._defaultMaterial;
  24169. },
  24170. /** The default material used on meshes when no material is affected */
  24171. set: function (value) {
  24172. this._defaultMaterial = value;
  24173. },
  24174. enumerable: true,
  24175. configurable: true
  24176. });
  24177. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24178. get: function () {
  24179. return this._texturesEnabled;
  24180. },
  24181. /**
  24182. * Gets or sets a boolean indicating if textures are enabled on this scene
  24183. */
  24184. set: function (value) {
  24185. if (this._texturesEnabled === value) {
  24186. return;
  24187. }
  24188. this._texturesEnabled = value;
  24189. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24195. get: function () {
  24196. return this._skeletonsEnabled;
  24197. },
  24198. /**
  24199. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24200. */
  24201. set: function (value) {
  24202. if (this._skeletonsEnabled === value) {
  24203. return;
  24204. }
  24205. this._skeletonsEnabled = value;
  24206. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24207. },
  24208. enumerable: true,
  24209. configurable: true
  24210. });
  24211. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24212. /**
  24213. * Gets the postprocess render pipeline manager
  24214. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24215. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24216. */
  24217. get: function () {
  24218. if (!this._postProcessRenderPipelineManager) {
  24219. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24220. }
  24221. return this._postProcessRenderPipelineManager;
  24222. },
  24223. enumerable: true,
  24224. configurable: true
  24225. });
  24226. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24227. /**
  24228. * Gets the main soundtrack associated with the scene
  24229. */
  24230. get: function () {
  24231. if (!this._mainSoundTrack) {
  24232. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24233. }
  24234. return this._mainSoundTrack;
  24235. },
  24236. enumerable: true,
  24237. configurable: true
  24238. });
  24239. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24240. /** @ignore */
  24241. get: function () {
  24242. return this._alternateRendering;
  24243. },
  24244. enumerable: true,
  24245. configurable: true
  24246. });
  24247. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24248. /**
  24249. * Gets the list of frustum planes (built from the active camera)
  24250. */
  24251. get: function () {
  24252. return this._frustumPlanes;
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24258. /**
  24259. * Gets the current geometry buffer associated to the scene.
  24260. */
  24261. get: function () {
  24262. return this._geometryBufferRenderer;
  24263. },
  24264. /**
  24265. * Sets the current geometry buffer for the scene.
  24266. */
  24267. set: function (geometryBufferRenderer) {
  24268. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24269. this._geometryBufferRenderer = geometryBufferRenderer;
  24270. }
  24271. },
  24272. enumerable: true,
  24273. configurable: true
  24274. });
  24275. Object.defineProperty(Scene.prototype, "debugLayer", {
  24276. /**
  24277. * Gets the debug layer associated with the scene
  24278. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24279. */
  24280. get: function () {
  24281. if (!this._debugLayer) {
  24282. this._debugLayer = new BABYLON.DebugLayer(this);
  24283. }
  24284. return this._debugLayer;
  24285. },
  24286. enumerable: true,
  24287. configurable: true
  24288. });
  24289. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24290. /**
  24291. * Gets a boolean indicating if collisions are processed on a web worker
  24292. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24293. */
  24294. get: function () {
  24295. return this._workerCollisions;
  24296. },
  24297. set: function (enabled) {
  24298. if (!BABYLON.CollisionCoordinatorLegacy) {
  24299. return;
  24300. }
  24301. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24302. this._workerCollisions = enabled;
  24303. if (this.collisionCoordinator) {
  24304. this.collisionCoordinator.destroy();
  24305. }
  24306. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24307. this.collisionCoordinator.init(this);
  24308. },
  24309. enumerable: true,
  24310. configurable: true
  24311. });
  24312. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24313. /**
  24314. * Gets the octree used to boost mesh selection (picking)
  24315. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24316. */
  24317. get: function () {
  24318. return this._selectionOctree;
  24319. },
  24320. enumerable: true,
  24321. configurable: true
  24322. });
  24323. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24324. /**
  24325. * Gets the mesh that is currently under the pointer
  24326. */
  24327. get: function () {
  24328. return this._pointerOverMesh;
  24329. },
  24330. enumerable: true,
  24331. configurable: true
  24332. });
  24333. Object.defineProperty(Scene.prototype, "pointerX", {
  24334. /**
  24335. * Gets the current on-screen X position of the pointer
  24336. */
  24337. get: function () {
  24338. return this._pointerX;
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. Object.defineProperty(Scene.prototype, "pointerY", {
  24344. /**
  24345. * Gets the current on-screen Y position of the pointer
  24346. */
  24347. get: function () {
  24348. return this._pointerY;
  24349. },
  24350. enumerable: true,
  24351. configurable: true
  24352. });
  24353. /**
  24354. * Gets the cached material (ie. the latest rendered one)
  24355. * @returns the cached material
  24356. */
  24357. Scene.prototype.getCachedMaterial = function () {
  24358. return this._cachedMaterial;
  24359. };
  24360. /**
  24361. * Gets the cached effect (ie. the latest rendered one)
  24362. * @returns the cached effect
  24363. */
  24364. Scene.prototype.getCachedEffect = function () {
  24365. return this._cachedEffect;
  24366. };
  24367. /**
  24368. * Gets the cached visibility state (ie. the latest rendered one)
  24369. * @returns the cached visibility state
  24370. */
  24371. Scene.prototype.getCachedVisibility = function () {
  24372. return this._cachedVisibility;
  24373. };
  24374. /**
  24375. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24376. * @param material defines the current material
  24377. * @param effect defines the current effect
  24378. * @param visibility defines the current visibility state
  24379. * @returns true if one parameter is not cached
  24380. */
  24381. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24382. if (visibility === void 0) { visibility = 1; }
  24383. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24384. };
  24385. /**
  24386. * Gets the bounding box renderer associated with the scene
  24387. * @returns a BoundingBoxRenderer
  24388. */
  24389. Scene.prototype.getBoundingBoxRenderer = function () {
  24390. if (!this._boundingBoxRenderer) {
  24391. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24392. }
  24393. return this._boundingBoxRenderer;
  24394. };
  24395. /**
  24396. * Gets the outline renderer associated with the scene
  24397. * @returns a OutlineRenderer
  24398. */
  24399. Scene.prototype.getOutlineRenderer = function () {
  24400. return this._outlineRenderer;
  24401. };
  24402. /**
  24403. * Gets the engine associated with the scene
  24404. * @returns an Engine
  24405. */
  24406. Scene.prototype.getEngine = function () {
  24407. return this._engine;
  24408. };
  24409. /**
  24410. * Gets the total number of vertices rendered per frame
  24411. * @returns the total number of vertices rendered per frame
  24412. */
  24413. Scene.prototype.getTotalVertices = function () {
  24414. return this._totalVertices.current;
  24415. };
  24416. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24417. /**
  24418. * Gets the performance counter for total vertices
  24419. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24420. */
  24421. get: function () {
  24422. return this._totalVertices;
  24423. },
  24424. enumerable: true,
  24425. configurable: true
  24426. });
  24427. /**
  24428. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24429. * @returns the total number of active indices rendered per frame
  24430. */
  24431. Scene.prototype.getActiveIndices = function () {
  24432. return this._activeIndices.current;
  24433. };
  24434. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24435. /**
  24436. * Gets the performance counter for active indices
  24437. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24438. */
  24439. get: function () {
  24440. return this._activeIndices;
  24441. },
  24442. enumerable: true,
  24443. configurable: true
  24444. });
  24445. /**
  24446. * Gets the total number of active particles rendered per frame
  24447. * @returns the total number of active particles rendered per frame
  24448. */
  24449. Scene.prototype.getActiveParticles = function () {
  24450. return this._activeParticles.current;
  24451. };
  24452. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24453. /**
  24454. * Gets the performance counter for active particles
  24455. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24456. */
  24457. get: function () {
  24458. return this._activeParticles;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. /**
  24464. * Gets the total number of active bones rendered per frame
  24465. * @returns the total number of active bones rendered per frame
  24466. */
  24467. Scene.prototype.getActiveBones = function () {
  24468. return this._activeBones.current;
  24469. };
  24470. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24471. /**
  24472. * Gets the performance counter for active bones
  24473. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24474. */
  24475. get: function () {
  24476. return this._activeBones;
  24477. },
  24478. enumerable: true,
  24479. configurable: true
  24480. });
  24481. /** @ignore */
  24482. Scene.prototype.getInterFramePerfCounter = function () {
  24483. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24484. return 0;
  24485. };
  24486. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24487. /** @ignore */
  24488. get: function () {
  24489. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24490. return null;
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. /** @ignore */
  24496. Scene.prototype.getLastFrameDuration = function () {
  24497. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24498. return 0;
  24499. };
  24500. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24501. /** @ignore */
  24502. get: function () {
  24503. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24504. return null;
  24505. },
  24506. enumerable: true,
  24507. configurable: true
  24508. });
  24509. /** @ignore */
  24510. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24511. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24512. return 0;
  24513. };
  24514. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24515. /** @ignore */
  24516. get: function () {
  24517. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24518. return null;
  24519. },
  24520. enumerable: true,
  24521. configurable: true
  24522. });
  24523. /**
  24524. * Gets the array of active meshes
  24525. * @returns an array of AbstractMesh
  24526. */
  24527. Scene.prototype.getActiveMeshes = function () {
  24528. return this._activeMeshes;
  24529. };
  24530. /** @ignore */
  24531. Scene.prototype.getRenderTargetsDuration = function () {
  24532. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24533. return 0;
  24534. };
  24535. /** @ignore */
  24536. Scene.prototype.getRenderDuration = function () {
  24537. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24538. return 0;
  24539. };
  24540. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24541. /** @ignore */
  24542. get: function () {
  24543. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24544. return null;
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. /** @ignore */
  24550. Scene.prototype.getParticlesDuration = function () {
  24551. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24552. return 0;
  24553. };
  24554. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24555. /** @ignore */
  24556. get: function () {
  24557. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24558. return null;
  24559. },
  24560. enumerable: true,
  24561. configurable: true
  24562. });
  24563. /** @ignore */
  24564. Scene.prototype.getSpritesDuration = function () {
  24565. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24566. return 0;
  24567. };
  24568. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24569. /** @ignore */
  24570. get: function () {
  24571. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24572. return null;
  24573. },
  24574. enumerable: true,
  24575. configurable: true
  24576. });
  24577. /**
  24578. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24579. * @returns a number
  24580. */
  24581. Scene.prototype.getAnimationRatio = function () {
  24582. return this._animationRatio;
  24583. };
  24584. /**
  24585. * Gets an unique Id for the current frame
  24586. * @returns a number
  24587. */
  24588. Scene.prototype.getRenderId = function () {
  24589. return this._renderId;
  24590. };
  24591. /** Call this function if you want to manually increment the render Id*/
  24592. Scene.prototype.incrementRenderId = function () {
  24593. this._renderId++;
  24594. };
  24595. Scene.prototype._updatePointerPosition = function (evt) {
  24596. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24597. if (!canvasRect) {
  24598. return;
  24599. }
  24600. this._pointerX = evt.clientX - canvasRect.left;
  24601. this._pointerY = evt.clientY - canvasRect.top;
  24602. this._unTranslatedPointerX = this._pointerX;
  24603. this._unTranslatedPointerY = this._pointerY;
  24604. };
  24605. Scene.prototype._createUbo = function () {
  24606. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24607. this._sceneUbo.addUniform("viewProjection", 16);
  24608. this._sceneUbo.addUniform("view", 16);
  24609. };
  24610. Scene.prototype._createAlternateUbo = function () {
  24611. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24612. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24613. this._alternateSceneUbo.addUniform("view", 16);
  24614. };
  24615. // Pointers handling
  24616. /**
  24617. * Use this method to simulate a pointer move on a mesh
  24618. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24619. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24620. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24621. * @returns the current scene
  24622. */
  24623. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24624. var evt = new PointerEvent("pointermove", pointerEventInit);
  24625. return this._processPointerMove(pickResult, evt);
  24626. };
  24627. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24628. var canvas = this._engine.getRenderingCanvas();
  24629. if (!canvas) {
  24630. return this;
  24631. }
  24632. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24633. this.setPointerOverSprite(null);
  24634. this.setPointerOverMesh(pickResult.pickedMesh);
  24635. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24636. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24637. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24638. }
  24639. else {
  24640. canvas.style.cursor = this.hoverCursor;
  24641. }
  24642. }
  24643. else {
  24644. canvas.style.cursor = this.defaultCursor;
  24645. }
  24646. }
  24647. else {
  24648. this.setPointerOverMesh(null);
  24649. // Sprites
  24650. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24651. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24652. this.setPointerOverSprite(pickResult.pickedSprite);
  24653. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24654. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24655. }
  24656. else {
  24657. canvas.style.cursor = this.hoverCursor;
  24658. }
  24659. }
  24660. else {
  24661. this.setPointerOverSprite(null);
  24662. // Restore pointer
  24663. canvas.style.cursor = this.defaultCursor;
  24664. }
  24665. }
  24666. if (pickResult) {
  24667. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24668. if (this.onPointerMove) {
  24669. this.onPointerMove(evt, pickResult, type);
  24670. }
  24671. if (this.onPointerObservable.hasObservers()) {
  24672. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24673. this.onPointerObservable.notifyObservers(pi, type);
  24674. }
  24675. }
  24676. return this;
  24677. };
  24678. /**
  24679. * Use this method to simulate a pointer down on a mesh
  24680. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24681. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24682. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24683. * @returns the current scene
  24684. */
  24685. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24686. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24687. return this._processPointerDown(pickResult, evt);
  24688. };
  24689. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24690. var _this = this;
  24691. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24692. this._pickedDownMesh = pickResult.pickedMesh;
  24693. var actionManager = pickResult.pickedMesh.actionManager;
  24694. if (actionManager) {
  24695. if (actionManager.hasPickTriggers) {
  24696. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24697. switch (evt.button) {
  24698. case 0:
  24699. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24700. break;
  24701. case 1:
  24702. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24703. break;
  24704. case 2:
  24705. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24706. break;
  24707. }
  24708. }
  24709. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24710. window.setTimeout(function () {
  24711. 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);
  24712. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24713. if (_this._totalPointersPressed !== 0 &&
  24714. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24715. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24716. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24717. _this._startingPointerTime = 0;
  24718. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24719. }
  24720. }
  24721. }, Scene.LongPressDelay);
  24722. }
  24723. }
  24724. }
  24725. if (pickResult) {
  24726. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24727. if (this.onPointerDown) {
  24728. this.onPointerDown(evt, pickResult, type);
  24729. }
  24730. if (this.onPointerObservable.hasObservers()) {
  24731. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24732. this.onPointerObservable.notifyObservers(pi, type);
  24733. }
  24734. }
  24735. return this;
  24736. };
  24737. /**
  24738. * Use this method to simulate a pointer up on a mesh
  24739. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24740. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24741. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24742. * @returns the current scene
  24743. */
  24744. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24745. var evt = new PointerEvent("pointerup", pointerEventInit);
  24746. var clickInfo = new ClickInfo();
  24747. clickInfo.singleClick = true;
  24748. clickInfo.ignore = true;
  24749. return this._processPointerUp(pickResult, evt, clickInfo);
  24750. };
  24751. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24752. if (pickResult && pickResult && pickResult.pickedMesh) {
  24753. this._pickedUpMesh = pickResult.pickedMesh;
  24754. if (this._pickedDownMesh === this._pickedUpMesh) {
  24755. if (this.onPointerPick) {
  24756. this.onPointerPick(evt, pickResult);
  24757. }
  24758. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24759. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24760. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24761. this.onPointerObservable.notifyObservers(pi, type_1);
  24762. }
  24763. }
  24764. if (pickResult.pickedMesh.actionManager) {
  24765. if (clickInfo.ignore) {
  24766. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24767. }
  24768. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24769. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24770. }
  24771. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24772. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24773. }
  24774. }
  24775. }
  24776. if (this._pickedDownMesh &&
  24777. this._pickedDownMesh.actionManager &&
  24778. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24779. this._pickedDownMesh !== this._pickedUpMesh) {
  24780. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24781. }
  24782. var type = BABYLON.PointerEventTypes.POINTERUP;
  24783. if (this.onPointerObservable.hasObservers()) {
  24784. if (!clickInfo.ignore) {
  24785. if (!clickInfo.hasSwiped) {
  24786. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24787. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24788. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24789. this.onPointerObservable.notifyObservers(pi, type_2);
  24790. }
  24791. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24792. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24793. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24794. this.onPointerObservable.notifyObservers(pi, type_3);
  24795. }
  24796. }
  24797. }
  24798. else {
  24799. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24800. this.onPointerObservable.notifyObservers(pi, type);
  24801. }
  24802. }
  24803. if (this.onPointerUp) {
  24804. this.onPointerUp(evt, pickResult, type);
  24805. }
  24806. return this;
  24807. };
  24808. /**
  24809. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24810. * @param attachUp defines if you want to attach events to pointerup
  24811. * @param attachDown defines if you want to attach events to pointerdown
  24812. * @param attachMove defines if you want to attach events to pointermove
  24813. */
  24814. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24815. var _this = this;
  24816. if (attachUp === void 0) { attachUp = true; }
  24817. if (attachDown === void 0) { attachDown = true; }
  24818. if (attachMove === void 0) { attachMove = true; }
  24819. this._initActionManager = function (act, clickInfo) {
  24820. if (!_this._meshPickProceed) {
  24821. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24822. _this._currentPickResult = pickResult;
  24823. if (pickResult) {
  24824. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24825. }
  24826. _this._meshPickProceed = true;
  24827. }
  24828. return act;
  24829. };
  24830. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  24831. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  24832. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  24833. btn !== _this._previousButtonPressed) {
  24834. _this._doubleClickOccured = false;
  24835. clickInfo.singleClick = true;
  24836. clickInfo.ignore = false;
  24837. cb(clickInfo, _this._currentPickResult);
  24838. }
  24839. };
  24840. this._initClickEvent = function (obs1, obs2, evt, cb) {
  24841. var clickInfo = new ClickInfo();
  24842. _this._currentPickResult = null;
  24843. var act = null;
  24844. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  24845. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  24846. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24847. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  24848. act = _this._initActionManager(act, clickInfo);
  24849. if (act)
  24850. checkPicking = act.hasPickTriggers;
  24851. }
  24852. if (checkPicking) {
  24853. var btn = evt.button;
  24854. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  24855. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  24856. if (!clickInfo.hasSwiped) {
  24857. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  24858. if (!checkSingleClickImmediately) {
  24859. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  24860. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24861. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24862. act = _this._initActionManager(act, clickInfo);
  24863. if (act)
  24864. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24865. }
  24866. }
  24867. if (checkSingleClickImmediately) {
  24868. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  24869. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  24870. btn !== _this._previousButtonPressed) {
  24871. clickInfo.singleClick = true;
  24872. cb(clickInfo, _this._currentPickResult);
  24873. }
  24874. }
  24875. // at least one double click is required to be check and exclusive double click is enabled
  24876. else {
  24877. // wait that no double click has been raised during the double click delay
  24878. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24879. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  24880. }
  24881. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  24882. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  24883. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24884. act = _this._initActionManager(act, clickInfo);
  24885. if (act)
  24886. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  24887. }
  24888. if (checkDoubleClick) {
  24889. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  24890. if (btn === _this._previousButtonPressed &&
  24891. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  24892. !_this._doubleClickOccured) {
  24893. // pointer has not moved for 2 clicks, it's a double click
  24894. if (!clickInfo.hasSwiped &&
  24895. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  24896. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  24897. _this._previousStartingPointerTime = 0;
  24898. _this._doubleClickOccured = true;
  24899. clickInfo.doubleClick = true;
  24900. clickInfo.ignore = false;
  24901. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  24902. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24903. }
  24904. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24905. cb(clickInfo, _this._currentPickResult);
  24906. }
  24907. // if the two successive clicks are too far, it's just two simple clicks
  24908. else {
  24909. _this._doubleClickOccured = false;
  24910. _this._previousStartingPointerTime = _this._startingPointerTime;
  24911. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24912. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24913. _this._previousButtonPressed = btn;
  24914. if (Scene.ExclusiveDoubleClickMode) {
  24915. if (_this._previousDelayedSimpleClickTimeout) {
  24916. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  24917. }
  24918. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  24919. cb(clickInfo, _this._previousPickResult);
  24920. }
  24921. else {
  24922. cb(clickInfo, _this._currentPickResult);
  24923. }
  24924. }
  24925. }
  24926. // just the first click of the double has been raised
  24927. else {
  24928. _this._doubleClickOccured = false;
  24929. _this._previousStartingPointerTime = _this._startingPointerTime;
  24930. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  24931. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  24932. _this._previousButtonPressed = btn;
  24933. }
  24934. }
  24935. }
  24936. }
  24937. clickInfo.ignore = true;
  24938. cb(clickInfo, _this._currentPickResult);
  24939. };
  24940. this._spritePredicate = function (sprite) {
  24941. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  24942. };
  24943. this._onPointerMove = function (evt) {
  24944. _this._updatePointerPosition(evt);
  24945. // PreObservable support
  24946. if (_this.onPrePointerObservable.hasObservers()) {
  24947. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24948. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24949. _this.onPrePointerObservable.notifyObservers(pi, type);
  24950. if (pi.skipOnPointerObservable) {
  24951. return;
  24952. }
  24953. }
  24954. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24955. return;
  24956. }
  24957. if (!_this.pointerMovePredicate) {
  24958. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  24959. }
  24960. // Meshes
  24961. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  24962. _this._processPointerMove(pickResult, evt);
  24963. };
  24964. this._onPointerDown = function (evt) {
  24965. _this._totalPointersPressed++;
  24966. _this._pickedDownMesh = null;
  24967. _this._meshPickProceed = false;
  24968. _this._updatePointerPosition(evt);
  24969. if (_this.preventDefaultOnPointerDown && canvas) {
  24970. evt.preventDefault();
  24971. canvas.focus();
  24972. }
  24973. // PreObservable support
  24974. if (_this.onPrePointerObservable.hasObservers()) {
  24975. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24976. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  24977. _this.onPrePointerObservable.notifyObservers(pi, type);
  24978. if (pi.skipOnPointerObservable) {
  24979. return;
  24980. }
  24981. }
  24982. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  24983. return;
  24984. }
  24985. _this._startingPointerPosition.x = _this._pointerX;
  24986. _this._startingPointerPosition.y = _this._pointerY;
  24987. _this._startingPointerTime = Date.now();
  24988. if (!_this.pointerDownPredicate) {
  24989. _this.pointerDownPredicate = function (mesh) {
  24990. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  24991. };
  24992. }
  24993. // Meshes
  24994. _this._pickedDownMesh = null;
  24995. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24996. _this._processPointerDown(pickResult, evt);
  24997. // Sprites
  24998. _this._pickedDownSprite = null;
  24999. if (_this.spriteManagers.length > 0) {
  25000. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25001. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25002. if (pickResult.pickedSprite.actionManager) {
  25003. _this._pickedDownSprite = pickResult.pickedSprite;
  25004. switch (evt.button) {
  25005. case 0:
  25006. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25007. break;
  25008. case 1:
  25009. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25010. break;
  25011. case 2:
  25012. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25013. break;
  25014. }
  25015. if (pickResult.pickedSprite.actionManager) {
  25016. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25017. }
  25018. }
  25019. }
  25020. }
  25021. };
  25022. this._onPointerUp = function (evt) {
  25023. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25024. return; // So we need to test it the pointer down was pressed before.
  25025. }
  25026. _this._totalPointersPressed--;
  25027. _this._pickedUpMesh = null;
  25028. _this._meshPickProceed = false;
  25029. _this._updatePointerPosition(evt);
  25030. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25031. // PreObservable support
  25032. if (_this.onPrePointerObservable.hasObservers()) {
  25033. if (!clickInfo.ignore) {
  25034. if (!clickInfo.hasSwiped) {
  25035. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25036. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25037. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25038. _this.onPrePointerObservable.notifyObservers(pi, type);
  25039. if (pi.skipOnPointerObservable) {
  25040. return;
  25041. }
  25042. }
  25043. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25044. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25045. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25046. _this.onPrePointerObservable.notifyObservers(pi, type);
  25047. if (pi.skipOnPointerObservable) {
  25048. return;
  25049. }
  25050. }
  25051. }
  25052. }
  25053. else {
  25054. var type = BABYLON.PointerEventTypes.POINTERUP;
  25055. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25056. _this.onPrePointerObservable.notifyObservers(pi, type);
  25057. if (pi.skipOnPointerObservable) {
  25058. return;
  25059. }
  25060. }
  25061. }
  25062. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25063. return;
  25064. }
  25065. if (!_this.pointerUpPredicate) {
  25066. _this.pointerUpPredicate = function (mesh) {
  25067. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25068. };
  25069. }
  25070. // Meshes
  25071. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25072. _this._initActionManager(null, clickInfo);
  25073. }
  25074. if (!pickResult) {
  25075. pickResult = _this._currentPickResult;
  25076. }
  25077. _this._processPointerUp(pickResult, evt, clickInfo);
  25078. // Sprites
  25079. if (_this.spriteManagers.length > 0) {
  25080. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25081. if (spritePickResult) {
  25082. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25083. if (spritePickResult.pickedSprite.actionManager) {
  25084. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25085. if (spritePickResult.pickedSprite.actionManager) {
  25086. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25087. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25088. }
  25089. }
  25090. }
  25091. }
  25092. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25093. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25094. }
  25095. }
  25096. }
  25097. _this._previousPickResult = _this._currentPickResult;
  25098. });
  25099. };
  25100. this._onKeyDown = function (evt) {
  25101. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25102. if (_this.onPreKeyboardObservable.hasObservers()) {
  25103. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25104. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25105. if (pi.skipOnPointerObservable) {
  25106. return;
  25107. }
  25108. }
  25109. if (_this.onKeyboardObservable.hasObservers()) {
  25110. var pi = new BABYLON.KeyboardInfo(type, evt);
  25111. _this.onKeyboardObservable.notifyObservers(pi, type);
  25112. }
  25113. if (_this.actionManager) {
  25114. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25115. }
  25116. };
  25117. this._onKeyUp = function (evt) {
  25118. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25119. if (_this.onPreKeyboardObservable.hasObservers()) {
  25120. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25121. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25122. if (pi.skipOnPointerObservable) {
  25123. return;
  25124. }
  25125. }
  25126. if (_this.onKeyboardObservable.hasObservers()) {
  25127. var pi = new BABYLON.KeyboardInfo(type, evt);
  25128. _this.onKeyboardObservable.notifyObservers(pi, type);
  25129. }
  25130. if (_this.actionManager) {
  25131. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25132. }
  25133. };
  25134. var engine = this.getEngine();
  25135. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25136. if (!canvas) {
  25137. return;
  25138. }
  25139. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25140. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25141. });
  25142. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25143. if (!canvas) {
  25144. return;
  25145. }
  25146. canvas.removeEventListener("keydown", _this._onKeyDown);
  25147. canvas.removeEventListener("keyup", _this._onKeyUp);
  25148. });
  25149. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25150. var canvas = this._engine.getRenderingCanvas();
  25151. if (!canvas) {
  25152. return;
  25153. }
  25154. if (attachMove) {
  25155. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25156. // Wheel
  25157. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25158. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25159. }
  25160. if (attachDown) {
  25161. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25162. }
  25163. if (attachUp) {
  25164. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25165. }
  25166. canvas.tabIndex = 1;
  25167. };
  25168. /** Detaches all event handlers*/
  25169. Scene.prototype.detachControl = function () {
  25170. var engine = this.getEngine();
  25171. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25172. var canvas = engine.getRenderingCanvas();
  25173. if (!canvas) {
  25174. return;
  25175. }
  25176. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25177. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25178. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25179. if (this._onCanvasBlurObserver) {
  25180. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25181. }
  25182. if (this._onCanvasFocusObserver) {
  25183. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25184. }
  25185. // Wheel
  25186. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25187. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25188. // Keyboard
  25189. canvas.removeEventListener("keydown", this._onKeyDown);
  25190. canvas.removeEventListener("keyup", this._onKeyUp);
  25191. // Observables
  25192. this.onKeyboardObservable.clear();
  25193. this.onPreKeyboardObservable.clear();
  25194. this.onPointerObservable.clear();
  25195. this.onPrePointerObservable.clear();
  25196. };
  25197. /**
  25198. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25199. * Delay loaded resources are not taking in account
  25200. * @return true if all required resources are ready
  25201. */
  25202. Scene.prototype.isReady = function () {
  25203. if (this._isDisposed) {
  25204. return false;
  25205. }
  25206. if (this._pendingData.length > 0) {
  25207. return false;
  25208. }
  25209. var index;
  25210. var engine = this.getEngine();
  25211. // Geometries
  25212. for (index = 0; index < this._geometries.length; index++) {
  25213. var geometry = this._geometries[index];
  25214. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25215. return false;
  25216. }
  25217. }
  25218. // Meshes
  25219. for (index = 0; index < this.meshes.length; index++) {
  25220. var mesh = this.meshes[index];
  25221. if (!mesh.isEnabled()) {
  25222. continue;
  25223. }
  25224. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25225. continue;
  25226. }
  25227. if (!mesh.isReady(true)) {
  25228. return false;
  25229. }
  25230. // Effect layers
  25231. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25232. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25233. var layer = _a[_i];
  25234. if (!layer.hasMesh(mesh)) {
  25235. continue;
  25236. }
  25237. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25238. var subMesh = _c[_b];
  25239. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25240. return false;
  25241. }
  25242. }
  25243. }
  25244. }
  25245. // Post-processes
  25246. if (this.activeCameras && this.activeCameras.length > 0) {
  25247. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25248. var camera = _e[_d];
  25249. if (!camera.isReady(true)) {
  25250. return false;
  25251. }
  25252. }
  25253. }
  25254. else if (this.activeCamera) {
  25255. if (!this.activeCamera.isReady(true)) {
  25256. return false;
  25257. }
  25258. }
  25259. // Particles
  25260. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25261. var particleSystem = _g[_f];
  25262. if (!particleSystem.isReady()) {
  25263. return false;
  25264. }
  25265. }
  25266. return true;
  25267. };
  25268. /** Resets all cached information relative to material (including effect and visibility) */
  25269. Scene.prototype.resetCachedMaterial = function () {
  25270. this._cachedMaterial = null;
  25271. this._cachedEffect = null;
  25272. this._cachedVisibility = null;
  25273. };
  25274. /**
  25275. * Registers a function to be called before every frame render
  25276. * @param func defines the function to register
  25277. */
  25278. Scene.prototype.registerBeforeRender = function (func) {
  25279. this.onBeforeRenderObservable.add(func);
  25280. };
  25281. /**
  25282. * Unregisters a function called before every frame render
  25283. * @param func defines the function to unregister
  25284. */
  25285. Scene.prototype.unregisterBeforeRender = function (func) {
  25286. this.onBeforeRenderObservable.removeCallback(func);
  25287. };
  25288. /**
  25289. * Registers a function to be called after every frame render
  25290. * @param func defines the function to register
  25291. */
  25292. Scene.prototype.registerAfterRender = function (func) {
  25293. this.onAfterRenderObservable.add(func);
  25294. };
  25295. /**
  25296. * Unregisters a function called after every frame render
  25297. * @param func defines the function to unregister
  25298. */
  25299. Scene.prototype.unregisterAfterRender = function (func) {
  25300. this.onAfterRenderObservable.removeCallback(func);
  25301. };
  25302. Scene.prototype._executeOnceBeforeRender = function (func) {
  25303. var _this = this;
  25304. var execFunc = function () {
  25305. func();
  25306. setTimeout(function () {
  25307. _this.unregisterBeforeRender(execFunc);
  25308. });
  25309. };
  25310. this.registerBeforeRender(execFunc);
  25311. };
  25312. /**
  25313. * The provided function will run before render once and will be disposed afterwards.
  25314. * A timeout delay can be provided so that the function will be executed in N ms.
  25315. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25316. * @param func The function to be executed.
  25317. * @param timeout optional delay in ms
  25318. */
  25319. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25320. var _this = this;
  25321. if (timeout !== undefined) {
  25322. setTimeout(function () {
  25323. _this._executeOnceBeforeRender(func);
  25324. }, timeout);
  25325. }
  25326. else {
  25327. this._executeOnceBeforeRender(func);
  25328. }
  25329. };
  25330. /** @ignore */
  25331. Scene.prototype._addPendingData = function (data) {
  25332. this._pendingData.push(data);
  25333. };
  25334. /** @ignore */
  25335. Scene.prototype._removePendingData = function (data) {
  25336. var wasLoading = this.isLoading;
  25337. var index = this._pendingData.indexOf(data);
  25338. if (index !== -1) {
  25339. this._pendingData.splice(index, 1);
  25340. }
  25341. if (wasLoading && !this.isLoading) {
  25342. this.onDataLoadedObservable.notifyObservers(this);
  25343. }
  25344. };
  25345. /**
  25346. * Returns the number of items waiting to be loaded
  25347. * @returns the number of items waiting to be loaded
  25348. */
  25349. Scene.prototype.getWaitingItemsCount = function () {
  25350. return this._pendingData.length;
  25351. };
  25352. Object.defineProperty(Scene.prototype, "isLoading", {
  25353. /**
  25354. * Returns a boolean indicating if the scene is still loading data
  25355. */
  25356. get: function () {
  25357. return this._pendingData.length > 0;
  25358. },
  25359. enumerable: true,
  25360. configurable: true
  25361. });
  25362. /**
  25363. * Registers a function to be executed when the scene is ready
  25364. * @param {Function} func - the function to be executed
  25365. */
  25366. Scene.prototype.executeWhenReady = function (func) {
  25367. var _this = this;
  25368. this.onReadyObservable.add(func);
  25369. if (this._executeWhenReadyTimeoutId !== -1) {
  25370. return;
  25371. }
  25372. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25373. _this._checkIsReady();
  25374. }, 150);
  25375. };
  25376. /**
  25377. * Returns a promise that resolves when the scene is ready
  25378. * @returns A promise that resolves when the scene is ready
  25379. */
  25380. Scene.prototype.whenReadyAsync = function () {
  25381. var _this = this;
  25382. return new Promise(function (resolve) {
  25383. _this.executeWhenReady(function () {
  25384. resolve();
  25385. });
  25386. });
  25387. };
  25388. /** @ignore */
  25389. Scene.prototype._checkIsReady = function () {
  25390. var _this = this;
  25391. if (this.isReady()) {
  25392. this.onReadyObservable.notifyObservers(this);
  25393. this.onReadyObservable.clear();
  25394. this._executeWhenReadyTimeoutId = -1;
  25395. return;
  25396. }
  25397. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25398. _this._checkIsReady();
  25399. }, 150);
  25400. };
  25401. // Animations
  25402. /**
  25403. * Will start the animation sequence of a given target
  25404. * @param target defines the target
  25405. * @param from defines from which frame should animation start
  25406. * @param to defines until which frame should animation run.
  25407. * @param weight defines the weight to apply to the animation (1.0 by default)
  25408. * @param loop defines if the animation loops
  25409. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25410. * @param onAnimationEnd defines the function to be executed when the animation ends
  25411. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25412. * @returns the animatable object created for this animation
  25413. */
  25414. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25415. if (weight === void 0) { weight = 1.0; }
  25416. if (speedRatio === void 0) { speedRatio = 1.0; }
  25417. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25418. returnedAnimatable.weight = weight;
  25419. return returnedAnimatable;
  25420. };
  25421. /**
  25422. * Will start the animation sequence of a given target
  25423. * @param target defines the target
  25424. * @param from defines from which frame should animation start
  25425. * @param to defines until which frame should animation run.
  25426. * @param loop defines if the animation loops
  25427. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25428. * @param onAnimationEnd defines the function to be executed when the animation ends
  25429. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25430. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25431. * @returns the animatable object created for this animation
  25432. */
  25433. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25434. if (speedRatio === void 0) { speedRatio = 1.0; }
  25435. if (stopCurrent === void 0) { stopCurrent = true; }
  25436. if (from > to && speedRatio > 0) {
  25437. speedRatio *= -1;
  25438. }
  25439. if (stopCurrent) {
  25440. this.stopAnimation(target);
  25441. }
  25442. if (!animatable) {
  25443. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25444. }
  25445. // Local animations
  25446. if (target.animations) {
  25447. animatable.appendAnimations(target, target.animations);
  25448. }
  25449. // Children animations
  25450. if (target.getAnimatables) {
  25451. var animatables = target.getAnimatables();
  25452. for (var index = 0; index < animatables.length; index++) {
  25453. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25454. }
  25455. }
  25456. animatable.reset();
  25457. return animatable;
  25458. };
  25459. /**
  25460. * Begin a new animation on a given node
  25461. * @param target defines the target where the animation will take place
  25462. * @param animations defines the list of animations to start
  25463. * @param from defines the initial value
  25464. * @param to defines the final value
  25465. * @param loop defines if you want animation to loop (off by default)
  25466. * @param speedRatio defines the speed ratio to apply to all animations
  25467. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25468. * @returns the list of created animatables
  25469. */
  25470. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25471. if (speedRatio === undefined) {
  25472. speedRatio = 1.0;
  25473. }
  25474. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25475. return animatable;
  25476. };
  25477. /**
  25478. * Begin a new animation on a given node and its hierarchy
  25479. * @param target defines the root node where the animation will take place
  25480. * @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.
  25481. * @param animations defines the list of animations to start
  25482. * @param from defines the initial value
  25483. * @param to defines the final value
  25484. * @param loop defines if you want animation to loop (off by default)
  25485. * @param speedRatio defines the speed ratio to apply to all animations
  25486. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25487. * @returns the list of animatables created for all nodes
  25488. */
  25489. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25490. var children = target.getDescendants(directDescendantsOnly);
  25491. var result = [];
  25492. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25493. var child = children_1[_i];
  25494. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25495. }
  25496. return result;
  25497. };
  25498. /**
  25499. * Gets the animatable associated with a specific target
  25500. * @param target defines the target of the animatable
  25501. * @returns the required animatable if found
  25502. */
  25503. Scene.prototype.getAnimatableByTarget = function (target) {
  25504. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25505. if (this._activeAnimatables[index].target === target) {
  25506. return this._activeAnimatables[index];
  25507. }
  25508. }
  25509. return null;
  25510. };
  25511. /**
  25512. * Gets all animatables associated with a given target
  25513. * @param target defines the target to look animatables for
  25514. * @returns an array of Animatables
  25515. */
  25516. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25517. var result = [];
  25518. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25519. if (this._activeAnimatables[index].target === target) {
  25520. result.push(this._activeAnimatables[index]);
  25521. }
  25522. }
  25523. return result;
  25524. };
  25525. Object.defineProperty(Scene.prototype, "animatables", {
  25526. /**
  25527. * Gets all animatable attached to the scene
  25528. */
  25529. get: function () {
  25530. return this._activeAnimatables;
  25531. },
  25532. enumerable: true,
  25533. configurable: true
  25534. });
  25535. /**
  25536. * Will stop the animation of the given target
  25537. * @param target - the target
  25538. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25539. */
  25540. Scene.prototype.stopAnimation = function (target, animationName) {
  25541. var animatables = this.getAllAnimatablesByTarget(target);
  25542. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25543. var animatable = animatables_1[_i];
  25544. animatable.stop(animationName);
  25545. }
  25546. };
  25547. /**
  25548. * Stops and removes all animations that have been applied to the scene
  25549. */
  25550. Scene.prototype.stopAllAnimations = function () {
  25551. if (this._activeAnimatables) {
  25552. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25553. this._activeAnimatables[i].stop();
  25554. }
  25555. this._activeAnimatables = [];
  25556. }
  25557. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25558. var group = _a[_i];
  25559. group.stop();
  25560. }
  25561. };
  25562. Scene.prototype._animate = function () {
  25563. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25564. return;
  25565. }
  25566. // Getting time
  25567. var now = BABYLON.Tools.Now;
  25568. if (!this._animationTimeLast) {
  25569. if (this._pendingData.length > 0) {
  25570. return;
  25571. }
  25572. this._animationTimeLast = now;
  25573. }
  25574. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25575. this._animationTime += deltaTime;
  25576. this._animationTimeLast = now;
  25577. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25578. this._activeAnimatables[index]._animate(this._animationTime);
  25579. }
  25580. // Late animation bindings
  25581. this._processLateAnimationBindings();
  25582. };
  25583. /** @ignore */
  25584. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25585. var target = runtimeAnimation.target;
  25586. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25587. if (!target._lateAnimationHolders) {
  25588. target._lateAnimationHolders = {};
  25589. }
  25590. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25591. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25592. totalWeight: 0,
  25593. animations: []
  25594. };
  25595. }
  25596. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25597. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25598. };
  25599. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25600. var normalizer = 1.0;
  25601. var finalPosition = BABYLON.Tmp.Vector3[0];
  25602. var finalScaling = BABYLON.Tmp.Vector3[1];
  25603. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25604. var startIndex = 0;
  25605. var originalAnimation = holder.animations[0];
  25606. var scale = 1;
  25607. if (holder.totalWeight < 1.0) {
  25608. // We need to mix the original value in
  25609. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25610. scale = 1.0 - holder.totalWeight;
  25611. }
  25612. else {
  25613. startIndex = 1;
  25614. // We need to normalize the weights
  25615. normalizer = holder.totalWeight;
  25616. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25617. scale = originalAnimation.weight / normalizer;
  25618. if (scale == 1) {
  25619. return originalAnimation.currentValue;
  25620. }
  25621. }
  25622. finalScaling.scaleInPlace(scale);
  25623. finalPosition.scaleInPlace(scale);
  25624. finalQuaternion.scaleInPlace(scale);
  25625. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25626. var runtimeAnimation = holder.animations[animIndex];
  25627. var scale = runtimeAnimation.weight / normalizer;
  25628. var currentPosition = BABYLON.Tmp.Vector3[2];
  25629. var currentScaling = BABYLON.Tmp.Vector3[3];
  25630. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25631. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25632. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25633. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25634. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25635. }
  25636. if (!originalAnimation._workValue) {
  25637. originalAnimation._workValue = BABYLON.Matrix.Identity();
  25638. }
  25639. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25640. return originalAnimation._workValue;
  25641. };
  25642. Scene.prototype._processLateAnimationBindings = function () {
  25643. if (!this._registeredForLateAnimationBindings.length) {
  25644. return;
  25645. }
  25646. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25647. var target = this._registeredForLateAnimationBindings.data[index];
  25648. for (var path in target._lateAnimationHolders) {
  25649. var holder = target._lateAnimationHolders[path];
  25650. var originalAnimation = holder.animations[0];
  25651. var originalValue = originalAnimation.originalValue;
  25652. var finalTarget = originalAnimation.target;
  25653. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25654. var finalValue = void 0;
  25655. if (matrixDecomposeMode) {
  25656. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25657. }
  25658. else {
  25659. var startIndex = 0;
  25660. var normalizer = 1.0;
  25661. if (holder.totalWeight < 1.0) {
  25662. // We need to mix the original value in
  25663. if (originalValue.scale) {
  25664. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25665. }
  25666. else {
  25667. finalValue = originalValue * (1.0 - holder.totalWeight);
  25668. }
  25669. }
  25670. else {
  25671. // We need to normalize the weights
  25672. normalizer = holder.totalWeight;
  25673. var scale_1 = originalAnimation.weight / normalizer;
  25674. if (scale_1 !== 1) {
  25675. if (originalAnimation.currentValue.scale) {
  25676. finalValue = originalAnimation.currentValue.scale(scale_1);
  25677. }
  25678. else {
  25679. finalValue = originalAnimation.currentValue * scale_1;
  25680. }
  25681. }
  25682. else {
  25683. finalValue = originalAnimation.currentValue;
  25684. }
  25685. startIndex = 1;
  25686. }
  25687. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25688. var runtimeAnimation = holder.animations[animIndex];
  25689. var scale = runtimeAnimation.weight / normalizer;
  25690. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25691. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25692. }
  25693. else {
  25694. finalValue += runtimeAnimation.currentValue * scale;
  25695. }
  25696. }
  25697. }
  25698. finalTarget[path] = finalValue;
  25699. }
  25700. target._lateAnimationHolders = {};
  25701. }
  25702. this._registeredForLateAnimationBindings.reset();
  25703. };
  25704. // Matrix
  25705. /** @ignore */
  25706. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25707. this._useAlternateCameraConfiguration = active;
  25708. };
  25709. /**
  25710. * Gets the current view matrix
  25711. * @returns a Matrix
  25712. */
  25713. Scene.prototype.getViewMatrix = function () {
  25714. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25715. };
  25716. /**
  25717. * Gets the current projection matrix
  25718. * @returns a Matrix
  25719. */
  25720. Scene.prototype.getProjectionMatrix = function () {
  25721. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25722. };
  25723. /**
  25724. * Gets the current transform matrix
  25725. * @returns a Matrix made of View * Projection
  25726. */
  25727. Scene.prototype.getTransformMatrix = function () {
  25728. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25729. };
  25730. /**
  25731. * Sets the current transform matrix
  25732. * @param view defines the View matrix to use
  25733. * @param projection defines the Projection matrix to use
  25734. */
  25735. Scene.prototype.setTransformMatrix = function (view, projection) {
  25736. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25737. return;
  25738. }
  25739. this._viewUpdateFlag = view.updateFlag;
  25740. this._projectionUpdateFlag = projection.updateFlag;
  25741. this._viewMatrix = view;
  25742. this._projectionMatrix = projection;
  25743. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25744. // Update frustum
  25745. if (!this._frustumPlanes) {
  25746. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25747. }
  25748. else {
  25749. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25750. }
  25751. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25752. var otherCamera = this.activeCamera._alternateCamera;
  25753. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25754. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25755. }
  25756. if (this._sceneUbo.useUbo) {
  25757. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25758. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25759. this._sceneUbo.update();
  25760. }
  25761. };
  25762. /** @ignore */
  25763. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25764. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25765. return;
  25766. }
  25767. this._alternateViewUpdateFlag = view.updateFlag;
  25768. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25769. this._alternateViewMatrix = view;
  25770. this._alternateProjectionMatrix = projection;
  25771. if (!this._alternateTransformMatrix) {
  25772. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25773. }
  25774. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25775. if (!this._alternateSceneUbo) {
  25776. this._createAlternateUbo();
  25777. }
  25778. if (this._alternateSceneUbo.useUbo) {
  25779. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25780. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25781. this._alternateSceneUbo.update();
  25782. }
  25783. };
  25784. /**
  25785. * Gets the uniform buffer used to store scene data
  25786. * @returns a UniformBuffer
  25787. */
  25788. Scene.prototype.getSceneUniformBuffer = function () {
  25789. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25790. };
  25791. /**
  25792. * Gets an unique (relatively to the current scene) Id
  25793. * @returns an unique number for the scene
  25794. */
  25795. Scene.prototype.getUniqueId = function () {
  25796. var result = Scene._uniqueIdCounter;
  25797. Scene._uniqueIdCounter++;
  25798. return result;
  25799. };
  25800. /**
  25801. * Add a mesh to the list of scene's meshes
  25802. * @param newMesh defines the mesh to add
  25803. */
  25804. Scene.prototype.addMesh = function (newMesh) {
  25805. this.meshes.push(newMesh);
  25806. //notify the collision coordinator
  25807. if (this.collisionCoordinator) {
  25808. this.collisionCoordinator.onMeshAdded(newMesh);
  25809. }
  25810. newMesh._resyncLightSources();
  25811. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25812. };
  25813. /**
  25814. * Remove a mesh for the list of scene's meshes
  25815. * @param toRemove defines the mesh to remove
  25816. * @returns the index where the mesh was in the mesh list
  25817. */
  25818. Scene.prototype.removeMesh = function (toRemove) {
  25819. var index = this.meshes.indexOf(toRemove);
  25820. if (index !== -1) {
  25821. // Remove from the scene if mesh found
  25822. this.meshes.splice(index, 1);
  25823. }
  25824. this.onMeshRemovedObservable.notifyObservers(toRemove);
  25825. return index;
  25826. };
  25827. /**
  25828. * Add a transform node to the list of scene's transform nodes
  25829. * @param newTransformNode defines the transform node to add
  25830. */
  25831. Scene.prototype.addTransformNode = function (newTransformNode) {
  25832. this.transformNodes.push(newTransformNode);
  25833. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  25834. };
  25835. /**
  25836. * Remove a transform node for the list of scene's transform nodes
  25837. * @param toRemove defines the transform node to remove
  25838. * @returns the index where the transform node was in the transform node list
  25839. */
  25840. Scene.prototype.removeTransformNode = function (toRemove) {
  25841. var index = this.transformNodes.indexOf(toRemove);
  25842. if (index !== -1) {
  25843. // Remove from the scene if found
  25844. this.transformNodes.splice(index, 1);
  25845. }
  25846. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  25847. return index;
  25848. };
  25849. /**
  25850. * Remove a skeleton for the list of scene's skeletons
  25851. * @param toRemove defines the skeleton to remove
  25852. * @returns the index where the skeleton was in the skeleton list
  25853. */
  25854. Scene.prototype.removeSkeleton = function (toRemove) {
  25855. var index = this.skeletons.indexOf(toRemove);
  25856. if (index !== -1) {
  25857. // Remove from the scene if found
  25858. this.skeletons.splice(index, 1);
  25859. }
  25860. return index;
  25861. };
  25862. /**
  25863. * Remove a morph target for the list of scene's morph targets
  25864. * @param toRemove defines the morph target to remove
  25865. * @returns the index where the morph target was in the morph target list
  25866. */
  25867. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  25868. var index = this.morphTargetManagers.indexOf(toRemove);
  25869. if (index !== -1) {
  25870. // Remove from the scene if found
  25871. this.morphTargetManagers.splice(index, 1);
  25872. }
  25873. return index;
  25874. };
  25875. /**
  25876. * Remove a light for the list of scene's lights
  25877. * @param toRemove defines the light to remove
  25878. * @returns the index where the light was in the light list
  25879. */
  25880. Scene.prototype.removeLight = function (toRemove) {
  25881. var index = this.lights.indexOf(toRemove);
  25882. if (index !== -1) {
  25883. // Remove from meshes
  25884. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  25885. var mesh = _a[_i];
  25886. mesh._removeLightSource(toRemove);
  25887. }
  25888. // Remove from the scene if mesh found
  25889. this.lights.splice(index, 1);
  25890. this.sortLightsByPriority();
  25891. }
  25892. this.onLightRemovedObservable.notifyObservers(toRemove);
  25893. return index;
  25894. };
  25895. /**
  25896. * Remove a camera for the list of scene's cameras
  25897. * @param toRemove defines the camera to remove
  25898. * @returns the index where the camera was in the camera list
  25899. */
  25900. Scene.prototype.removeCamera = function (toRemove) {
  25901. var index = this.cameras.indexOf(toRemove);
  25902. if (index !== -1) {
  25903. // Remove from the scene if mesh found
  25904. this.cameras.splice(index, 1);
  25905. }
  25906. // Remove from activeCameras
  25907. var index2 = this.activeCameras.indexOf(toRemove);
  25908. if (index2 !== -1) {
  25909. // Remove from the scene if mesh found
  25910. this.activeCameras.splice(index2, 1);
  25911. }
  25912. // Reset the activeCamera
  25913. if (this.activeCamera === toRemove) {
  25914. if (this.cameras.length > 0) {
  25915. this.activeCamera = this.cameras[0];
  25916. }
  25917. else {
  25918. this.activeCamera = null;
  25919. }
  25920. }
  25921. this.onCameraRemovedObservable.notifyObservers(toRemove);
  25922. return index;
  25923. };
  25924. /**
  25925. * Remove a particle system for the list of scene's particle systems
  25926. * @param toRemove defines the particle system to remove
  25927. * @returns the index where the particle system was in the particle system list
  25928. */
  25929. Scene.prototype.removeParticleSystem = function (toRemove) {
  25930. var index = this.particleSystems.indexOf(toRemove);
  25931. if (index !== -1) {
  25932. this.particleSystems.splice(index, 1);
  25933. }
  25934. return index;
  25935. };
  25936. /**
  25937. * Remove a animation for the list of scene's animations
  25938. * @param toRemove defines the animation to remove
  25939. * @returns the index where the animation was in the animation list
  25940. */
  25941. Scene.prototype.removeAnimation = function (toRemove) {
  25942. var index = this.animations.indexOf(toRemove);
  25943. if (index !== -1) {
  25944. this.animations.splice(index, 1);
  25945. }
  25946. return index;
  25947. };
  25948. /**
  25949. * Removes the given animation group from this scene.
  25950. * @param toRemove The animation group to remove
  25951. * @returns The index of the removed animation group
  25952. */
  25953. Scene.prototype.removeAnimationGroup = function (toRemove) {
  25954. var index = this.animationGroups.indexOf(toRemove);
  25955. if (index !== -1) {
  25956. this.animationGroups.splice(index, 1);
  25957. }
  25958. return index;
  25959. };
  25960. /**
  25961. * Removes the given multi-material from this scene.
  25962. * @param toRemove The multi-material to remove
  25963. * @returns The index of the removed multi-material
  25964. */
  25965. Scene.prototype.removeMultiMaterial = function (toRemove) {
  25966. var index = this.multiMaterials.indexOf(toRemove);
  25967. if (index !== -1) {
  25968. this.multiMaterials.splice(index, 1);
  25969. }
  25970. return index;
  25971. };
  25972. /**
  25973. * Removes the given material from this scene.
  25974. * @param toRemove The material to remove
  25975. * @returns The index of the removed material
  25976. */
  25977. Scene.prototype.removeMaterial = function (toRemove) {
  25978. var index = this.materials.indexOf(toRemove);
  25979. if (index !== -1) {
  25980. this.materials.splice(index, 1);
  25981. }
  25982. return index;
  25983. };
  25984. /**
  25985. * Removes the given lens flare system from this scene.
  25986. * @param toRemove The lens flare system to remove
  25987. * @returns The index of the removed lens flare system
  25988. */
  25989. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  25990. var index = this.lensFlareSystems.indexOf(toRemove);
  25991. if (index !== -1) {
  25992. this.lensFlareSystems.splice(index, 1);
  25993. }
  25994. return index;
  25995. };
  25996. /**
  25997. * Removes the given action manager from this scene.
  25998. * @param toRemove The action manager to remove
  25999. * @returns The index of the removed action manager
  26000. */
  26001. Scene.prototype.removeActionManager = function (toRemove) {
  26002. var index = this._actionManagers.indexOf(toRemove);
  26003. if (index !== -1) {
  26004. this._actionManagers.splice(index, 1);
  26005. }
  26006. return index;
  26007. };
  26008. /**
  26009. * Removes the given effect layer from this scene.
  26010. * @param toRemove defines the effect layer to remove
  26011. * @returns the index of the removed effect layer
  26012. */
  26013. Scene.prototype.removeEffectLayer = function (toRemove) {
  26014. var index = this.effectLayers.indexOf(toRemove);
  26015. if (index !== -1) {
  26016. this.effectLayers.splice(index, 1);
  26017. }
  26018. return index;
  26019. };
  26020. /**
  26021. * Removes the given texture from this scene.
  26022. * @param toRemove The texture to remove
  26023. * @returns The index of the removed texture
  26024. */
  26025. Scene.prototype.removeTexture = function (toRemove) {
  26026. var index = this.textures.indexOf(toRemove);
  26027. if (index !== -1) {
  26028. this.textures.splice(index, 1);
  26029. }
  26030. return index;
  26031. };
  26032. /**
  26033. * Adds the given light to this scene
  26034. * @param newLight The light to add
  26035. */
  26036. Scene.prototype.addLight = function (newLight) {
  26037. this.lights.push(newLight);
  26038. this.sortLightsByPriority();
  26039. // Add light to all meshes (To support if the light is removed and then readded)
  26040. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26041. var mesh = _a[_i];
  26042. if (mesh._lightSources.indexOf(newLight) === -1) {
  26043. mesh._lightSources.push(newLight);
  26044. mesh._resyncLightSources();
  26045. }
  26046. }
  26047. this.onNewLightAddedObservable.notifyObservers(newLight);
  26048. };
  26049. /**
  26050. * Sorts the list list based on light priorities
  26051. */
  26052. Scene.prototype.sortLightsByPriority = function () {
  26053. if (this.requireLightSorting) {
  26054. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26055. }
  26056. };
  26057. /**
  26058. * Adds the given camera to this scene
  26059. * @param newCamera The camera to add
  26060. */
  26061. Scene.prototype.addCamera = function (newCamera) {
  26062. this.cameras.push(newCamera);
  26063. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26064. };
  26065. /**
  26066. * Adds the given skeleton to this scene
  26067. * @param newSkeleton The skeleton to add
  26068. */
  26069. Scene.prototype.addSkeleton = function (newSkeleton) {
  26070. this.skeletons.push(newSkeleton);
  26071. };
  26072. /**
  26073. * Adds the given particle system to this scene
  26074. * @param newParticleSystem The particle system to add
  26075. */
  26076. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26077. this.particleSystems.push(newParticleSystem);
  26078. };
  26079. /**
  26080. * Adds the given animation to this scene
  26081. * @param newAnimation The animation to add
  26082. */
  26083. Scene.prototype.addAnimation = function (newAnimation) {
  26084. this.animations.push(newAnimation);
  26085. };
  26086. /**
  26087. * Adds the given animation group to this scene.
  26088. * @param newAnimationGroup The animation group to add
  26089. */
  26090. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26091. this.animationGroups.push(newAnimationGroup);
  26092. };
  26093. /**
  26094. * Adds the given multi-material to this scene
  26095. * @param newMultiMaterial The multi-material to add
  26096. */
  26097. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26098. this.multiMaterials.push(newMultiMaterial);
  26099. };
  26100. /**
  26101. * Adds the given material to this scene
  26102. * @param newMaterial The material to add
  26103. */
  26104. Scene.prototype.addMaterial = function (newMaterial) {
  26105. this.materials.push(newMaterial);
  26106. };
  26107. /**
  26108. * Adds the given morph target to this scene
  26109. * @param newMorphTargetManager The morph target to add
  26110. */
  26111. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26112. this.morphTargetManagers.push(newMorphTargetManager);
  26113. };
  26114. /**
  26115. * Adds the given geometry to this scene
  26116. * @param newGeometry The geometry to add
  26117. */
  26118. Scene.prototype.addGeometry = function (newGeometry) {
  26119. this._geometries.push(newGeometry);
  26120. };
  26121. /**
  26122. * Adds the given lens flare system to this scene
  26123. * @param newLensFlareSystem The lens flare system to add
  26124. */
  26125. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26126. this.lensFlareSystems.push(newLensFlareSystem);
  26127. };
  26128. /**
  26129. * Adds the given effect layer to this scene
  26130. * @param newEffectLayer defines the effect layer to add
  26131. */
  26132. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26133. this.effectLayers.push(newEffectLayer);
  26134. };
  26135. /**
  26136. * Adds the given action manager to this scene
  26137. * @param newActionManager The action manager to add
  26138. */
  26139. Scene.prototype.addActionManager = function (newActionManager) {
  26140. this._actionManagers.push(newActionManager);
  26141. };
  26142. /**
  26143. * Adds the given texture to this scene.
  26144. * @param newTexture The texture to add
  26145. */
  26146. Scene.prototype.addTexture = function (newTexture) {
  26147. this.textures.push(newTexture);
  26148. };
  26149. /**
  26150. * Switch active camera
  26151. * @param newCamera defines the new active camera
  26152. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26153. */
  26154. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26155. if (attachControl === void 0) { attachControl = true; }
  26156. var canvas = this._engine.getRenderingCanvas();
  26157. if (!canvas) {
  26158. return;
  26159. }
  26160. if (this.activeCamera) {
  26161. this.activeCamera.detachControl(canvas);
  26162. }
  26163. this.activeCamera = newCamera;
  26164. if (attachControl) {
  26165. newCamera.attachControl(canvas);
  26166. }
  26167. };
  26168. /**
  26169. * sets the active camera of the scene using its ID
  26170. * @param id defines the camera's ID
  26171. * @return the new active camera or null if none found.
  26172. */
  26173. Scene.prototype.setActiveCameraByID = function (id) {
  26174. var camera = this.getCameraByID(id);
  26175. if (camera) {
  26176. this.activeCamera = camera;
  26177. return camera;
  26178. }
  26179. return null;
  26180. };
  26181. /**
  26182. * sets the active camera of the scene using its name
  26183. * @param name defines the camera's name
  26184. * @returns the new active camera or null if none found.
  26185. */
  26186. Scene.prototype.setActiveCameraByName = function (name) {
  26187. var camera = this.getCameraByName(name);
  26188. if (camera) {
  26189. this.activeCamera = camera;
  26190. return camera;
  26191. }
  26192. return null;
  26193. };
  26194. /**
  26195. * get an animation group using its name
  26196. * @param name defines the material's name
  26197. * @return the animation group or null if none found.
  26198. */
  26199. Scene.prototype.getAnimationGroupByName = function (name) {
  26200. for (var index = 0; index < this.animationGroups.length; index++) {
  26201. if (this.animationGroups[index].name === name) {
  26202. return this.animationGroups[index];
  26203. }
  26204. }
  26205. return null;
  26206. };
  26207. /**
  26208. * get a material using its id
  26209. * @param id defines the material's ID
  26210. * @return the material or null if none found.
  26211. */
  26212. Scene.prototype.getMaterialByID = function (id) {
  26213. for (var index = 0; index < this.materials.length; index++) {
  26214. if (this.materials[index].id === id) {
  26215. return this.materials[index];
  26216. }
  26217. }
  26218. return null;
  26219. };
  26220. /**
  26221. * Gets a material using its name
  26222. * @param name defines the material's name
  26223. * @return the material or null if none found.
  26224. */
  26225. Scene.prototype.getMaterialByName = function (name) {
  26226. for (var index = 0; index < this.materials.length; index++) {
  26227. if (this.materials[index].name === name) {
  26228. return this.materials[index];
  26229. }
  26230. }
  26231. return null;
  26232. };
  26233. /**
  26234. * Gets a lens flare system using its name
  26235. * @param name defines the name to look for
  26236. * @returns the lens flare system or null if not found
  26237. */
  26238. Scene.prototype.getLensFlareSystemByName = function (name) {
  26239. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26240. if (this.lensFlareSystems[index].name === name) {
  26241. return this.lensFlareSystems[index];
  26242. }
  26243. }
  26244. return null;
  26245. };
  26246. /**
  26247. * Gets a lens flare system using its id
  26248. * @param id defines the id to look for
  26249. * @returns the lens flare system or null if not found
  26250. */
  26251. Scene.prototype.getLensFlareSystemByID = function (id) {
  26252. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26253. if (this.lensFlareSystems[index].id === id) {
  26254. return this.lensFlareSystems[index];
  26255. }
  26256. }
  26257. return null;
  26258. };
  26259. /**
  26260. * Gets a camera using its id
  26261. * @param id defines the id to look for
  26262. * @returns the camera or null if not found
  26263. */
  26264. Scene.prototype.getCameraByID = function (id) {
  26265. for (var index = 0; index < this.cameras.length; index++) {
  26266. if (this.cameras[index].id === id) {
  26267. return this.cameras[index];
  26268. }
  26269. }
  26270. return null;
  26271. };
  26272. /**
  26273. * Gets a camera using its unique id
  26274. * @param uniqueId defines the unique id to look for
  26275. * @returns the camera or null if not found
  26276. */
  26277. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26278. for (var index = 0; index < this.cameras.length; index++) {
  26279. if (this.cameras[index].uniqueId === uniqueId) {
  26280. return this.cameras[index];
  26281. }
  26282. }
  26283. return null;
  26284. };
  26285. /**
  26286. * Gets a camera using its name
  26287. * @param name defines the camera's name
  26288. * @return the camera or null if none found.
  26289. */
  26290. Scene.prototype.getCameraByName = function (name) {
  26291. for (var index = 0; index < this.cameras.length; index++) {
  26292. if (this.cameras[index].name === name) {
  26293. return this.cameras[index];
  26294. }
  26295. }
  26296. return null;
  26297. };
  26298. /**
  26299. * Gets a bone using its id
  26300. * @param id defines the bone's id
  26301. * @return the bone or null if not found
  26302. */
  26303. Scene.prototype.getBoneByID = function (id) {
  26304. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26305. var skeleton = this.skeletons[skeletonIndex];
  26306. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26307. if (skeleton.bones[boneIndex].id === id) {
  26308. return skeleton.bones[boneIndex];
  26309. }
  26310. }
  26311. }
  26312. return null;
  26313. };
  26314. /**
  26315. * Gets a bone using its id
  26316. * @param name defines the bone's name
  26317. * @return the bone or null if not found
  26318. */
  26319. Scene.prototype.getBoneByName = function (name) {
  26320. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26321. var skeleton = this.skeletons[skeletonIndex];
  26322. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26323. if (skeleton.bones[boneIndex].name === name) {
  26324. return skeleton.bones[boneIndex];
  26325. }
  26326. }
  26327. }
  26328. return null;
  26329. };
  26330. /**
  26331. * Gets a light node using its name
  26332. * @param name defines the the light's name
  26333. * @return the light or null if none found.
  26334. */
  26335. Scene.prototype.getLightByName = function (name) {
  26336. for (var index = 0; index < this.lights.length; index++) {
  26337. if (this.lights[index].name === name) {
  26338. return this.lights[index];
  26339. }
  26340. }
  26341. return null;
  26342. };
  26343. /**
  26344. * Gets a light node using its id
  26345. * @param id defines the light's id
  26346. * @return the light or null if none found.
  26347. */
  26348. Scene.prototype.getLightByID = function (id) {
  26349. for (var index = 0; index < this.lights.length; index++) {
  26350. if (this.lights[index].id === id) {
  26351. return this.lights[index];
  26352. }
  26353. }
  26354. return null;
  26355. };
  26356. /**
  26357. * Gets a light node using its scene-generated unique ID
  26358. * @param uniqueId defines the light's unique id
  26359. * @return the light or null if none found.
  26360. */
  26361. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26362. for (var index = 0; index < this.lights.length; index++) {
  26363. if (this.lights[index].uniqueId === uniqueId) {
  26364. return this.lights[index];
  26365. }
  26366. }
  26367. return null;
  26368. };
  26369. /**
  26370. * Gets a particle system by id
  26371. * @param id defines the particle system id
  26372. * @return the corresponding system or null if none found
  26373. */
  26374. Scene.prototype.getParticleSystemByID = function (id) {
  26375. for (var index = 0; index < this.particleSystems.length; index++) {
  26376. if (this.particleSystems[index].id === id) {
  26377. return this.particleSystems[index];
  26378. }
  26379. }
  26380. return null;
  26381. };
  26382. /**
  26383. * Gets a geometry using its ID
  26384. * @param id defines the geometry's id
  26385. * @return the geometry or null if none found.
  26386. */
  26387. Scene.prototype.getGeometryByID = function (id) {
  26388. for (var index = 0; index < this._geometries.length; index++) {
  26389. if (this._geometries[index].id === id) {
  26390. return this._geometries[index];
  26391. }
  26392. }
  26393. return null;
  26394. };
  26395. /**
  26396. * Add a new geometry to this scene
  26397. * @param geometry defines the geometry to be added to the scene.
  26398. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26399. * @return a boolean defining if the geometry was added or not
  26400. */
  26401. Scene.prototype.pushGeometry = function (geometry, force) {
  26402. if (!force && this.getGeometryByID(geometry.id)) {
  26403. return false;
  26404. }
  26405. this._geometries.push(geometry);
  26406. //notify the collision coordinator
  26407. if (this.collisionCoordinator) {
  26408. this.collisionCoordinator.onGeometryAdded(geometry);
  26409. }
  26410. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26411. return true;
  26412. };
  26413. /**
  26414. * Removes an existing geometry
  26415. * @param geometry defines the geometry to be removed from the scene
  26416. * @return a boolean defining if the geometry was removed or not
  26417. */
  26418. Scene.prototype.removeGeometry = function (geometry) {
  26419. var index = this._geometries.indexOf(geometry);
  26420. if (index > -1) {
  26421. this._geometries.splice(index, 1);
  26422. //notify the collision coordinator
  26423. if (this.collisionCoordinator) {
  26424. this.collisionCoordinator.onGeometryDeleted(geometry);
  26425. }
  26426. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26427. return true;
  26428. }
  26429. return false;
  26430. };
  26431. /**
  26432. * Gets the list of geometries attached to the scene
  26433. * @returns an array of Geometry
  26434. */
  26435. Scene.prototype.getGeometries = function () {
  26436. return this._geometries;
  26437. };
  26438. /**
  26439. * Gets the first added mesh found of a given ID
  26440. * @param id defines the id to search for
  26441. * @return the mesh found or null if not found at all
  26442. */
  26443. Scene.prototype.getMeshByID = function (id) {
  26444. for (var index = 0; index < this.meshes.length; index++) {
  26445. if (this.meshes[index].id === id) {
  26446. return this.meshes[index];
  26447. }
  26448. }
  26449. return null;
  26450. };
  26451. /**
  26452. * Gets a list of meshes using their id
  26453. * @param id defines the id to search for
  26454. * @returns a list of meshes
  26455. */
  26456. Scene.prototype.getMeshesByID = function (id) {
  26457. return this.meshes.filter(function (m) {
  26458. return m.id === id;
  26459. });
  26460. };
  26461. /**
  26462. * Gets the first added transform node found of a given ID
  26463. * @param id defines the id to search for
  26464. * @return the found transform node or null if not found at all.
  26465. */
  26466. Scene.prototype.getTransformNodeByID = function (id) {
  26467. for (var index = 0; index < this.transformNodes.length; index++) {
  26468. if (this.transformNodes[index].id === id) {
  26469. return this.transformNodes[index];
  26470. }
  26471. }
  26472. return null;
  26473. };
  26474. /**
  26475. * Gets a list of transform nodes using their id
  26476. * @param id defines the id to search for
  26477. * @returns a list of transform nodes
  26478. */
  26479. Scene.prototype.getTransformNodesByID = function (id) {
  26480. return this.transformNodes.filter(function (m) {
  26481. return m.id === id;
  26482. });
  26483. };
  26484. /**
  26485. * Gets a mesh with its auto-generated unique id
  26486. * @param uniqueId defines the unique id to search for
  26487. * @return the found mesh or null if not found at all.
  26488. */
  26489. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26490. for (var index = 0; index < this.meshes.length; index++) {
  26491. if (this.meshes[index].uniqueId === uniqueId) {
  26492. return this.meshes[index];
  26493. }
  26494. }
  26495. return null;
  26496. };
  26497. /**
  26498. * Gets a the last added mesh using a given id
  26499. * @param id defines the id to search for
  26500. * @return the found mesh or null if not found at all.
  26501. */
  26502. Scene.prototype.getLastMeshByID = function (id) {
  26503. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26504. if (this.meshes[index].id === id) {
  26505. return this.meshes[index];
  26506. }
  26507. }
  26508. return null;
  26509. };
  26510. /**
  26511. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26512. * @param id defines the id to search for
  26513. * @return the found node or null if not found at all
  26514. */
  26515. Scene.prototype.getLastEntryByID = function (id) {
  26516. var index;
  26517. for (index = this.meshes.length - 1; index >= 0; index--) {
  26518. if (this.meshes[index].id === id) {
  26519. return this.meshes[index];
  26520. }
  26521. }
  26522. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26523. if (this.transformNodes[index].id === id) {
  26524. return this.transformNodes[index];
  26525. }
  26526. }
  26527. for (index = this.cameras.length - 1; index >= 0; index--) {
  26528. if (this.cameras[index].id === id) {
  26529. return this.cameras[index];
  26530. }
  26531. }
  26532. for (index = this.lights.length - 1; index >= 0; index--) {
  26533. if (this.lights[index].id === id) {
  26534. return this.lights[index];
  26535. }
  26536. }
  26537. return null;
  26538. };
  26539. /**
  26540. * Gets a node (Mesh, Camera, Light) using a given id
  26541. * @param id defines the id to search for
  26542. * @return the found node or null if not found at all
  26543. */
  26544. Scene.prototype.getNodeByID = function (id) {
  26545. var mesh = this.getMeshByID(id);
  26546. if (mesh) {
  26547. return mesh;
  26548. }
  26549. var light = this.getLightByID(id);
  26550. if (light) {
  26551. return light;
  26552. }
  26553. var camera = this.getCameraByID(id);
  26554. if (camera) {
  26555. return camera;
  26556. }
  26557. var bone = this.getBoneByID(id);
  26558. return bone;
  26559. };
  26560. /**
  26561. * Gets a node (Mesh, Camera, Light) using a given name
  26562. * @param name defines the name to search for
  26563. * @return the found node or null if not found at all.
  26564. */
  26565. Scene.prototype.getNodeByName = function (name) {
  26566. var mesh = this.getMeshByName(name);
  26567. if (mesh) {
  26568. return mesh;
  26569. }
  26570. var light = this.getLightByName(name);
  26571. if (light) {
  26572. return light;
  26573. }
  26574. var camera = this.getCameraByName(name);
  26575. if (camera) {
  26576. return camera;
  26577. }
  26578. var bone = this.getBoneByName(name);
  26579. return bone;
  26580. };
  26581. /**
  26582. * Gets a mesh using a given name
  26583. * @param name defines the name to search for
  26584. * @return the found mesh or null if not found at all.
  26585. */
  26586. Scene.prototype.getMeshByName = function (name) {
  26587. for (var index = 0; index < this.meshes.length; index++) {
  26588. if (this.meshes[index].name === name) {
  26589. return this.meshes[index];
  26590. }
  26591. }
  26592. return null;
  26593. };
  26594. /**
  26595. * Gets a transform node using a given name
  26596. * @param name defines the name to search for
  26597. * @return the found transform node or null if not found at all.
  26598. */
  26599. Scene.prototype.getTransformNodeByName = function (name) {
  26600. for (var index = 0; index < this.transformNodes.length; index++) {
  26601. if (this.transformNodes[index].name === name) {
  26602. return this.transformNodes[index];
  26603. }
  26604. }
  26605. return null;
  26606. };
  26607. /**
  26608. * Gets a sound using a given name
  26609. * @param name defines the name to search for
  26610. * @return the found sound or null if not found at all.
  26611. */
  26612. Scene.prototype.getSoundByName = function (name) {
  26613. var index;
  26614. if (BABYLON.AudioEngine) {
  26615. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26616. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26617. return this.mainSoundTrack.soundCollection[index];
  26618. }
  26619. }
  26620. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26621. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26622. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26623. return this.soundTracks[sdIndex].soundCollection[index];
  26624. }
  26625. }
  26626. }
  26627. }
  26628. return null;
  26629. };
  26630. /**
  26631. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26632. * @param id defines the id to search for
  26633. * @return the found skeleton or null if not found at all.
  26634. */
  26635. Scene.prototype.getLastSkeletonByID = function (id) {
  26636. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26637. if (this.skeletons[index].id === id) {
  26638. return this.skeletons[index];
  26639. }
  26640. }
  26641. return null;
  26642. };
  26643. /**
  26644. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26645. * @param id defines the id to search for
  26646. * @return the found skeleton or null if not found at all.
  26647. */
  26648. Scene.prototype.getSkeletonById = function (id) {
  26649. for (var index = 0; index < this.skeletons.length; index++) {
  26650. if (this.skeletons[index].id === id) {
  26651. return this.skeletons[index];
  26652. }
  26653. }
  26654. return null;
  26655. };
  26656. /**
  26657. * Gets a skeleton using a given name
  26658. * @param name defines the name to search for
  26659. * @return the found skeleton or null if not found at all.
  26660. */
  26661. Scene.prototype.getSkeletonByName = function (name) {
  26662. for (var index = 0; index < this.skeletons.length; index++) {
  26663. if (this.skeletons[index].name === name) {
  26664. return this.skeletons[index];
  26665. }
  26666. }
  26667. return null;
  26668. };
  26669. /**
  26670. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26671. * @param id defines the id to search for
  26672. * @return the found morph target manager or null if not found at all.
  26673. */
  26674. Scene.prototype.getMorphTargetManagerById = function (id) {
  26675. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26676. if (this.morphTargetManagers[index].uniqueId === id) {
  26677. return this.morphTargetManagers[index];
  26678. }
  26679. }
  26680. return null;
  26681. };
  26682. /**
  26683. * Gets a boolean indicating if the given mesh is active
  26684. * @param mesh defines the mesh to look for
  26685. * @returns true if the mesh is in the active list
  26686. */
  26687. Scene.prototype.isActiveMesh = function (mesh) {
  26688. return (this._activeMeshes.indexOf(mesh) !== -1);
  26689. };
  26690. /**
  26691. * Return a the first highlight layer of the scene with a given name.
  26692. * @param name The name of the highlight layer to look for.
  26693. * @return The highlight layer if found otherwise null.
  26694. */
  26695. Scene.prototype.getHighlightLayerByName = function (name) {
  26696. for (var index = 0; index < this.effectLayers.length; index++) {
  26697. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26698. return this.effectLayers[index];
  26699. }
  26700. }
  26701. return null;
  26702. };
  26703. /**
  26704. * Return a the first highlight layer of the scene with a given name.
  26705. * @param name The name of the highlight layer to look for.
  26706. * @return The highlight layer if found otherwise null.
  26707. */
  26708. Scene.prototype.getGlowLayerByName = function (name) {
  26709. for (var index = 0; index < this.effectLayers.length; index++) {
  26710. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26711. return this.effectLayers[index];
  26712. }
  26713. }
  26714. return null;
  26715. };
  26716. Object.defineProperty(Scene.prototype, "uid", {
  26717. /**
  26718. * Return a unique id as a string which can serve as an identifier for the scene
  26719. */
  26720. get: function () {
  26721. if (!this._uid) {
  26722. this._uid = BABYLON.Tools.RandomId();
  26723. }
  26724. return this._uid;
  26725. },
  26726. enumerable: true,
  26727. configurable: true
  26728. });
  26729. /**
  26730. * Add an externaly attached data from its key.
  26731. * This method call will fail and return false, if such key already exists.
  26732. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26733. * @param key the unique key that identifies the data
  26734. * @param data the data object to associate to the key for this Engine instance
  26735. * @return true if no such key were already present and the data was added successfully, false otherwise
  26736. */
  26737. Scene.prototype.addExternalData = function (key, data) {
  26738. if (!this._externalData) {
  26739. this._externalData = new BABYLON.StringDictionary();
  26740. }
  26741. return this._externalData.add(key, data);
  26742. };
  26743. /**
  26744. * Get an externaly attached data from its key
  26745. * @param key the unique key that identifies the data
  26746. * @return the associated data, if present (can be null), or undefined if not present
  26747. */
  26748. Scene.prototype.getExternalData = function (key) {
  26749. if (!this._externalData) {
  26750. return null;
  26751. }
  26752. return this._externalData.get(key);
  26753. };
  26754. /**
  26755. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26756. * @param key the unique key that identifies the data
  26757. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26758. * @return the associated data, can be null if the factory returned null.
  26759. */
  26760. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26761. if (!this._externalData) {
  26762. this._externalData = new BABYLON.StringDictionary();
  26763. }
  26764. return this._externalData.getOrAddWithFactory(key, factory);
  26765. };
  26766. /**
  26767. * Remove an externaly attached data from the Engine instance
  26768. * @param key the unique key that identifies the data
  26769. * @return true if the data was successfully removed, false if it doesn't exist
  26770. */
  26771. Scene.prototype.removeExternalData = function (key) {
  26772. return this._externalData.remove(key);
  26773. };
  26774. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26775. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26776. if (mesh.showSubMeshesBoundingBox) {
  26777. var boundingInfo = subMesh.getBoundingInfo();
  26778. if (boundingInfo !== null && boundingInfo !== undefined) {
  26779. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26780. }
  26781. }
  26782. var material = subMesh.getMaterial();
  26783. if (material !== null && material !== undefined) {
  26784. // Render targets
  26785. if (material.getRenderTargetTextures !== undefined) {
  26786. if (this._processedMaterials.indexOf(material) === -1) {
  26787. this._processedMaterials.push(material);
  26788. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26789. }
  26790. }
  26791. // Dispatch
  26792. this._activeIndices.addCount(subMesh.indexCount, false);
  26793. this._renderingManager.dispatch(subMesh, mesh, material);
  26794. }
  26795. }
  26796. };
  26797. /**
  26798. * Clear the processed materials smart array preventing retention point in material dispose.
  26799. */
  26800. Scene.prototype.freeProcessedMaterials = function () {
  26801. this._processedMaterials.dispose();
  26802. };
  26803. /**
  26804. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26805. */
  26806. Scene.prototype.freeActiveMeshes = function () {
  26807. this._activeMeshes.dispose();
  26808. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26809. this.activeCamera._activeMeshes.dispose();
  26810. }
  26811. if (this.activeCameras) {
  26812. for (var i = 0; i < this.activeCameras.length; i++) {
  26813. var activeCamera = this.activeCameras[i];
  26814. if (activeCamera && activeCamera._activeMeshes) {
  26815. activeCamera._activeMeshes.dispose();
  26816. }
  26817. }
  26818. }
  26819. };
  26820. /**
  26821. * Clear the info related to rendering groups preventing retention points during dispose.
  26822. */
  26823. Scene.prototype.freeRenderingGroups = function () {
  26824. if (this._renderingManager) {
  26825. this._renderingManager.freeRenderingGroups();
  26826. }
  26827. if (this.textures) {
  26828. for (var i = 0; i < this.textures.length; i++) {
  26829. var texture = this.textures[i];
  26830. if (texture && texture.renderList) {
  26831. texture.freeRenderingGroups();
  26832. }
  26833. }
  26834. }
  26835. };
  26836. /** @ignore */
  26837. Scene.prototype._isInIntermediateRendering = function () {
  26838. return this._intermediateRendering;
  26839. };
  26840. /**
  26841. * Defines the current active mesh candidate provider
  26842. * @param provider defines the provider to use
  26843. */
  26844. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  26845. this._activeMeshCandidateProvider = provider;
  26846. };
  26847. /**
  26848. * Gets the current active mesh candidate provider
  26849. * @returns the current active mesh candidate provider
  26850. */
  26851. Scene.prototype.getActiveMeshCandidateProvider = function () {
  26852. return this._activeMeshCandidateProvider;
  26853. };
  26854. /**
  26855. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  26856. * @returns the current scene
  26857. */
  26858. Scene.prototype.freezeActiveMeshes = function () {
  26859. if (!this.activeCamera) {
  26860. return this;
  26861. }
  26862. if (!this._frustumPlanes) {
  26863. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  26864. }
  26865. this._evaluateActiveMeshes();
  26866. this._activeMeshesFrozen = true;
  26867. return this;
  26868. };
  26869. /**
  26870. * Use this function to restart evaluating active meshes on every frame
  26871. * @returns the current scene
  26872. */
  26873. Scene.prototype.unfreezeActiveMeshes = function () {
  26874. this._activeMeshesFrozen = false;
  26875. return this;
  26876. };
  26877. Scene.prototype._evaluateActiveMeshes = function () {
  26878. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  26879. return;
  26880. }
  26881. if (!this.activeCamera) {
  26882. return;
  26883. }
  26884. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  26885. this.activeCamera._activeMeshes.reset();
  26886. this._activeMeshes.reset();
  26887. this._renderingManager.reset();
  26888. this._processedMaterials.reset();
  26889. this._activeParticleSystems.reset();
  26890. this._activeSkeletons.reset();
  26891. this._softwareSkinnedMeshes.reset();
  26892. if (this._boundingBoxRenderer) {
  26893. this._boundingBoxRenderer.reset();
  26894. }
  26895. // Meshes
  26896. var meshes;
  26897. var len;
  26898. var checkIsEnabled = true;
  26899. // Determine mesh candidates
  26900. if (this._activeMeshCandidateProvider !== undefined) {
  26901. // Use _activeMeshCandidateProvider
  26902. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  26903. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  26904. if (meshes !== undefined) {
  26905. len = meshes.length;
  26906. }
  26907. else {
  26908. len = 0;
  26909. }
  26910. }
  26911. else if (this._selectionOctree !== undefined) {
  26912. // Octree
  26913. var selection = this._selectionOctree.select(this._frustumPlanes);
  26914. meshes = selection.data;
  26915. len = selection.length;
  26916. }
  26917. else {
  26918. // Full scene traversal
  26919. len = this.meshes.length;
  26920. meshes = this.meshes;
  26921. }
  26922. // Check each mesh
  26923. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  26924. mesh = meshes[meshIndex];
  26925. if (mesh.isBlocked) {
  26926. continue;
  26927. }
  26928. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  26929. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  26930. continue;
  26931. }
  26932. mesh.computeWorldMatrix();
  26933. // Intersections
  26934. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  26935. this._meshesForIntersections.pushNoDuplicate(mesh);
  26936. }
  26937. // Switch to current LOD
  26938. meshLOD = mesh.getLOD(this.activeCamera);
  26939. if (meshLOD === undefined || meshLOD === null) {
  26940. continue;
  26941. }
  26942. mesh._preActivate();
  26943. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  26944. this._activeMeshes.push(mesh);
  26945. this.activeCamera._activeMeshes.push(mesh);
  26946. mesh._activate(this._renderId);
  26947. if (meshLOD !== mesh) {
  26948. meshLOD._activate(this._renderId);
  26949. }
  26950. this._activeMesh(mesh, meshLOD);
  26951. }
  26952. }
  26953. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  26954. // Particle systems
  26955. if (this.particlesEnabled) {
  26956. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  26957. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  26958. var particleSystem = this.particleSystems[particleIndex];
  26959. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  26960. continue;
  26961. }
  26962. var emitter = particleSystem.emitter;
  26963. if (!emitter.position || emitter.isEnabled()) {
  26964. this._activeParticleSystems.push(particleSystem);
  26965. particleSystem.animate();
  26966. this._renderingManager.dispatchParticles(particleSystem);
  26967. }
  26968. }
  26969. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  26970. }
  26971. };
  26972. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  26973. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  26974. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  26975. mesh.skeleton.prepare();
  26976. }
  26977. if (!mesh.computeBonesUsingShaders) {
  26978. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  26979. }
  26980. }
  26981. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  26982. var boundingInfo = sourceMesh.getBoundingInfo();
  26983. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26984. }
  26985. if (mesh !== undefined && mesh !== null
  26986. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  26987. // Submeshes Octrees
  26988. var len;
  26989. var subMeshes;
  26990. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  26991. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  26992. len = intersections.length;
  26993. subMeshes = intersections.data;
  26994. }
  26995. else {
  26996. subMeshes = mesh.subMeshes;
  26997. len = subMeshes.length;
  26998. }
  26999. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27000. subMesh = subMeshes[subIndex];
  27001. this._evaluateSubMesh(subMesh, mesh);
  27002. }
  27003. }
  27004. };
  27005. /**
  27006. * Update the transform matrix to update from the current active camera
  27007. * @param force defines a boolean used to force the update even if cache is up to date
  27008. */
  27009. Scene.prototype.updateTransformMatrix = function (force) {
  27010. if (!this.activeCamera) {
  27011. return;
  27012. }
  27013. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27014. };
  27015. /**
  27016. * 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)
  27017. * @param alternateCamera defines the camera to use
  27018. */
  27019. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27020. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27021. };
  27022. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27023. if (camera && camera._skipRendering) {
  27024. return;
  27025. }
  27026. var engine = this._engine;
  27027. this.activeCamera = camera;
  27028. if (!this.activeCamera)
  27029. throw new Error("Active camera not set");
  27030. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27031. // Viewport
  27032. engine.setViewport(this.activeCamera.viewport);
  27033. // Camera
  27034. this.resetCachedMaterial();
  27035. this._renderId++;
  27036. this.updateTransformMatrix();
  27037. if (camera._alternateCamera) {
  27038. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27039. this._alternateRendering = true;
  27040. }
  27041. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27042. // Meshes
  27043. this._evaluateActiveMeshes();
  27044. // Software skinning
  27045. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27046. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27047. mesh.applySkeleton(mesh.skeleton);
  27048. }
  27049. // Render targets
  27050. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27051. var needsRestoreFrameBuffer = false;
  27052. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27053. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27054. }
  27055. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27056. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27057. }
  27058. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27059. this._intermediateRendering = true;
  27060. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27061. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27062. var renderTarget = this._renderTargets.data[renderIndex];
  27063. if (renderTarget._shouldRender()) {
  27064. this._renderId++;
  27065. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27066. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27067. }
  27068. }
  27069. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27070. this._intermediateRendering = false;
  27071. this._renderId++;
  27072. needsRestoreFrameBuffer = true; // Restore back buffer
  27073. }
  27074. // Render EffecttLayer Texture
  27075. var stencilState = this._engine.getStencilBuffer();
  27076. var renderEffects = false;
  27077. var needStencil = false;
  27078. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27079. this._intermediateRendering = true;
  27080. for (var i = 0; i < this.effectLayers.length; i++) {
  27081. var effectLayer = this.effectLayers[i];
  27082. if (effectLayer.shouldRender() &&
  27083. (!effectLayer.camera ||
  27084. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27085. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27086. renderEffects = true;
  27087. needStencil = needStencil || effectLayer.needStencil();
  27088. var renderTarget = effectLayer._mainTexture;
  27089. if (renderTarget._shouldRender()) {
  27090. this._renderId++;
  27091. renderTarget.render(false, false);
  27092. needsRestoreFrameBuffer = true;
  27093. }
  27094. }
  27095. }
  27096. this._intermediateRendering = false;
  27097. this._renderId++;
  27098. }
  27099. if (needsRestoreFrameBuffer) {
  27100. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27101. }
  27102. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27103. // Prepare Frame
  27104. this.postProcessManager._prepareFrame();
  27105. // Backgrounds
  27106. var layerIndex;
  27107. var layer;
  27108. if (this.layers.length) {
  27109. engine.setDepthBuffer(false);
  27110. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27111. layer = this.layers[layerIndex];
  27112. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27113. layer.render();
  27114. }
  27115. }
  27116. engine.setDepthBuffer(true);
  27117. }
  27118. // Activate effect Layer stencil
  27119. if (needStencil) {
  27120. this._engine.setStencilBuffer(true);
  27121. }
  27122. // Render
  27123. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27124. this._renderingManager.render(null, null, true, true);
  27125. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27126. // Restore effect Layer stencil
  27127. if (needStencil) {
  27128. this._engine.setStencilBuffer(stencilState);
  27129. }
  27130. // Bounding boxes
  27131. if (this._boundingBoxRenderer) {
  27132. this._boundingBoxRenderer.render();
  27133. }
  27134. // Lens flares
  27135. if (this.lensFlaresEnabled) {
  27136. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27137. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27138. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27139. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27140. lensFlareSystem.render();
  27141. }
  27142. }
  27143. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27144. }
  27145. // Effect Layer
  27146. if (renderEffects) {
  27147. engine.setDepthBuffer(false);
  27148. for (var i = 0; i < this.effectLayers.length; i++) {
  27149. if (this.effectLayers[i].shouldRender()) {
  27150. this.effectLayers[i].render();
  27151. }
  27152. }
  27153. engine.setDepthBuffer(true);
  27154. }
  27155. // Foregrounds
  27156. if (this.layers.length) {
  27157. engine.setDepthBuffer(false);
  27158. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27159. layer = this.layers[layerIndex];
  27160. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27161. layer.render();
  27162. }
  27163. }
  27164. engine.setDepthBuffer(true);
  27165. }
  27166. // Finalize frame
  27167. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27168. // Reset some special arrays
  27169. this._renderTargets.reset();
  27170. this._alternateRendering = false;
  27171. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27172. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27173. };
  27174. Scene.prototype._processSubCameras = function (camera) {
  27175. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27176. this._renderForCamera(camera);
  27177. return;
  27178. }
  27179. // rig cameras
  27180. for (var index = 0; index < camera._rigCameras.length; index++) {
  27181. this._renderForCamera(camera._rigCameras[index], camera);
  27182. }
  27183. this.activeCamera = camera;
  27184. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27185. };
  27186. Scene.prototype._checkIntersections = function () {
  27187. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27188. var sourceMesh = this._meshesForIntersections.data[index];
  27189. if (!sourceMesh.actionManager) {
  27190. continue;
  27191. }
  27192. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27193. var action = sourceMesh.actionManager.actions[actionIndex];
  27194. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27195. var parameters = action.getTriggerParameter();
  27196. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27197. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27198. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27199. if (areIntersecting && currentIntersectionInProgress === -1) {
  27200. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27201. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27202. sourceMesh._intersectionsInProgress.push(otherMesh);
  27203. }
  27204. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27205. sourceMesh._intersectionsInProgress.push(otherMesh);
  27206. }
  27207. }
  27208. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27209. //They intersected, and now they don't.
  27210. //is this trigger an exit trigger? execute an event.
  27211. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27212. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27213. }
  27214. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27215. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27216. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27217. return otherMesh === parameterMesh;
  27218. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27219. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27220. }
  27221. }
  27222. }
  27223. }
  27224. }
  27225. };
  27226. /**
  27227. * Render the scene
  27228. */
  27229. Scene.prototype.render = function () {
  27230. if (this.isDisposed) {
  27231. return;
  27232. }
  27233. this._activeParticles.fetchNewFrame();
  27234. this._totalVertices.fetchNewFrame();
  27235. this._activeIndices.fetchNewFrame();
  27236. this._activeBones.fetchNewFrame();
  27237. this._meshesForIntersections.reset();
  27238. this.resetCachedMaterial();
  27239. this.onBeforeAnimationsObservable.notifyObservers(this);
  27240. // Actions
  27241. if (this.actionManager) {
  27242. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27243. }
  27244. //Simplification Queue
  27245. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27246. this.simplificationQueue.executeNext();
  27247. }
  27248. if (this._engine.isDeterministicLockStep()) {
  27249. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27250. var defaultFPS = (60.0 / 1000.0);
  27251. var defaultFrameTime = 1000 / 60; // frame time in MS
  27252. if (this._physicsEngine) {
  27253. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27254. }
  27255. var stepsTaken = 0;
  27256. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27257. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27258. internalSteps = Math.min(internalSteps, maxSubSteps);
  27259. do {
  27260. this.onBeforeStepObservable.notifyObservers(this);
  27261. // Animations
  27262. this._animationRatio = defaultFrameTime * defaultFPS;
  27263. this._animate();
  27264. this.onAfterAnimationsObservable.notifyObservers(this);
  27265. // Physics
  27266. if (this._physicsEngine) {
  27267. this.onBeforePhysicsObservable.notifyObservers(this);
  27268. this._physicsEngine._step(defaultFrameTime / 1000);
  27269. this.onAfterPhysicsObservable.notifyObservers(this);
  27270. }
  27271. this.onAfterStepObservable.notifyObservers(this);
  27272. this._currentStepId++;
  27273. stepsTaken++;
  27274. deltaTime -= defaultFrameTime;
  27275. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27276. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27277. }
  27278. else {
  27279. // Animations
  27280. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27281. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27282. this._animate();
  27283. this.onAfterAnimationsObservable.notifyObservers(this);
  27284. // Physics
  27285. if (this._physicsEngine) {
  27286. this.onBeforePhysicsObservable.notifyObservers(this);
  27287. this._physicsEngine._step(deltaTime / 1000.0);
  27288. this.onAfterPhysicsObservable.notifyObservers(this);
  27289. }
  27290. }
  27291. // update gamepad manager
  27292. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27293. this._gamepadManager._checkGamepadsStatus();
  27294. }
  27295. // Update Cameras
  27296. if (this.activeCameras.length > 0) {
  27297. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27298. var camera = this.activeCameras[cameraIndex];
  27299. camera.update();
  27300. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27301. // rig cameras
  27302. for (var index = 0; index < camera._rigCameras.length; index++) {
  27303. camera._rigCameras[index].update();
  27304. }
  27305. }
  27306. }
  27307. }
  27308. else if (this.activeCamera) {
  27309. this.activeCamera.update();
  27310. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27311. // rig cameras
  27312. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27313. this.activeCamera._rigCameras[index].update();
  27314. }
  27315. }
  27316. }
  27317. // Before render
  27318. this.onBeforeRenderObservable.notifyObservers(this);
  27319. // Customs render targets
  27320. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27321. var engine = this.getEngine();
  27322. var currentActiveCamera = this.activeCamera;
  27323. if (this.renderTargetsEnabled) {
  27324. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27325. this._intermediateRendering = true;
  27326. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27327. var renderTarget = this.customRenderTargets[customIndex];
  27328. if (renderTarget._shouldRender()) {
  27329. this._renderId++;
  27330. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27331. if (!this.activeCamera)
  27332. throw new Error("Active camera not set");
  27333. // Viewport
  27334. engine.setViewport(this.activeCamera.viewport);
  27335. // Camera
  27336. this.updateTransformMatrix();
  27337. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27338. }
  27339. }
  27340. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27341. this._intermediateRendering = false;
  27342. this._renderId++;
  27343. }
  27344. // Restore back buffer
  27345. if (this.customRenderTargets.length > 0) {
  27346. engine.restoreDefaultFramebuffer();
  27347. }
  27348. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27349. this.activeCamera = currentActiveCamera;
  27350. // Procedural textures
  27351. if (this.proceduralTexturesEnabled) {
  27352. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27353. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27354. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27355. if (proceduralTexture._shouldRender()) {
  27356. proceduralTexture.render();
  27357. }
  27358. }
  27359. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27360. }
  27361. // Clear
  27362. if (this.autoClearDepthAndStencil || this.autoClear) {
  27363. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27364. }
  27365. // Shadows
  27366. if (this.shadowsEnabled) {
  27367. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27368. var light = this.lights[lightIndex];
  27369. var shadowGenerator = light.getShadowGenerator();
  27370. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27371. var shadowMap = (shadowGenerator.getShadowMap());
  27372. if (this.textures.indexOf(shadowMap) !== -1) {
  27373. this._renderTargets.push(shadowMap);
  27374. }
  27375. }
  27376. }
  27377. }
  27378. // Depth renderer
  27379. for (var key in this._depthRenderer) {
  27380. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27381. }
  27382. // Geometry renderer
  27383. if (this._geometryBufferRenderer) {
  27384. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27385. }
  27386. // RenderPipeline
  27387. if (this._postProcessRenderPipelineManager) {
  27388. this._postProcessRenderPipelineManager.update();
  27389. }
  27390. // Multi-cameras?
  27391. if (this.activeCameras.length > 0) {
  27392. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27393. if (cameraIndex > 0) {
  27394. this._engine.clear(null, false, true, true);
  27395. }
  27396. this._processSubCameras(this.activeCameras[cameraIndex]);
  27397. }
  27398. }
  27399. else {
  27400. if (!this.activeCamera) {
  27401. throw new Error("No camera defined");
  27402. }
  27403. this._processSubCameras(this.activeCamera);
  27404. }
  27405. // Intersection checks
  27406. this._checkIntersections();
  27407. // Update the audio listener attached to the camera
  27408. if (BABYLON.AudioEngine) {
  27409. this._updateAudioParameters();
  27410. }
  27411. // After render
  27412. if (this.afterRender) {
  27413. this.afterRender();
  27414. }
  27415. this.onAfterRenderObservable.notifyObservers(this);
  27416. // Cleaning
  27417. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27418. var data = this._toBeDisposed.data[index];
  27419. if (data) {
  27420. data.dispose();
  27421. }
  27422. this._toBeDisposed[index] = null;
  27423. }
  27424. this._toBeDisposed.reset();
  27425. if (this.dumpNextRenderTargets) {
  27426. this.dumpNextRenderTargets = false;
  27427. }
  27428. this._activeBones.addCount(0, true);
  27429. this._activeIndices.addCount(0, true);
  27430. this._activeParticles.addCount(0, true);
  27431. };
  27432. Scene.prototype._updateAudioParameters = function () {
  27433. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27434. return;
  27435. }
  27436. var listeningCamera;
  27437. var audioEngine = BABYLON.Engine.audioEngine;
  27438. if (this.activeCameras.length > 0) {
  27439. listeningCamera = this.activeCameras[0];
  27440. }
  27441. else {
  27442. listeningCamera = this.activeCamera;
  27443. }
  27444. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27445. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27446. // for VR cameras
  27447. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27448. listeningCamera = listeningCamera.rigCameras[0];
  27449. }
  27450. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27451. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27452. cameraDirection.normalize();
  27453. // To avoid some errors on GearVR
  27454. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27455. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27456. }
  27457. var i;
  27458. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27459. var sound = this.mainSoundTrack.soundCollection[i];
  27460. if (sound.useCustomAttenuation) {
  27461. sound.updateDistanceFromListener();
  27462. }
  27463. }
  27464. for (i = 0; i < this.soundTracks.length; i++) {
  27465. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27466. sound = this.soundTracks[i].soundCollection[j];
  27467. if (sound.useCustomAttenuation) {
  27468. sound.updateDistanceFromListener();
  27469. }
  27470. }
  27471. }
  27472. }
  27473. };
  27474. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27475. // Audio
  27476. /**
  27477. * Gets or sets if audio support is enabled
  27478. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27479. */
  27480. get: function () {
  27481. return this._audioEnabled;
  27482. },
  27483. set: function (value) {
  27484. this._audioEnabled = value;
  27485. if (BABYLON.AudioEngine) {
  27486. if (this._audioEnabled) {
  27487. this._enableAudio();
  27488. }
  27489. else {
  27490. this._disableAudio();
  27491. }
  27492. }
  27493. },
  27494. enumerable: true,
  27495. configurable: true
  27496. });
  27497. Scene.prototype._disableAudio = function () {
  27498. var i;
  27499. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27500. this.mainSoundTrack.soundCollection[i].pause();
  27501. }
  27502. for (i = 0; i < this.soundTracks.length; i++) {
  27503. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27504. this.soundTracks[i].soundCollection[j].pause();
  27505. }
  27506. }
  27507. };
  27508. Scene.prototype._enableAudio = function () {
  27509. var i;
  27510. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27511. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27512. this.mainSoundTrack.soundCollection[i].play();
  27513. }
  27514. }
  27515. for (i = 0; i < this.soundTracks.length; i++) {
  27516. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27517. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27518. this.soundTracks[i].soundCollection[j].play();
  27519. }
  27520. }
  27521. }
  27522. };
  27523. Object.defineProperty(Scene.prototype, "headphone", {
  27524. /**
  27525. * Gets or sets if audio will be output to headphones
  27526. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27527. */
  27528. get: function () {
  27529. return this._headphone;
  27530. },
  27531. set: function (value) {
  27532. this._headphone = value;
  27533. if (BABYLON.AudioEngine) {
  27534. if (this._headphone) {
  27535. this._switchAudioModeForHeadphones();
  27536. }
  27537. else {
  27538. this._switchAudioModeForNormalSpeakers();
  27539. }
  27540. }
  27541. },
  27542. enumerable: true,
  27543. configurable: true
  27544. });
  27545. Scene.prototype._switchAudioModeForHeadphones = function () {
  27546. this.mainSoundTrack.switchPanningModelToHRTF();
  27547. for (var i = 0; i < this.soundTracks.length; i++) {
  27548. this.soundTracks[i].switchPanningModelToHRTF();
  27549. }
  27550. };
  27551. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27552. this.mainSoundTrack.switchPanningModelToEqualPower();
  27553. for (var i = 0; i < this.soundTracks.length; i++) {
  27554. this.soundTracks[i].switchPanningModelToEqualPower();
  27555. }
  27556. };
  27557. /**
  27558. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27559. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27560. * @returns the created depth renderer
  27561. */
  27562. Scene.prototype.enableDepthRenderer = function (camera) {
  27563. camera = camera || this.activeCamera;
  27564. if (!camera) {
  27565. throw "No camera available to enable depth renderer";
  27566. }
  27567. if (!this._depthRenderer[camera.id]) {
  27568. var textureType = 0;
  27569. if (this._engine.getCaps().textureHalfFloatRender) {
  27570. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27571. }
  27572. else if (this._engine.getCaps().textureFloatRender) {
  27573. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27574. }
  27575. else {
  27576. throw "Depth renderer does not support int texture type";
  27577. }
  27578. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27579. }
  27580. return this._depthRenderer[camera.id];
  27581. };
  27582. /**
  27583. * Disables a depth renderer for a given camera
  27584. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27585. */
  27586. Scene.prototype.disableDepthRenderer = function (camera) {
  27587. camera = camera || this.activeCamera;
  27588. if (!camera || !this._depthRenderer[camera.id]) {
  27589. return;
  27590. }
  27591. this._depthRenderer[camera.id].dispose();
  27592. delete this._depthRenderer[camera.id];
  27593. };
  27594. /**
  27595. * Enables a GeometryBufferRender and associates it with the scene
  27596. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27597. * @returns the GeometryBufferRenderer
  27598. */
  27599. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27600. if (ratio === void 0) { ratio = 1; }
  27601. if (this._geometryBufferRenderer) {
  27602. return this._geometryBufferRenderer;
  27603. }
  27604. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27605. if (!this._geometryBufferRenderer.isSupported) {
  27606. this._geometryBufferRenderer = null;
  27607. }
  27608. return this._geometryBufferRenderer;
  27609. };
  27610. /**
  27611. * Disables the GeometryBufferRender associated with the scene
  27612. */
  27613. Scene.prototype.disableGeometryBufferRenderer = function () {
  27614. if (!this._geometryBufferRenderer) {
  27615. return;
  27616. }
  27617. this._geometryBufferRenderer.dispose();
  27618. this._geometryBufferRenderer = null;
  27619. };
  27620. /**
  27621. * Freeze all materials
  27622. * A frozen material will not be updatable but should be faster to render
  27623. */
  27624. Scene.prototype.freezeMaterials = function () {
  27625. for (var i = 0; i < this.materials.length; i++) {
  27626. this.materials[i].freeze();
  27627. }
  27628. };
  27629. /**
  27630. * Unfreeze all materials
  27631. * A frozen material will not be updatable but should be faster to render
  27632. */
  27633. Scene.prototype.unfreezeMaterials = function () {
  27634. for (var i = 0; i < this.materials.length; i++) {
  27635. this.materials[i].unfreeze();
  27636. }
  27637. };
  27638. /**
  27639. * Releases all held ressources
  27640. */
  27641. Scene.prototype.dispose = function () {
  27642. this.beforeRender = null;
  27643. this.afterRender = null;
  27644. this.skeletons = [];
  27645. this.morphTargetManagers = [];
  27646. this.importedMeshesFiles = new Array();
  27647. this.stopAllAnimations();
  27648. this.resetCachedMaterial();
  27649. for (var key in this._depthRenderer) {
  27650. this._depthRenderer[key].dispose();
  27651. }
  27652. if (this._gamepadManager) {
  27653. this._gamepadManager.dispose();
  27654. this._gamepadManager = null;
  27655. }
  27656. // Smart arrays
  27657. if (this.activeCamera) {
  27658. this.activeCamera._activeMeshes.dispose();
  27659. this.activeCamera = null;
  27660. }
  27661. this._activeMeshes.dispose();
  27662. this._renderingManager.dispose();
  27663. this._processedMaterials.dispose();
  27664. this._activeParticleSystems.dispose();
  27665. this._activeSkeletons.dispose();
  27666. this._softwareSkinnedMeshes.dispose();
  27667. this._renderTargets.dispose();
  27668. this._registeredForLateAnimationBindings.dispose();
  27669. if (this._boundingBoxRenderer) {
  27670. this._boundingBoxRenderer.dispose();
  27671. }
  27672. this._meshesForIntersections.dispose();
  27673. this._toBeDisposed.dispose();
  27674. // Abort active requests
  27675. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27676. var request = _a[_i];
  27677. request.abort();
  27678. }
  27679. // Debug layer
  27680. if (this._debugLayer) {
  27681. this._debugLayer.hide();
  27682. }
  27683. // Events
  27684. this.onDisposeObservable.notifyObservers(this);
  27685. this.onDisposeObservable.clear();
  27686. this.onBeforeRenderObservable.clear();
  27687. this.onAfterRenderObservable.clear();
  27688. this.onBeforeRenderTargetsRenderObservable.clear();
  27689. this.onAfterRenderTargetsRenderObservable.clear();
  27690. this.onAfterStepObservable.clear();
  27691. this.onBeforeStepObservable.clear();
  27692. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27693. this.onAfterActiveMeshesEvaluationObservable.clear();
  27694. this.onBeforeParticlesRenderingObservable.clear();
  27695. this.onAfterParticlesRenderingObservable.clear();
  27696. this.onBeforeSpritesRenderingObservable.clear();
  27697. this.onAfterSpritesRenderingObservable.clear();
  27698. this.onBeforeDrawPhaseObservable.clear();
  27699. this.onAfterDrawPhaseObservable.clear();
  27700. this.onBeforePhysicsObservable.clear();
  27701. this.onAfterPhysicsObservable.clear();
  27702. this.onBeforeAnimationsObservable.clear();
  27703. this.onAfterAnimationsObservable.clear();
  27704. this.onDataLoadedObservable.clear();
  27705. this.detachControl();
  27706. // Release sounds & sounds tracks
  27707. if (BABYLON.AudioEngine) {
  27708. this.disposeSounds();
  27709. }
  27710. // VR Helper
  27711. if (this.VRHelper) {
  27712. this.VRHelper.dispose();
  27713. }
  27714. // Detach cameras
  27715. var canvas = this._engine.getRenderingCanvas();
  27716. if (canvas) {
  27717. var index;
  27718. for (index = 0; index < this.cameras.length; index++) {
  27719. this.cameras[index].detachControl(canvas);
  27720. }
  27721. }
  27722. // Release animation groups
  27723. while (this.animationGroups.length) {
  27724. this.animationGroups[0].dispose();
  27725. }
  27726. // Release lights
  27727. while (this.lights.length) {
  27728. this.lights[0].dispose();
  27729. }
  27730. // Release meshes
  27731. while (this.meshes.length) {
  27732. this.meshes[0].dispose(true);
  27733. }
  27734. while (this.transformNodes.length) {
  27735. this.removeTransformNode(this.transformNodes[0]);
  27736. }
  27737. // Release cameras
  27738. while (this.cameras.length) {
  27739. this.cameras[0].dispose();
  27740. }
  27741. // Release materials
  27742. if (this.defaultMaterial) {
  27743. this.defaultMaterial.dispose();
  27744. }
  27745. while (this.multiMaterials.length) {
  27746. this.multiMaterials[0].dispose();
  27747. }
  27748. while (this.materials.length) {
  27749. this.materials[0].dispose();
  27750. }
  27751. // Release particles
  27752. while (this.particleSystems.length) {
  27753. this.particleSystems[0].dispose();
  27754. }
  27755. // Release sprites
  27756. while (this.spriteManagers.length) {
  27757. this.spriteManagers[0].dispose();
  27758. }
  27759. // Release postProcesses
  27760. while (this.postProcesses.length) {
  27761. this.postProcesses[0].dispose();
  27762. }
  27763. // Release layers
  27764. while (this.layers.length) {
  27765. this.layers[0].dispose();
  27766. }
  27767. while (this.effectLayers.length) {
  27768. this.effectLayers[0].dispose();
  27769. }
  27770. // Release textures
  27771. while (this.textures.length) {
  27772. this.textures[0].dispose();
  27773. }
  27774. // Release UBO
  27775. this._sceneUbo.dispose();
  27776. if (this._alternateSceneUbo) {
  27777. this._alternateSceneUbo.dispose();
  27778. }
  27779. // Post-processes
  27780. this.postProcessManager.dispose();
  27781. if (this._postProcessRenderPipelineManager) {
  27782. this._postProcessRenderPipelineManager.dispose();
  27783. }
  27784. // Physics
  27785. if (this._physicsEngine) {
  27786. this.disablePhysicsEngine();
  27787. }
  27788. // Remove from engine
  27789. index = this._engine.scenes.indexOf(this);
  27790. if (index > -1) {
  27791. this._engine.scenes.splice(index, 1);
  27792. }
  27793. this._engine.wipeCaches(true);
  27794. this._isDisposed = true;
  27795. };
  27796. Object.defineProperty(Scene.prototype, "isDisposed", {
  27797. /**
  27798. * Gets if the scene is already disposed
  27799. */
  27800. get: function () {
  27801. return this._isDisposed;
  27802. },
  27803. enumerable: true,
  27804. configurable: true
  27805. });
  27806. /**
  27807. * Releases sounds & soundtracks
  27808. */
  27809. Scene.prototype.disposeSounds = function () {
  27810. if (!this._mainSoundTrack) {
  27811. return;
  27812. }
  27813. this.mainSoundTrack.dispose();
  27814. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27815. this.soundTracks[scIndex].dispose();
  27816. }
  27817. };
  27818. // Octrees
  27819. /**
  27820. * Get the world extend vectors with an optional filter
  27821. *
  27822. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  27823. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  27824. */
  27825. Scene.prototype.getWorldExtends = function (filterPredicate) {
  27826. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  27827. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  27828. filterPredicate = filterPredicate || (function () { return true; });
  27829. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  27830. mesh.computeWorldMatrix(true);
  27831. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  27832. return;
  27833. }
  27834. var boundingInfo = mesh.getBoundingInfo();
  27835. var minBox = boundingInfo.boundingBox.minimumWorld;
  27836. var maxBox = boundingInfo.boundingBox.maximumWorld;
  27837. BABYLON.Tools.CheckExtends(minBox, min, max);
  27838. BABYLON.Tools.CheckExtends(maxBox, min, max);
  27839. });
  27840. return {
  27841. min: min,
  27842. max: max
  27843. };
  27844. };
  27845. /**
  27846. * Creates or updates the octree used to boost selection (picking)
  27847. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  27848. * @param maxCapacity defines the maximum capacity per leaf
  27849. * @param maxDepth defines the maximum depth of the octree
  27850. * @returns an octree of AbstractMesh
  27851. */
  27852. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  27853. if (maxCapacity === void 0) { maxCapacity = 64; }
  27854. if (maxDepth === void 0) { maxDepth = 2; }
  27855. if (!this._selectionOctree) {
  27856. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  27857. }
  27858. var worldExtends = this.getWorldExtends();
  27859. // Update octree
  27860. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  27861. return this._selectionOctree;
  27862. };
  27863. // Picking
  27864. /**
  27865. * Creates a ray that can be used to pick in the scene
  27866. * @param x defines the x coordinate of the origin (on-screen)
  27867. * @param y defines the y coordinate of the origin (on-screen)
  27868. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27869. * @param camera defines the camera to use for the picking
  27870. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27871. * @returns a Ray
  27872. */
  27873. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  27874. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27875. var result = BABYLON.Ray.Zero();
  27876. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  27877. return result;
  27878. };
  27879. /**
  27880. * Creates a ray that can be used to pick in the scene
  27881. * @param x defines the x coordinate of the origin (on-screen)
  27882. * @param y defines the y coordinate of the origin (on-screen)
  27883. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  27884. * @param result defines the ray where to store the picking ray
  27885. * @param camera defines the camera to use for the picking
  27886. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  27887. * @returns the current scene
  27888. */
  27889. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  27890. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  27891. var engine = this._engine;
  27892. if (!camera) {
  27893. if (!this.activeCamera)
  27894. throw new Error("Active camera not set");
  27895. camera = this.activeCamera;
  27896. }
  27897. var cameraViewport = camera.viewport;
  27898. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27899. // Moving coordinates to local viewport world
  27900. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27901. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27902. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  27903. return this;
  27904. };
  27905. /**
  27906. * Creates a ray that can be used to pick in the scene
  27907. * @param x defines the x coordinate of the origin (on-screen)
  27908. * @param y defines the y coordinate of the origin (on-screen)
  27909. * @param camera defines the camera to use for the picking
  27910. * @returns a Ray
  27911. */
  27912. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  27913. var result = BABYLON.Ray.Zero();
  27914. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  27915. return result;
  27916. };
  27917. /**
  27918. * Creates a ray that can be used to pick in the scene
  27919. * @param x defines the x coordinate of the origin (on-screen)
  27920. * @param y defines the y coordinate of the origin (on-screen)
  27921. * @param result defines the ray where to store the picking ray
  27922. * @param camera defines the camera to use for the picking
  27923. * @returns the current scene
  27924. */
  27925. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  27926. if (!BABYLON.PickingInfo) {
  27927. return this;
  27928. }
  27929. var engine = this._engine;
  27930. if (!camera) {
  27931. if (!this.activeCamera)
  27932. throw new Error("Active camera not set");
  27933. camera = this.activeCamera;
  27934. }
  27935. var cameraViewport = camera.viewport;
  27936. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  27937. var identity = BABYLON.Matrix.Identity();
  27938. // Moving coordinates to local viewport world
  27939. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  27940. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  27941. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  27942. return this;
  27943. };
  27944. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  27945. if (!BABYLON.PickingInfo) {
  27946. return null;
  27947. }
  27948. var pickingInfo = null;
  27949. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27950. var mesh = this.meshes[meshIndex];
  27951. if (predicate) {
  27952. if (!predicate(mesh)) {
  27953. continue;
  27954. }
  27955. }
  27956. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27957. continue;
  27958. }
  27959. var world = mesh.getWorldMatrix();
  27960. var ray = rayFunction(world);
  27961. var result = mesh.intersects(ray, fastCheck);
  27962. if (!result || !result.hit)
  27963. continue;
  27964. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  27965. continue;
  27966. pickingInfo = result;
  27967. if (fastCheck) {
  27968. break;
  27969. }
  27970. }
  27971. return pickingInfo || new BABYLON.PickingInfo();
  27972. };
  27973. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  27974. if (!BABYLON.PickingInfo) {
  27975. return null;
  27976. }
  27977. var pickingInfos = new Array();
  27978. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  27979. var mesh = this.meshes[meshIndex];
  27980. if (predicate) {
  27981. if (!predicate(mesh)) {
  27982. continue;
  27983. }
  27984. }
  27985. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  27986. continue;
  27987. }
  27988. var world = mesh.getWorldMatrix();
  27989. var ray = rayFunction(world);
  27990. var result = mesh.intersects(ray, false);
  27991. if (!result || !result.hit)
  27992. continue;
  27993. pickingInfos.push(result);
  27994. }
  27995. return pickingInfos;
  27996. };
  27997. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  27998. if (!BABYLON.PickingInfo) {
  27999. return null;
  28000. }
  28001. var pickingInfo = null;
  28002. if (!camera) {
  28003. if (!this.activeCamera) {
  28004. return null;
  28005. }
  28006. camera = this.activeCamera;
  28007. }
  28008. if (this.spriteManagers.length > 0) {
  28009. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28010. var spriteManager = this.spriteManagers[spriteIndex];
  28011. if (!spriteManager.isPickable) {
  28012. continue;
  28013. }
  28014. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28015. if (!result || !result.hit)
  28016. continue;
  28017. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28018. continue;
  28019. pickingInfo = result;
  28020. if (fastCheck) {
  28021. break;
  28022. }
  28023. }
  28024. }
  28025. return pickingInfo || new BABYLON.PickingInfo();
  28026. };
  28027. /** Launch a ray to try to pick a mesh in the scene
  28028. * @param x position on screen
  28029. * @param y position on screen
  28030. * @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
  28031. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28032. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28033. * @returns a PickingInfo
  28034. */
  28035. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28036. var _this = this;
  28037. if (!BABYLON.PickingInfo) {
  28038. return null;
  28039. }
  28040. return this._internalPick(function (world) {
  28041. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28042. return _this._tempPickingRay;
  28043. }, predicate, fastCheck);
  28044. };
  28045. /** Launch a ray to try to pick a sprite in the scene
  28046. * @param x position on screen
  28047. * @param y position on screen
  28048. * @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
  28049. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28050. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28051. * @returns a PickingInfo
  28052. */
  28053. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28054. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28055. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28056. };
  28057. /** Use the given ray to pick a mesh in the scene
  28058. * @param ray The ray to use to pick meshes
  28059. * @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
  28060. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28061. * @returns a PickingInfo
  28062. */
  28063. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28064. var _this = this;
  28065. return this._internalPick(function (world) {
  28066. if (!_this._pickWithRayInverseMatrix) {
  28067. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28068. }
  28069. world.invertToRef(_this._pickWithRayInverseMatrix);
  28070. if (!_this._cachedRayForTransform) {
  28071. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28072. }
  28073. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28074. return _this._cachedRayForTransform;
  28075. }, predicate, fastCheck);
  28076. };
  28077. /**
  28078. * Launch a ray to try to pick a mesh in the scene
  28079. * @param x X position on screen
  28080. * @param y Y position on screen
  28081. * @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
  28082. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28083. * @returns an array of PickingInfo
  28084. */
  28085. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28086. var _this = this;
  28087. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28088. };
  28089. /**
  28090. * Launch a ray to try to pick a mesh in the scene
  28091. * @param ray Ray to use
  28092. * @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
  28093. * @returns an array of PickingInfo
  28094. */
  28095. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28096. var _this = this;
  28097. return this._internalMultiPick(function (world) {
  28098. if (!_this._pickWithRayInverseMatrix) {
  28099. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28100. }
  28101. world.invertToRef(_this._pickWithRayInverseMatrix);
  28102. if (!_this._cachedRayForTransform) {
  28103. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28104. }
  28105. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28106. return _this._cachedRayForTransform;
  28107. }, predicate);
  28108. };
  28109. /**
  28110. * Force the value of meshUnderPointer
  28111. * @param mesh defines the mesh to use
  28112. */
  28113. Scene.prototype.setPointerOverMesh = function (mesh) {
  28114. if (this._pointerOverMesh === mesh) {
  28115. return;
  28116. }
  28117. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28118. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28119. }
  28120. this._pointerOverMesh = mesh;
  28121. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28122. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28123. }
  28124. };
  28125. /**
  28126. * Gets the mesh under the pointer
  28127. * @returns a Mesh or null if no mesh is under the pointer
  28128. */
  28129. Scene.prototype.getPointerOverMesh = function () {
  28130. return this._pointerOverMesh;
  28131. };
  28132. /**
  28133. * Force the sprite under the pointer
  28134. * @param sprite defines the sprite to use
  28135. */
  28136. Scene.prototype.setPointerOverSprite = function (sprite) {
  28137. if (this._pointerOverSprite === sprite) {
  28138. return;
  28139. }
  28140. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28141. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28142. }
  28143. this._pointerOverSprite = sprite;
  28144. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28145. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28146. }
  28147. };
  28148. /**
  28149. * Gets the sprite under the pointer
  28150. * @returns a Sprite or null if no sprite is under the pointer
  28151. */
  28152. Scene.prototype.getPointerOverSprite = function () {
  28153. return this._pointerOverSprite;
  28154. };
  28155. // Physics
  28156. /**
  28157. * Gets the current physics engine
  28158. * @returns a PhysicsEngine or null if none attached
  28159. */
  28160. Scene.prototype.getPhysicsEngine = function () {
  28161. return this._physicsEngine;
  28162. };
  28163. /**
  28164. * Enables physics to the current scene
  28165. * @param gravity defines the scene's gravity for the physics engine
  28166. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28167. * @return a boolean indicating if the physics engine was initialized
  28168. */
  28169. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28170. if (gravity === void 0) { gravity = null; }
  28171. if (this._physicsEngine) {
  28172. return true;
  28173. }
  28174. try {
  28175. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28176. return true;
  28177. }
  28178. catch (e) {
  28179. BABYLON.Tools.Error(e.message);
  28180. return false;
  28181. }
  28182. };
  28183. /**
  28184. * Disables and disposes the physics engine associated with the scene
  28185. */
  28186. Scene.prototype.disablePhysicsEngine = function () {
  28187. if (!this._physicsEngine) {
  28188. return;
  28189. }
  28190. this._physicsEngine.dispose();
  28191. this._physicsEngine = null;
  28192. };
  28193. /**
  28194. * Gets a boolean indicating if there is an active physics engine
  28195. * @returns a boolean indicating if there is an active physics engine
  28196. */
  28197. Scene.prototype.isPhysicsEnabled = function () {
  28198. return this._physicsEngine !== undefined;
  28199. };
  28200. /**
  28201. * Deletes a physics compound impostor
  28202. * @param compound defines the compound to delete
  28203. */
  28204. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28205. var mesh = compound.parts[0].mesh;
  28206. if (mesh.physicsImpostor) {
  28207. mesh.physicsImpostor.dispose( /*true*/);
  28208. mesh.physicsImpostor = null;
  28209. }
  28210. };
  28211. // Misc.
  28212. /** @ignore */
  28213. Scene.prototype._rebuildGeometries = function () {
  28214. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28215. var geometry = _a[_i];
  28216. geometry._rebuild();
  28217. }
  28218. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28219. var mesh = _c[_b];
  28220. mesh._rebuild();
  28221. }
  28222. if (this.postProcessManager) {
  28223. this.postProcessManager._rebuild();
  28224. }
  28225. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28226. var layer = _e[_d];
  28227. layer._rebuild();
  28228. }
  28229. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28230. var effectLayer = _g[_f];
  28231. effectLayer._rebuild();
  28232. }
  28233. if (this._boundingBoxRenderer) {
  28234. this._boundingBoxRenderer._rebuild();
  28235. }
  28236. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28237. var system = _j[_h];
  28238. system.rebuild();
  28239. }
  28240. if (this._postProcessRenderPipelineManager) {
  28241. this._postProcessRenderPipelineManager._rebuild();
  28242. }
  28243. };
  28244. /** @ignore */
  28245. Scene.prototype._rebuildTextures = function () {
  28246. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28247. var texture = _a[_i];
  28248. texture._rebuild();
  28249. }
  28250. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28251. };
  28252. /**
  28253. * Creates a default light for the scene.
  28254. * @param replace Whether to replace the existing lights in the scene.
  28255. */
  28256. Scene.prototype.createDefaultLight = function (replace) {
  28257. if (replace === void 0) { replace = false; }
  28258. // Dispose existing light in replace mode.
  28259. if (replace) {
  28260. if (this.lights) {
  28261. for (var i = 0; i < this.lights.length; i++) {
  28262. this.lights[i].dispose();
  28263. }
  28264. }
  28265. }
  28266. // Light
  28267. if (this.lights.length === 0) {
  28268. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28269. }
  28270. };
  28271. /**
  28272. * Creates a default camera for the scene.
  28273. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28274. * @param replace Whether to replace the existing active camera in the scene.
  28275. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28276. */
  28277. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28278. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28279. if (replace === void 0) { replace = false; }
  28280. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28281. // Dispose existing camera in replace mode.
  28282. if (replace) {
  28283. if (this.activeCamera) {
  28284. this.activeCamera.dispose();
  28285. this.activeCamera = null;
  28286. }
  28287. }
  28288. // Camera
  28289. if (!this.activeCamera) {
  28290. var worldExtends = this.getWorldExtends();
  28291. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28292. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28293. var camera;
  28294. var radius = worldSize.length() * 1.5;
  28295. // empty scene scenario!
  28296. if (!isFinite(radius)) {
  28297. radius = 1;
  28298. worldCenter.copyFromFloats(0, 0, 0);
  28299. }
  28300. if (createArcRotateCamera) {
  28301. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28302. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28303. arcRotateCamera.wheelPrecision = 100 / radius;
  28304. camera = arcRotateCamera;
  28305. }
  28306. else {
  28307. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28308. freeCamera.setTarget(worldCenter);
  28309. camera = freeCamera;
  28310. }
  28311. camera.minZ = radius * 0.01;
  28312. camera.maxZ = radius * 1000;
  28313. camera.speed = radius * 0.2;
  28314. this.activeCamera = camera;
  28315. var canvas = this.getEngine().getRenderingCanvas();
  28316. if (attachCameraControls && canvas) {
  28317. camera.attachControl(canvas);
  28318. }
  28319. }
  28320. };
  28321. /**
  28322. * Creates a default camera and a default light
  28323. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28324. * @param replace defines if the camera and/or light will replace the existing ones
  28325. * @param attachCameraControls defines if attachControl will be called on the new camera
  28326. */
  28327. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28328. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28329. if (replace === void 0) { replace = false; }
  28330. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28331. this.createDefaultLight(replace);
  28332. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28333. };
  28334. /**
  28335. * Creates a new sky box
  28336. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28337. * @param environmentTexture defines the texture to use as environment texture
  28338. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28339. * @param scale defines the overall scale of the skybox
  28340. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28341. * @returns a new mesh holding the sky box
  28342. */
  28343. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  28344. if (pbr === void 0) { pbr = false; }
  28345. if (scale === void 0) { scale = 1000; }
  28346. if (blur === void 0) { blur = 0; }
  28347. if (environmentTexture) {
  28348. this.environmentTexture = environmentTexture;
  28349. }
  28350. if (!this.environmentTexture) {
  28351. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28352. return null;
  28353. }
  28354. // Skybox
  28355. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28356. if (pbr) {
  28357. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28358. hdrSkyboxMaterial.backFaceCulling = false;
  28359. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28360. if (hdrSkyboxMaterial.reflectionTexture) {
  28361. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28362. }
  28363. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28364. hdrSkyboxMaterial.disableLighting = true;
  28365. hdrSkyboxMaterial.twoSidedLighting = true;
  28366. hdrSkybox.infiniteDistance = true;
  28367. hdrSkybox.material = hdrSkyboxMaterial;
  28368. }
  28369. else {
  28370. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28371. skyboxMaterial.backFaceCulling = false;
  28372. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  28373. if (skyboxMaterial.reflectionTexture) {
  28374. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28375. }
  28376. skyboxMaterial.disableLighting = true;
  28377. hdrSkybox.infiniteDistance = true;
  28378. hdrSkybox.material = skyboxMaterial;
  28379. }
  28380. return hdrSkybox;
  28381. };
  28382. /**
  28383. * Creates a new environment
  28384. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28385. * @param options defines the options you can use to configure the environment
  28386. * @returns the new EnvironmentHelper
  28387. */
  28388. Scene.prototype.createDefaultEnvironment = function (options) {
  28389. if (BABYLON.EnvironmentHelper) {
  28390. return new BABYLON.EnvironmentHelper(options, this);
  28391. }
  28392. return null;
  28393. };
  28394. /**
  28395. * Creates a new VREXperienceHelper
  28396. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28397. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28398. * @returns a new VREXperienceHelper
  28399. */
  28400. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28401. if (webVROptions === void 0) { webVROptions = {}; }
  28402. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28403. };
  28404. // Tags
  28405. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28406. if (tagsQuery === undefined) {
  28407. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28408. return list;
  28409. }
  28410. var listByTags = [];
  28411. forEach = forEach || (function (item) { return; });
  28412. for (var i in list) {
  28413. var item = list[i];
  28414. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28415. listByTags.push(item);
  28416. forEach(item);
  28417. }
  28418. }
  28419. return listByTags;
  28420. };
  28421. /**
  28422. * Get a list of meshes by tags
  28423. * @param tagsQuery defines the tags query to use
  28424. * @param forEach defines a predicate used to filter results
  28425. * @returns an array of Mesh
  28426. */
  28427. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28428. return this._getByTags(this.meshes, tagsQuery, forEach);
  28429. };
  28430. /**
  28431. * Get a list of cameras by tags
  28432. * @param tagsQuery defines the tags query to use
  28433. * @param forEach defines a predicate used to filter results
  28434. * @returns an array of Camera
  28435. */
  28436. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28437. return this._getByTags(this.cameras, tagsQuery, forEach);
  28438. };
  28439. /**
  28440. * Get a list of lights by tags
  28441. * @param tagsQuery defines the tags query to use
  28442. * @param forEach defines a predicate used to filter results
  28443. * @returns an array of Light
  28444. */
  28445. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28446. return this._getByTags(this.lights, tagsQuery, forEach);
  28447. };
  28448. /**
  28449. * Get a list of materials by tags
  28450. * @param tagsQuery defines the tags query to use
  28451. * @param forEach defines a predicate used to filter results
  28452. * @returns an array of Material
  28453. */
  28454. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28455. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28456. };
  28457. /**
  28458. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28459. * This allowed control for front to back rendering or reversly depending of the special needs.
  28460. *
  28461. * @param renderingGroupId The rendering group id corresponding to its index
  28462. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28463. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28464. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28465. */
  28466. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28467. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28468. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28469. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28470. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28471. };
  28472. /**
  28473. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28474. *
  28475. * @param renderingGroupId The rendering group id corresponding to its index
  28476. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28477. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28478. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28479. */
  28480. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28481. if (depth === void 0) { depth = true; }
  28482. if (stencil === void 0) { stencil = true; }
  28483. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28484. };
  28485. /**
  28486. * Will flag all materials as dirty to trigger new shader compilation
  28487. * @param flag defines the flag used to specify which material part must be marked as dirty
  28488. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28489. */
  28490. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28491. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28492. var material = _a[_i];
  28493. if (predicate && !predicate(material)) {
  28494. continue;
  28495. }
  28496. material.markAsDirty(flag);
  28497. }
  28498. };
  28499. /** @ignore */
  28500. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28501. var _this = this;
  28502. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28503. this._activeRequests.push(request);
  28504. request.onCompleteObservable.add(function (request) {
  28505. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28506. });
  28507. return request;
  28508. };
  28509. /** @ignore */
  28510. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28511. var _this = this;
  28512. return new Promise(function (resolve, reject) {
  28513. _this._loadFile(url, function (data) {
  28514. resolve(data);
  28515. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28516. reject(exception);
  28517. });
  28518. });
  28519. };
  28520. // Statics
  28521. Scene._FOGMODE_NONE = 0;
  28522. Scene._FOGMODE_EXP = 1;
  28523. Scene._FOGMODE_EXP2 = 2;
  28524. Scene._FOGMODE_LINEAR = 3;
  28525. Scene._uniqueIdCounter = 0;
  28526. /**
  28527. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28528. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28529. */
  28530. Scene.MinDeltaTime = 1.0;
  28531. /**
  28532. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28533. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28534. */
  28535. Scene.MaxDeltaTime = 1000.0;
  28536. /** The distance in pixel that you have to move to prevent some events */
  28537. Scene.DragMovementThreshold = 10; // in pixels
  28538. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28539. Scene.LongPressDelay = 500; // in milliseconds
  28540. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28541. Scene.DoubleClickDelay = 300; // in milliseconds
  28542. /** If you need to check double click without raising a single click at first click, enable this flag */
  28543. Scene.ExclusiveDoubleClickMode = false;
  28544. return Scene;
  28545. }());
  28546. BABYLON.Scene = Scene;
  28547. })(BABYLON || (BABYLON = {}));
  28548. //# sourceMappingURL=babylon.scene.js.map
  28549. var BABYLON;
  28550. (function (BABYLON) {
  28551. /**
  28552. * Set of assets to keep when moving a scene into an asset container.
  28553. */
  28554. var KeepAssets = /** @class */ (function () {
  28555. function KeepAssets() {
  28556. /**
  28557. * Cameras to keep.
  28558. */
  28559. this.cameras = new Array();
  28560. /**
  28561. * Lights to keep.
  28562. */
  28563. this.lights = new Array();
  28564. /**
  28565. * Meshes to keep.
  28566. */
  28567. this.meshes = new Array();
  28568. /**
  28569. * Skeletons to keep.
  28570. */
  28571. this.skeletons = new Array();
  28572. /**
  28573. * ParticleSystems to keep.
  28574. */
  28575. this.particleSystems = new Array();
  28576. /**
  28577. * Animations to keep.
  28578. */
  28579. this.animations = new Array();
  28580. /**
  28581. * AnimationGroups to keep.
  28582. */
  28583. this.animationGroups = new Array();
  28584. /**
  28585. * MultiMaterials to keep.
  28586. */
  28587. this.multiMaterials = new Array();
  28588. /**
  28589. * Materials to keep.
  28590. */
  28591. this.materials = new Array();
  28592. /**
  28593. * MorphTargetManagers to keep.
  28594. */
  28595. this.morphTargetManagers = new Array();
  28596. /**
  28597. * Geometries to keep.
  28598. */
  28599. this.geometries = new Array();
  28600. /**
  28601. * TransformNodes to keep.
  28602. */
  28603. this.transformNodes = new Array();
  28604. /**
  28605. * LensFlareSystems to keep.
  28606. */
  28607. this.lensFlareSystems = new Array();
  28608. /**
  28609. * ShadowGenerators to keep.
  28610. */
  28611. this.shadowGenerators = new Array();
  28612. /**
  28613. * ActionManagers to keep.
  28614. */
  28615. this.actionManagers = new Array();
  28616. /**
  28617. * Sounds to keep.
  28618. */
  28619. this.sounds = new Array();
  28620. /**
  28621. * Textures to keep.
  28622. */
  28623. this.textures = new Array();
  28624. /**
  28625. * Effect layers to keep.
  28626. */
  28627. this.effectLayers = new Array();
  28628. }
  28629. return KeepAssets;
  28630. }());
  28631. BABYLON.KeepAssets = KeepAssets;
  28632. /**
  28633. * Container with a set of assets that can be added or removed from a scene.
  28634. */
  28635. var AssetContainer = /** @class */ (function () {
  28636. /**
  28637. * Instantiates an AssetContainer.
  28638. * @param scene The scene the AssetContainer belongs to.
  28639. */
  28640. function AssetContainer(scene) {
  28641. // Objects
  28642. /**
  28643. * Cameras populated in the container.
  28644. */
  28645. this.cameras = new Array();
  28646. /**
  28647. * Lights populated in the container.
  28648. */
  28649. this.lights = new Array();
  28650. /**
  28651. * Meshes populated in the container.
  28652. */
  28653. this.meshes = new Array();
  28654. /**
  28655. * Skeletons populated in the container.
  28656. */
  28657. this.skeletons = new Array();
  28658. /**
  28659. * ParticleSystems populated in the container.
  28660. */
  28661. this.particleSystems = new Array();
  28662. /**
  28663. * Animations populated in the container.
  28664. */
  28665. this.animations = new Array();
  28666. /**
  28667. * AnimationGroups populated in the container.
  28668. */
  28669. this.animationGroups = new Array();
  28670. /**
  28671. * MultiMaterials populated in the container.
  28672. */
  28673. this.multiMaterials = new Array();
  28674. /**
  28675. * Materials populated in the container.
  28676. */
  28677. this.materials = new Array();
  28678. /**
  28679. * MorphTargetManagers populated in the container.
  28680. */
  28681. this.morphTargetManagers = new Array();
  28682. /**
  28683. * Geometries populated in the container.
  28684. */
  28685. this.geometries = new Array();
  28686. /**
  28687. * TransformNodes populated in the container.
  28688. */
  28689. this.transformNodes = new Array();
  28690. /**
  28691. * LensFlareSystems populated in the container.
  28692. */
  28693. this.lensFlareSystems = new Array();
  28694. /**
  28695. * ShadowGenerators populated in the container.
  28696. */
  28697. this.shadowGenerators = new Array();
  28698. /**
  28699. * ActionManagers populated in the container.
  28700. */
  28701. this.actionManagers = new Array();
  28702. /**
  28703. * Sounds populated in the container.
  28704. */
  28705. this.sounds = new Array();
  28706. /**
  28707. * Textures populated in the container.
  28708. */
  28709. this.textures = new Array();
  28710. /**
  28711. * Effect layers populated in the container.
  28712. */
  28713. this.effectLayers = new Array();
  28714. this.scene = scene;
  28715. }
  28716. /**
  28717. * Adds all the assets from the container to the scene.
  28718. */
  28719. AssetContainer.prototype.addAllToScene = function () {
  28720. var _this = this;
  28721. this.cameras.forEach(function (o) {
  28722. _this.scene.addCamera(o);
  28723. });
  28724. this.lights.forEach(function (o) {
  28725. _this.scene.addLight(o);
  28726. });
  28727. this.meshes.forEach(function (o) {
  28728. _this.scene.addMesh(o);
  28729. });
  28730. this.skeletons.forEach(function (o) {
  28731. _this.scene.addSkeleton(o);
  28732. });
  28733. this.particleSystems.forEach(function (o) {
  28734. _this.scene.addParticleSystem(o);
  28735. });
  28736. this.animations.forEach(function (o) {
  28737. _this.scene.addAnimation(o);
  28738. });
  28739. this.animationGroups.forEach(function (o) {
  28740. _this.scene.addAnimationGroup(o);
  28741. });
  28742. this.multiMaterials.forEach(function (o) {
  28743. _this.scene.addMultiMaterial(o);
  28744. });
  28745. this.materials.forEach(function (o) {
  28746. _this.scene.addMaterial(o);
  28747. });
  28748. this.morphTargetManagers.forEach(function (o) {
  28749. _this.scene.addMorphTargetManager(o);
  28750. });
  28751. this.geometries.forEach(function (o) {
  28752. _this.scene.addGeometry(o);
  28753. });
  28754. this.transformNodes.forEach(function (o) {
  28755. _this.scene.addTransformNode(o);
  28756. });
  28757. this.lensFlareSystems.forEach(function (o) {
  28758. _this.scene.addLensFlareSystem(o);
  28759. });
  28760. this.actionManagers.forEach(function (o) {
  28761. _this.scene.addActionManager(o);
  28762. });
  28763. this.sounds.forEach(function (o) {
  28764. o.play();
  28765. o.autoplay = true;
  28766. _this.scene.mainSoundTrack.AddSound(o);
  28767. });
  28768. this.textures.forEach(function (o) {
  28769. _this.scene.addTexture(o);
  28770. });
  28771. this.effectLayers.forEach(function (o) {
  28772. _this.scene.addEffectLayer(o);
  28773. });
  28774. };
  28775. /**
  28776. * Removes all the assets in the container from the scene
  28777. */
  28778. AssetContainer.prototype.removeAllFromScene = function () {
  28779. var _this = this;
  28780. this.cameras.forEach(function (o) {
  28781. _this.scene.removeCamera(o);
  28782. });
  28783. this.lights.forEach(function (o) {
  28784. _this.scene.removeLight(o);
  28785. });
  28786. this.meshes.forEach(function (o) {
  28787. _this.scene.removeMesh(o);
  28788. });
  28789. this.skeletons.forEach(function (o) {
  28790. _this.scene.removeSkeleton(o);
  28791. });
  28792. this.particleSystems.forEach(function (o) {
  28793. _this.scene.removeParticleSystem(o);
  28794. });
  28795. this.animations.forEach(function (o) {
  28796. _this.scene.removeAnimation(o);
  28797. });
  28798. this.animationGroups.forEach(function (o) {
  28799. _this.scene.removeAnimationGroup(o);
  28800. });
  28801. this.multiMaterials.forEach(function (o) {
  28802. _this.scene.removeMultiMaterial(o);
  28803. });
  28804. this.materials.forEach(function (o) {
  28805. _this.scene.removeMaterial(o);
  28806. });
  28807. this.morphTargetManagers.forEach(function (o) {
  28808. _this.scene.removeMorphTargetManager(o);
  28809. });
  28810. this.geometries.forEach(function (o) {
  28811. _this.scene.removeGeometry(o);
  28812. });
  28813. this.transformNodes.forEach(function (o) {
  28814. _this.scene.removeTransformNode(o);
  28815. });
  28816. this.lensFlareSystems.forEach(function (o) {
  28817. _this.scene.removeLensFlareSystem(o);
  28818. });
  28819. this.actionManagers.forEach(function (o) {
  28820. _this.scene.removeActionManager(o);
  28821. });
  28822. this.sounds.forEach(function (o) {
  28823. o.stop();
  28824. o.autoplay = false;
  28825. _this.scene.mainSoundTrack.RemoveSound(o);
  28826. });
  28827. this.textures.forEach(function (o) {
  28828. _this.scene.removeTexture(o);
  28829. });
  28830. this.effectLayers.forEach(function (o) {
  28831. _this.scene.removeEffectLayer(o);
  28832. });
  28833. };
  28834. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  28835. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  28836. var asset = sourceAssets_1[_i];
  28837. var move = true;
  28838. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  28839. var keepAsset = keepAssets_1[_a];
  28840. if (asset === keepAsset) {
  28841. move = false;
  28842. break;
  28843. }
  28844. }
  28845. if (move) {
  28846. targetAssets.push(asset);
  28847. }
  28848. }
  28849. };
  28850. /**
  28851. * Removes all the assets contained in the scene and adds them to the container.
  28852. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  28853. */
  28854. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  28855. if (keepAssets === undefined) {
  28856. keepAssets = new KeepAssets();
  28857. }
  28858. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  28859. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  28860. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  28861. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  28862. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  28863. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  28864. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  28865. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  28866. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  28867. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  28868. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  28869. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  28870. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  28871. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  28872. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  28873. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  28874. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  28875. this.removeAllFromScene();
  28876. };
  28877. return AssetContainer;
  28878. }());
  28879. BABYLON.AssetContainer = AssetContainer;
  28880. })(BABYLON || (BABYLON = {}));
  28881. //# sourceMappingURL=babylon.assetContainer.js.map
  28882. var BABYLON;
  28883. (function (BABYLON) {
  28884. var Buffer = /** @class */ (function () {
  28885. /**
  28886. * Constructor
  28887. * @param engine the engine
  28888. * @param data the data to use for this buffer
  28889. * @param updatable whether the data is updatable
  28890. * @param stride the stride (optional)
  28891. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  28892. * @param instanced whether the buffer is instanced (optional)
  28893. * @param useBytes set to true if the stride in in bytes (optional)
  28894. */
  28895. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  28896. if (stride === void 0) { stride = 0; }
  28897. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  28898. if (instanced === void 0) { instanced = false; }
  28899. if (useBytes === void 0) { useBytes = false; }
  28900. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  28901. this._engine = engine.getScene().getEngine();
  28902. }
  28903. else {
  28904. this._engine = engine;
  28905. }
  28906. this._updatable = updatable;
  28907. this._instanced = instanced;
  28908. this._data = data;
  28909. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  28910. if (!postponeInternalCreation) { // by default
  28911. this.create();
  28912. }
  28913. }
  28914. /**
  28915. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  28916. * @param kind defines the vertex buffer kind (position, normal, etc.)
  28917. * @param offset defines offset in the buffer (0 by default)
  28918. * @param size defines the size in floats of attributes (position is 3 for instance)
  28919. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  28920. * @param instanced defines if the vertex buffer contains indexed data
  28921. * @param useBytes defines if the offset and stride are in bytes
  28922. * @returns the new vertex buffer
  28923. */
  28924. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  28925. if (useBytes === void 0) { useBytes = false; }
  28926. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  28927. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  28928. // a lot of these parameters are ignored as they are overriden by the buffer
  28929. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  28930. };
  28931. // Properties
  28932. Buffer.prototype.isUpdatable = function () {
  28933. return this._updatable;
  28934. };
  28935. Buffer.prototype.getData = function () {
  28936. return this._data;
  28937. };
  28938. Buffer.prototype.getBuffer = function () {
  28939. return this._buffer;
  28940. };
  28941. /**
  28942. * Gets the stride in float32 units (i.e. byte stride / 4).
  28943. * May not be an integer if the byte stride is not divisible by 4.
  28944. * DEPRECATED. Use byteStride instead.
  28945. * @returns the stride in float32 units
  28946. */
  28947. Buffer.prototype.getStrideSize = function () {
  28948. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  28949. };
  28950. // Methods
  28951. Buffer.prototype.create = function (data) {
  28952. if (data === void 0) { data = null; }
  28953. if (!data && this._buffer) {
  28954. return; // nothing to do
  28955. }
  28956. data = data || this._data;
  28957. if (!data) {
  28958. return;
  28959. }
  28960. if (!this._buffer) { // create buffer
  28961. if (this._updatable) {
  28962. this._buffer = this._engine.createDynamicVertexBuffer(data);
  28963. this._data = data;
  28964. }
  28965. else {
  28966. this._buffer = this._engine.createVertexBuffer(data);
  28967. }
  28968. }
  28969. else if (this._updatable) { // update buffer
  28970. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  28971. this._data = data;
  28972. }
  28973. };
  28974. Buffer.prototype._rebuild = function () {
  28975. this._buffer = null;
  28976. this.create(this._data);
  28977. };
  28978. Buffer.prototype.update = function (data) {
  28979. this.create(data);
  28980. };
  28981. /**
  28982. * Updates the data directly.
  28983. * @param data the new data
  28984. * @param offset the new offset
  28985. * @param vertexCount the vertex count (optional)
  28986. * @param useBytes set to true if the offset is in bytes
  28987. */
  28988. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  28989. if (useBytes === void 0) { useBytes = false; }
  28990. if (!this._buffer) {
  28991. return;
  28992. }
  28993. if (this._updatable) { // update buffer
  28994. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  28995. this._data = null;
  28996. }
  28997. };
  28998. Buffer.prototype.dispose = function () {
  28999. if (!this._buffer) {
  29000. return;
  29001. }
  29002. if (this._engine._releaseBuffer(this._buffer)) {
  29003. this._buffer = null;
  29004. }
  29005. };
  29006. return Buffer;
  29007. }());
  29008. BABYLON.Buffer = Buffer;
  29009. })(BABYLON || (BABYLON = {}));
  29010. //# sourceMappingURL=babylon.buffer.js.map
  29011. var BABYLON;
  29012. (function (BABYLON) {
  29013. var VertexBuffer = /** @class */ (function () {
  29014. /**
  29015. * Constructor
  29016. * @param engine the engine
  29017. * @param data the data to use for this vertex buffer
  29018. * @param kind the vertex buffer kind
  29019. * @param updatable whether the data is updatable
  29020. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29021. * @param stride the stride (optional)
  29022. * @param instanced whether the buffer is instanced (optional)
  29023. * @param offset the offset of the data (optional)
  29024. * @param size the number of components (optional)
  29025. * @param type the type of the component (optional)
  29026. * @param normalized whether the data contains normalized data (optional)
  29027. * @param useBytes set to true if stride and offset are in bytes (optional)
  29028. */
  29029. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29030. if (normalized === void 0) { normalized = false; }
  29031. if (useBytes === void 0) { useBytes = false; }
  29032. if (data instanceof BABYLON.Buffer) {
  29033. this._buffer = data;
  29034. this._ownsBuffer = false;
  29035. }
  29036. else {
  29037. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29038. this._ownsBuffer = true;
  29039. }
  29040. this._kind = kind;
  29041. if (type == undefined) {
  29042. var data_1 = this.getData();
  29043. this.type = VertexBuffer.FLOAT;
  29044. if (data_1 instanceof Int8Array)
  29045. this.type = VertexBuffer.BYTE;
  29046. else if (data_1 instanceof Uint8Array)
  29047. this.type = VertexBuffer.UNSIGNED_BYTE;
  29048. else if (data_1 instanceof Int16Array)
  29049. this.type = VertexBuffer.SHORT;
  29050. else if (data_1 instanceof Uint16Array)
  29051. this.type = VertexBuffer.UNSIGNED_SHORT;
  29052. else if (data_1 instanceof Int32Array)
  29053. this.type = VertexBuffer.INT;
  29054. else if (data_1 instanceof Uint32Array)
  29055. this.type = VertexBuffer.UNSIGNED_INT;
  29056. }
  29057. else {
  29058. this.type = type;
  29059. }
  29060. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29061. if (useBytes) {
  29062. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29063. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29064. this.byteOffset = offset || 0;
  29065. }
  29066. else {
  29067. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29068. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29069. this.byteOffset = (offset || 0) * typeByteLength;
  29070. }
  29071. this.normalized = normalized;
  29072. this._instanced = instanced !== undefined ? instanced : false;
  29073. this._instanceDivisor = instanced ? 1 : 0;
  29074. }
  29075. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29076. /**
  29077. * Gets or sets the instance divisor when in instanced mode
  29078. */
  29079. get: function () {
  29080. return this._instanceDivisor;
  29081. },
  29082. set: function (value) {
  29083. this._instanceDivisor = value;
  29084. if (value == 0) {
  29085. this._instanced = false;
  29086. }
  29087. else {
  29088. this._instanced = true;
  29089. }
  29090. },
  29091. enumerable: true,
  29092. configurable: true
  29093. });
  29094. VertexBuffer.prototype._rebuild = function () {
  29095. if (!this._buffer) {
  29096. return;
  29097. }
  29098. this._buffer._rebuild();
  29099. };
  29100. /**
  29101. * Returns the kind of the VertexBuffer (string).
  29102. */
  29103. VertexBuffer.prototype.getKind = function () {
  29104. return this._kind;
  29105. };
  29106. // Properties
  29107. /**
  29108. * Boolean : is the VertexBuffer updatable ?
  29109. */
  29110. VertexBuffer.prototype.isUpdatable = function () {
  29111. return this._buffer.isUpdatable();
  29112. };
  29113. /**
  29114. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29115. */
  29116. VertexBuffer.prototype.getData = function () {
  29117. return this._buffer.getData();
  29118. };
  29119. /**
  29120. * Returns the WebGLBuffer associated to the VertexBuffer.
  29121. */
  29122. VertexBuffer.prototype.getBuffer = function () {
  29123. return this._buffer.getBuffer();
  29124. };
  29125. /**
  29126. * Returns the stride as a multiple of the type byte length.
  29127. * DEPRECATED. Use byteStride instead.
  29128. */
  29129. VertexBuffer.prototype.getStrideSize = function () {
  29130. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29131. };
  29132. /**
  29133. * Returns the offset as a multiple of the type byte length.
  29134. * DEPRECATED. Use byteOffset instead.
  29135. */
  29136. VertexBuffer.prototype.getOffset = function () {
  29137. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29138. };
  29139. /**
  29140. * Returns the number of components per vertex attribute (integer).
  29141. */
  29142. VertexBuffer.prototype.getSize = function () {
  29143. return this._size;
  29144. };
  29145. /**
  29146. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29147. */
  29148. VertexBuffer.prototype.getIsInstanced = function () {
  29149. return this._instanced;
  29150. };
  29151. /**
  29152. * Returns the instancing divisor, zero for non-instanced (integer).
  29153. */
  29154. VertexBuffer.prototype.getInstanceDivisor = function () {
  29155. return this._instanceDivisor;
  29156. };
  29157. // Methods
  29158. /**
  29159. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29160. * Returns the created WebGLBuffer.
  29161. */
  29162. VertexBuffer.prototype.create = function (data) {
  29163. return this._buffer.create(data);
  29164. };
  29165. /**
  29166. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29167. * This function will create a new buffer if the current one is not updatable
  29168. * Returns the updated WebGLBuffer.
  29169. */
  29170. VertexBuffer.prototype.update = function (data) {
  29171. return this._buffer.update(data);
  29172. };
  29173. /**
  29174. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29175. * Returns the directly updated WebGLBuffer.
  29176. * @param data the new data
  29177. * @param offset the new offset
  29178. * @param useBytes set to true if the offset is in bytes
  29179. */
  29180. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29181. if (useBytes === void 0) { useBytes = false; }
  29182. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29183. };
  29184. /**
  29185. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29186. */
  29187. VertexBuffer.prototype.dispose = function () {
  29188. if (this._ownsBuffer) {
  29189. this._buffer.dispose();
  29190. }
  29191. };
  29192. /**
  29193. * Enumerates each value of this vertex buffer as numbers.
  29194. * @param count the number of values to enumerate
  29195. * @param callback the callback function called for each value
  29196. */
  29197. VertexBuffer.prototype.forEach = function (count, callback) {
  29198. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29199. };
  29200. Object.defineProperty(VertexBuffer, "PositionKind", {
  29201. get: function () {
  29202. return VertexBuffer._PositionKind;
  29203. },
  29204. enumerable: true,
  29205. configurable: true
  29206. });
  29207. Object.defineProperty(VertexBuffer, "NormalKind", {
  29208. get: function () {
  29209. return VertexBuffer._NormalKind;
  29210. },
  29211. enumerable: true,
  29212. configurable: true
  29213. });
  29214. Object.defineProperty(VertexBuffer, "TangentKind", {
  29215. get: function () {
  29216. return VertexBuffer._TangentKind;
  29217. },
  29218. enumerable: true,
  29219. configurable: true
  29220. });
  29221. Object.defineProperty(VertexBuffer, "UVKind", {
  29222. get: function () {
  29223. return VertexBuffer._UVKind;
  29224. },
  29225. enumerable: true,
  29226. configurable: true
  29227. });
  29228. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29229. get: function () {
  29230. return VertexBuffer._UV2Kind;
  29231. },
  29232. enumerable: true,
  29233. configurable: true
  29234. });
  29235. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29236. get: function () {
  29237. return VertexBuffer._UV3Kind;
  29238. },
  29239. enumerable: true,
  29240. configurable: true
  29241. });
  29242. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29243. get: function () {
  29244. return VertexBuffer._UV4Kind;
  29245. },
  29246. enumerable: true,
  29247. configurable: true
  29248. });
  29249. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29250. get: function () {
  29251. return VertexBuffer._UV5Kind;
  29252. },
  29253. enumerable: true,
  29254. configurable: true
  29255. });
  29256. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29257. get: function () {
  29258. return VertexBuffer._UV6Kind;
  29259. },
  29260. enumerable: true,
  29261. configurable: true
  29262. });
  29263. Object.defineProperty(VertexBuffer, "ColorKind", {
  29264. get: function () {
  29265. return VertexBuffer._ColorKind;
  29266. },
  29267. enumerable: true,
  29268. configurable: true
  29269. });
  29270. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29271. get: function () {
  29272. return VertexBuffer._MatricesIndicesKind;
  29273. },
  29274. enumerable: true,
  29275. configurable: true
  29276. });
  29277. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29278. get: function () {
  29279. return VertexBuffer._MatricesWeightsKind;
  29280. },
  29281. enumerable: true,
  29282. configurable: true
  29283. });
  29284. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29285. get: function () {
  29286. return VertexBuffer._MatricesIndicesExtraKind;
  29287. },
  29288. enumerable: true,
  29289. configurable: true
  29290. });
  29291. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29292. get: function () {
  29293. return VertexBuffer._MatricesWeightsExtraKind;
  29294. },
  29295. enumerable: true,
  29296. configurable: true
  29297. });
  29298. /**
  29299. * Deduces the stride given a kind.
  29300. * @param kind The kind string to deduce
  29301. * @returns The deduced stride
  29302. */
  29303. VertexBuffer.DeduceStride = function (kind) {
  29304. switch (kind) {
  29305. case VertexBuffer.UVKind:
  29306. case VertexBuffer.UV2Kind:
  29307. case VertexBuffer.UV3Kind:
  29308. case VertexBuffer.UV4Kind:
  29309. case VertexBuffer.UV5Kind:
  29310. case VertexBuffer.UV6Kind:
  29311. return 2;
  29312. case VertexBuffer.NormalKind:
  29313. case VertexBuffer.PositionKind:
  29314. return 3;
  29315. case VertexBuffer.ColorKind:
  29316. case VertexBuffer.MatricesIndicesKind:
  29317. case VertexBuffer.MatricesIndicesExtraKind:
  29318. case VertexBuffer.MatricesWeightsKind:
  29319. case VertexBuffer.MatricesWeightsExtraKind:
  29320. case VertexBuffer.TangentKind:
  29321. return 4;
  29322. default:
  29323. throw new Error("Invalid kind '" + kind + "'");
  29324. }
  29325. };
  29326. /**
  29327. * Gets the byte length of the given type.
  29328. * @param type the type
  29329. * @returns the number of bytes
  29330. */
  29331. VertexBuffer.GetTypeByteLength = function (type) {
  29332. switch (type) {
  29333. case VertexBuffer.BYTE:
  29334. case VertexBuffer.UNSIGNED_BYTE:
  29335. return 1;
  29336. case VertexBuffer.SHORT:
  29337. case VertexBuffer.UNSIGNED_SHORT:
  29338. return 2;
  29339. case VertexBuffer.INT:
  29340. case VertexBuffer.FLOAT:
  29341. return 4;
  29342. default:
  29343. throw new Error("Invalid type '" + type + "'");
  29344. }
  29345. };
  29346. /**
  29347. * Enumerates each value of the given parameters as numbers.
  29348. * @param data the data to enumerate
  29349. * @param byteOffset the byte offset of the data
  29350. * @param byteStride the byte stride of the data
  29351. * @param componentCount the number of components per element
  29352. * @param componentType the type of the component
  29353. * @param count the total number of components
  29354. * @param normalized whether the data is normalized
  29355. * @param callback the callback function called for each value
  29356. */
  29357. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29358. if (data instanceof Array) {
  29359. var offset = byteOffset / 4;
  29360. var stride = byteStride / 4;
  29361. for (var index = 0; index < count; index += componentCount) {
  29362. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29363. callback(data[offset + componentIndex], index + componentIndex);
  29364. }
  29365. offset += stride;
  29366. }
  29367. }
  29368. else {
  29369. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29370. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29371. for (var index = 0; index < count; index += componentCount) {
  29372. var componentByteOffset = byteOffset;
  29373. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29374. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29375. callback(value, index + componentIndex);
  29376. componentByteOffset += componentByteLength;
  29377. }
  29378. byteOffset += byteStride;
  29379. }
  29380. }
  29381. };
  29382. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29383. switch (type) {
  29384. case VertexBuffer.BYTE: {
  29385. var value = dataView.getInt8(byteOffset);
  29386. if (normalized) {
  29387. value = (value + 0.5) / 127.5;
  29388. }
  29389. return value;
  29390. }
  29391. case VertexBuffer.UNSIGNED_BYTE: {
  29392. var value = dataView.getUint8(byteOffset);
  29393. if (normalized) {
  29394. value = value / 255;
  29395. }
  29396. return value;
  29397. }
  29398. case VertexBuffer.SHORT: {
  29399. var value = dataView.getInt16(byteOffset, true);
  29400. if (normalized) {
  29401. value = (value + 0.5) / 16383.5;
  29402. }
  29403. return value;
  29404. }
  29405. case VertexBuffer.UNSIGNED_SHORT: {
  29406. var value = dataView.getUint16(byteOffset, true);
  29407. if (normalized) {
  29408. value = value / 65535;
  29409. }
  29410. return value;
  29411. }
  29412. case VertexBuffer.FLOAT: {
  29413. return dataView.getFloat32(byteOffset, true);
  29414. }
  29415. default: {
  29416. throw new Error("Invalid component type " + type);
  29417. }
  29418. }
  29419. };
  29420. /**
  29421. * The byte type.
  29422. */
  29423. VertexBuffer.BYTE = 5120;
  29424. /**
  29425. * The unsigned byte type.
  29426. */
  29427. VertexBuffer.UNSIGNED_BYTE = 5121;
  29428. /**
  29429. * The short type.
  29430. */
  29431. VertexBuffer.SHORT = 5122;
  29432. /**
  29433. * The unsigned short type.
  29434. */
  29435. VertexBuffer.UNSIGNED_SHORT = 5123;
  29436. /**
  29437. * The integer type.
  29438. */
  29439. VertexBuffer.INT = 5124;
  29440. /**
  29441. * The unsigned integer type.
  29442. */
  29443. VertexBuffer.UNSIGNED_INT = 5125;
  29444. /**
  29445. * The float type.
  29446. */
  29447. VertexBuffer.FLOAT = 5126;
  29448. // Enums
  29449. VertexBuffer._PositionKind = "position";
  29450. VertexBuffer._NormalKind = "normal";
  29451. VertexBuffer._TangentKind = "tangent";
  29452. VertexBuffer._UVKind = "uv";
  29453. VertexBuffer._UV2Kind = "uv2";
  29454. VertexBuffer._UV3Kind = "uv3";
  29455. VertexBuffer._UV4Kind = "uv4";
  29456. VertexBuffer._UV5Kind = "uv5";
  29457. VertexBuffer._UV6Kind = "uv6";
  29458. VertexBuffer._ColorKind = "color";
  29459. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29460. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29461. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29462. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29463. return VertexBuffer;
  29464. }());
  29465. BABYLON.VertexBuffer = VertexBuffer;
  29466. })(BABYLON || (BABYLON = {}));
  29467. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29468. var BABYLON;
  29469. (function (BABYLON) {
  29470. /**
  29471. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29472. */
  29473. var DummyInternalTextureTracker = /** @class */ (function () {
  29474. function DummyInternalTextureTracker() {
  29475. /**
  29476. * Gets or set the previous tracker in the list
  29477. */
  29478. this.previous = null;
  29479. /**
  29480. * Gets or set the next tracker in the list
  29481. */
  29482. this.next = null;
  29483. }
  29484. return DummyInternalTextureTracker;
  29485. }());
  29486. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29487. })(BABYLON || (BABYLON = {}));
  29488. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29489. var BABYLON;
  29490. (function (BABYLON) {
  29491. /**
  29492. * Class used to store data associated with WebGL texture data for the engine
  29493. * This class should not be used directly
  29494. */
  29495. var InternalTexture = /** @class */ (function () {
  29496. /**
  29497. * Creates a new InternalTexture
  29498. * @param engine defines the engine to use
  29499. * @param dataSource defines the type of data that will be used
  29500. */
  29501. function InternalTexture(engine, dataSource) {
  29502. /**
  29503. * Observable called when the texture is loaded
  29504. */
  29505. this.onLoadedObservable = new BABYLON.Observable();
  29506. /**
  29507. * Gets or set the previous tracker in the list
  29508. */
  29509. this.previous = null;
  29510. /**
  29511. * Gets or set the next tracker in the list
  29512. */
  29513. this.next = null;
  29514. // Private
  29515. /** @ignore */
  29516. this._initialSlot = -1;
  29517. /** @ignore */
  29518. this._designatedSlot = -1;
  29519. /** @ignore */
  29520. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29521. /** @ignore */
  29522. this._comparisonFunction = 0;
  29523. /** @ignore */
  29524. this._references = 1;
  29525. this._engine = engine;
  29526. this._dataSource = dataSource;
  29527. this._webGLTexture = engine._createTexture();
  29528. }
  29529. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29530. /**
  29531. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29532. */
  29533. get: function () {
  29534. return this._dataSource;
  29535. },
  29536. enumerable: true,
  29537. configurable: true
  29538. });
  29539. /**
  29540. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29541. */
  29542. InternalTexture.prototype.incrementReferences = function () {
  29543. this._references++;
  29544. };
  29545. /**
  29546. * Change the size of the texture (not the size of the content)
  29547. * @param width defines the new width
  29548. * @param height defines the new height
  29549. * @param depth defines the new depth (1 by default)
  29550. */
  29551. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29552. if (depth === void 0) { depth = 1; }
  29553. this.width = width;
  29554. this.height = height;
  29555. this.depth = depth;
  29556. this.baseWidth = width;
  29557. this.baseHeight = height;
  29558. this.baseDepth = depth;
  29559. this._size = width * height * depth;
  29560. };
  29561. /** @ignore */
  29562. InternalTexture.prototype._rebuild = function () {
  29563. var _this = this;
  29564. var proxy;
  29565. this.isReady = false;
  29566. this._cachedCoordinatesMode = null;
  29567. this._cachedWrapU = null;
  29568. this._cachedWrapV = null;
  29569. this._cachedAnisotropicFilteringLevel = null;
  29570. switch (this._dataSource) {
  29571. case InternalTexture.DATASOURCE_TEMP:
  29572. return;
  29573. case InternalTexture.DATASOURCE_URL:
  29574. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29575. _this.isReady = true;
  29576. }, null, this._buffer, undefined, this.format);
  29577. proxy._swapAndDie(this);
  29578. return;
  29579. case InternalTexture.DATASOURCE_RAW:
  29580. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29581. proxy._swapAndDie(this);
  29582. this.isReady = true;
  29583. return;
  29584. case InternalTexture.DATASOURCE_RAW3D:
  29585. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29586. proxy._swapAndDie(this);
  29587. this.isReady = true;
  29588. return;
  29589. case InternalTexture.DATASOURCE_DYNAMIC:
  29590. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29591. proxy._swapAndDie(this);
  29592. // The engine will make sure to update content so no need to flag it as isReady = true
  29593. return;
  29594. case InternalTexture.DATASOURCE_RENDERTARGET:
  29595. var options = new BABYLON.RenderTargetCreationOptions();
  29596. options.generateDepthBuffer = this._generateDepthBuffer;
  29597. options.generateMipMaps = this.generateMipMaps;
  29598. options.generateStencilBuffer = this._generateStencilBuffer;
  29599. options.samplingMode = this.samplingMode;
  29600. options.type = this.type;
  29601. if (this.isCube) {
  29602. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29603. }
  29604. else {
  29605. var size = {
  29606. width: this.width,
  29607. height: this.height
  29608. };
  29609. proxy = this._engine.createRenderTargetTexture(size, options);
  29610. }
  29611. proxy._swapAndDie(this);
  29612. this.isReady = true;
  29613. return;
  29614. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29615. var depthTextureOptions = {
  29616. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29617. comparisonFunction: this._comparisonFunction,
  29618. generateStencil: this._generateStencilBuffer,
  29619. isCube: this.isCube
  29620. };
  29621. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29622. proxy._swapAndDie(this);
  29623. this.isReady = true;
  29624. return;
  29625. case InternalTexture.DATASOURCE_CUBE:
  29626. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29627. _this.isReady = true;
  29628. }, null, this.format, this._extension);
  29629. proxy._swapAndDie(this);
  29630. return;
  29631. case InternalTexture.DATASOURCE_CUBERAW:
  29632. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29633. proxy._swapAndDie(this);
  29634. this.isReady = true;
  29635. return;
  29636. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29637. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29638. if (proxy) {
  29639. proxy._swapAndDie(_this);
  29640. }
  29641. _this.isReady = true;
  29642. }, null, this.format, this._extension);
  29643. return;
  29644. }
  29645. };
  29646. InternalTexture.prototype._swapAndDie = function (target) {
  29647. target._webGLTexture = this._webGLTexture;
  29648. if (this._framebuffer) {
  29649. target._framebuffer = this._framebuffer;
  29650. }
  29651. if (this._depthStencilBuffer) {
  29652. target._depthStencilBuffer = this._depthStencilBuffer;
  29653. }
  29654. if (this._lodTextureHigh) {
  29655. if (target._lodTextureHigh) {
  29656. target._lodTextureHigh.dispose();
  29657. }
  29658. target._lodTextureHigh = this._lodTextureHigh;
  29659. }
  29660. if (this._lodTextureMid) {
  29661. if (target._lodTextureMid) {
  29662. target._lodTextureMid.dispose();
  29663. }
  29664. target._lodTextureMid = this._lodTextureMid;
  29665. }
  29666. if (this._lodTextureLow) {
  29667. if (target._lodTextureLow) {
  29668. target._lodTextureLow.dispose();
  29669. }
  29670. target._lodTextureLow = this._lodTextureLow;
  29671. }
  29672. var cache = this._engine.getLoadedTexturesCache();
  29673. var index = cache.indexOf(this);
  29674. if (index !== -1) {
  29675. cache.splice(index, 1);
  29676. }
  29677. };
  29678. /**
  29679. * Dispose the current allocated resources
  29680. */
  29681. InternalTexture.prototype.dispose = function () {
  29682. if (!this._webGLTexture) {
  29683. return;
  29684. }
  29685. this._references--;
  29686. if (this._references === 0) {
  29687. this._engine._releaseTexture(this);
  29688. this._webGLTexture = null;
  29689. this.previous = null;
  29690. this.next = null;
  29691. }
  29692. };
  29693. /**
  29694. * The source of the texture data is unknown
  29695. */
  29696. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29697. /**
  29698. * Texture data comes from an URL
  29699. */
  29700. InternalTexture.DATASOURCE_URL = 1;
  29701. /**
  29702. * Texture data is only used for temporary storage
  29703. */
  29704. InternalTexture.DATASOURCE_TEMP = 2;
  29705. /**
  29706. * Texture data comes from raw data (ArrayBuffer)
  29707. */
  29708. InternalTexture.DATASOURCE_RAW = 3;
  29709. /**
  29710. * Texture content is dynamic (video or dynamic texture)
  29711. */
  29712. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29713. /**
  29714. * Texture content is generated by rendering to it
  29715. */
  29716. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29717. /**
  29718. * Texture content is part of a multi render target process
  29719. */
  29720. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29721. /**
  29722. * Texture data comes from a cube data file
  29723. */
  29724. InternalTexture.DATASOURCE_CUBE = 7;
  29725. /**
  29726. * Texture data comes from a raw cube data
  29727. */
  29728. InternalTexture.DATASOURCE_CUBERAW = 8;
  29729. /**
  29730. * Texture data come from a prefiltered cube data file
  29731. */
  29732. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29733. /**
  29734. * Texture content is raw 3D data
  29735. */
  29736. InternalTexture.DATASOURCE_RAW3D = 10;
  29737. /**
  29738. * Texture content is a depth texture
  29739. */
  29740. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29741. return InternalTexture;
  29742. }());
  29743. BABYLON.InternalTexture = InternalTexture;
  29744. })(BABYLON || (BABYLON = {}));
  29745. //# sourceMappingURL=babylon.internalTexture.js.map
  29746. var BABYLON;
  29747. (function (BABYLON) {
  29748. var BaseTexture = /** @class */ (function () {
  29749. function BaseTexture(scene) {
  29750. this._hasAlpha = false;
  29751. this.getAlphaFromRGB = false;
  29752. this.level = 1;
  29753. this.coordinatesIndex = 0;
  29754. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29755. /**
  29756. * | Value | Type | Description |
  29757. * | ----- | ------------------ | ----------- |
  29758. * | 0 | CLAMP_ADDRESSMODE | |
  29759. * | 1 | WRAP_ADDRESSMODE | |
  29760. * | 2 | MIRROR_ADDRESSMODE | |
  29761. */
  29762. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29763. /**
  29764. * | Value | Type | Description |
  29765. * | ----- | ------------------ | ----------- |
  29766. * | 0 | CLAMP_ADDRESSMODE | |
  29767. * | 1 | WRAP_ADDRESSMODE | |
  29768. * | 2 | MIRROR_ADDRESSMODE | |
  29769. */
  29770. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29771. /**
  29772. * | Value | Type | Description |
  29773. * | ----- | ------------------ | ----------- |
  29774. * | 0 | CLAMP_ADDRESSMODE | |
  29775. * | 1 | WRAP_ADDRESSMODE | |
  29776. * | 2 | MIRROR_ADDRESSMODE | |
  29777. */
  29778. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29779. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29780. this.isCube = false;
  29781. this.is3D = false;
  29782. this.gammaSpace = true;
  29783. this.invertZ = false;
  29784. this.lodLevelInAlpha = false;
  29785. this.lodGenerationOffset = 0.0;
  29786. this.lodGenerationScale = 0.8;
  29787. this.isRenderTarget = false;
  29788. this.animations = new Array();
  29789. /**
  29790. * An event triggered when the texture is disposed.
  29791. */
  29792. this.onDisposeObservable = new BABYLON.Observable();
  29793. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29794. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29795. if (this._scene) {
  29796. this._scene.textures.push(this);
  29797. }
  29798. this._uid = null;
  29799. }
  29800. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29801. get: function () {
  29802. return this._hasAlpha;
  29803. },
  29804. set: function (value) {
  29805. if (this._hasAlpha === value) {
  29806. return;
  29807. }
  29808. this._hasAlpha = value;
  29809. if (this._scene) {
  29810. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29811. }
  29812. },
  29813. enumerable: true,
  29814. configurable: true
  29815. });
  29816. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  29817. get: function () {
  29818. return this._coordinatesMode;
  29819. },
  29820. /**
  29821. * How a texture is mapped.
  29822. *
  29823. * | Value | Type | Description |
  29824. * | ----- | ----------------------------------- | ----------- |
  29825. * | 0 | EXPLICIT_MODE | |
  29826. * | 1 | SPHERICAL_MODE | |
  29827. * | 2 | PLANAR_MODE | |
  29828. * | 3 | CUBIC_MODE | |
  29829. * | 4 | PROJECTION_MODE | |
  29830. * | 5 | SKYBOX_MODE | |
  29831. * | 6 | INVCUBIC_MODE | |
  29832. * | 7 | EQUIRECTANGULAR_MODE | |
  29833. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  29834. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  29835. */
  29836. set: function (value) {
  29837. if (this._coordinatesMode === value) {
  29838. return;
  29839. }
  29840. this._coordinatesMode = value;
  29841. if (this._scene) {
  29842. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29843. }
  29844. },
  29845. enumerable: true,
  29846. configurable: true
  29847. });
  29848. Object.defineProperty(BaseTexture.prototype, "uid", {
  29849. get: function () {
  29850. if (!this._uid) {
  29851. this._uid = BABYLON.Tools.RandomId();
  29852. }
  29853. return this._uid;
  29854. },
  29855. enumerable: true,
  29856. configurable: true
  29857. });
  29858. BaseTexture.prototype.toString = function () {
  29859. return this.name;
  29860. };
  29861. BaseTexture.prototype.getClassName = function () {
  29862. return "BaseTexture";
  29863. };
  29864. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  29865. set: function (callback) {
  29866. if (this._onDisposeObserver) {
  29867. this.onDisposeObservable.remove(this._onDisposeObserver);
  29868. }
  29869. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29870. },
  29871. enumerable: true,
  29872. configurable: true
  29873. });
  29874. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  29875. get: function () {
  29876. return true;
  29877. },
  29878. enumerable: true,
  29879. configurable: true
  29880. });
  29881. BaseTexture.prototype.getScene = function () {
  29882. return this._scene;
  29883. };
  29884. BaseTexture.prototype.getTextureMatrix = function () {
  29885. return BABYLON.Matrix.IdentityReadOnly;
  29886. };
  29887. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  29888. return BABYLON.Matrix.IdentityReadOnly;
  29889. };
  29890. BaseTexture.prototype.getInternalTexture = function () {
  29891. return this._texture;
  29892. };
  29893. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  29894. return !this.isBlocking || this.isReady();
  29895. };
  29896. BaseTexture.prototype.isReady = function () {
  29897. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29898. this.delayLoad();
  29899. return false;
  29900. }
  29901. if (this._texture) {
  29902. return this._texture.isReady;
  29903. }
  29904. return false;
  29905. };
  29906. BaseTexture.prototype.getSize = function () {
  29907. if (this._texture && this._texture.width) {
  29908. return new BABYLON.Size(this._texture.width, this._texture.height);
  29909. }
  29910. if (this._texture && this._texture._size) {
  29911. return new BABYLON.Size(this._texture._size, this._texture._size);
  29912. }
  29913. return BABYLON.Size.Zero();
  29914. };
  29915. BaseTexture.prototype.getBaseSize = function () {
  29916. if (!this.isReady() || !this._texture)
  29917. return BABYLON.Size.Zero();
  29918. if (this._texture._size) {
  29919. return new BABYLON.Size(this._texture._size, this._texture._size);
  29920. }
  29921. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  29922. };
  29923. BaseTexture.prototype.scale = function (ratio) {
  29924. };
  29925. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  29926. get: function () {
  29927. return false;
  29928. },
  29929. enumerable: true,
  29930. configurable: true
  29931. });
  29932. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  29933. if (!this._scene) {
  29934. return null;
  29935. }
  29936. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  29937. for (var index = 0; index < texturesCache.length; index++) {
  29938. var texturesCacheEntry = texturesCache[index];
  29939. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  29940. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  29941. texturesCacheEntry.incrementReferences();
  29942. return texturesCacheEntry;
  29943. }
  29944. }
  29945. }
  29946. return null;
  29947. };
  29948. BaseTexture.prototype._rebuild = function () {
  29949. };
  29950. BaseTexture.prototype.delayLoad = function () {
  29951. };
  29952. BaseTexture.prototype.clone = function () {
  29953. return null;
  29954. };
  29955. Object.defineProperty(BaseTexture.prototype, "textureType", {
  29956. get: function () {
  29957. if (!this._texture) {
  29958. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29959. }
  29960. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  29961. },
  29962. enumerable: true,
  29963. configurable: true
  29964. });
  29965. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  29966. get: function () {
  29967. if (!this._texture) {
  29968. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29969. }
  29970. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  29971. },
  29972. enumerable: true,
  29973. configurable: true
  29974. });
  29975. BaseTexture.prototype.readPixels = function (faceIndex) {
  29976. if (faceIndex === void 0) { faceIndex = 0; }
  29977. if (!this._texture) {
  29978. return null;
  29979. }
  29980. var size = this.getSize();
  29981. var scene = this.getScene();
  29982. if (!scene) {
  29983. return null;
  29984. }
  29985. var engine = scene.getEngine();
  29986. if (this._texture.isCube) {
  29987. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  29988. }
  29989. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  29990. };
  29991. BaseTexture.prototype.releaseInternalTexture = function () {
  29992. if (this._texture) {
  29993. this._texture.dispose();
  29994. this._texture = null;
  29995. }
  29996. };
  29997. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  29998. get: function () {
  29999. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30000. return null;
  30001. }
  30002. if (!this._texture._sphericalPolynomial) {
  30003. this._texture._sphericalPolynomial =
  30004. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30005. }
  30006. return this._texture._sphericalPolynomial;
  30007. },
  30008. set: function (value) {
  30009. if (this._texture) {
  30010. this._texture._sphericalPolynomial = value;
  30011. }
  30012. },
  30013. enumerable: true,
  30014. configurable: true
  30015. });
  30016. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30017. get: function () {
  30018. if (this._texture) {
  30019. return this._texture._lodTextureHigh;
  30020. }
  30021. return null;
  30022. },
  30023. enumerable: true,
  30024. configurable: true
  30025. });
  30026. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30027. get: function () {
  30028. if (this._texture) {
  30029. return this._texture._lodTextureMid;
  30030. }
  30031. return null;
  30032. },
  30033. enumerable: true,
  30034. configurable: true
  30035. });
  30036. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30037. get: function () {
  30038. if (this._texture) {
  30039. return this._texture._lodTextureLow;
  30040. }
  30041. return null;
  30042. },
  30043. enumerable: true,
  30044. configurable: true
  30045. });
  30046. BaseTexture.prototype.dispose = function () {
  30047. if (!this._scene) {
  30048. return;
  30049. }
  30050. // Animations
  30051. this._scene.stopAnimation(this);
  30052. // Remove from scene
  30053. this._scene._removePendingData(this);
  30054. var index = this._scene.textures.indexOf(this);
  30055. if (index >= 0) {
  30056. this._scene.textures.splice(index, 1);
  30057. }
  30058. if (this._texture === undefined) {
  30059. return;
  30060. }
  30061. // Release
  30062. this.releaseInternalTexture();
  30063. // Callback
  30064. this.onDisposeObservable.notifyObservers(this);
  30065. this.onDisposeObservable.clear();
  30066. };
  30067. BaseTexture.prototype.serialize = function () {
  30068. if (!this.name) {
  30069. return null;
  30070. }
  30071. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30072. // Animations
  30073. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30074. return serializationObject;
  30075. };
  30076. BaseTexture.WhenAllReady = function (textures, callback) {
  30077. var numRemaining = textures.length;
  30078. if (numRemaining === 0) {
  30079. callback();
  30080. return;
  30081. }
  30082. var _loop_1 = function () {
  30083. texture = textures[i];
  30084. if (texture.isReady()) {
  30085. if (--numRemaining === 0) {
  30086. callback();
  30087. }
  30088. }
  30089. else {
  30090. onLoadObservable = texture.onLoadObservable;
  30091. var onLoadCallback_1 = function () {
  30092. onLoadObservable.removeCallback(onLoadCallback_1);
  30093. if (--numRemaining === 0) {
  30094. callback();
  30095. }
  30096. };
  30097. onLoadObservable.add(onLoadCallback_1);
  30098. }
  30099. };
  30100. var texture, onLoadObservable;
  30101. for (var i = 0; i < textures.length; i++) {
  30102. _loop_1();
  30103. }
  30104. };
  30105. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30106. __decorate([
  30107. BABYLON.serialize()
  30108. ], BaseTexture.prototype, "name", void 0);
  30109. __decorate([
  30110. BABYLON.serialize("hasAlpha")
  30111. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30112. __decorate([
  30113. BABYLON.serialize()
  30114. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30115. __decorate([
  30116. BABYLON.serialize()
  30117. ], BaseTexture.prototype, "level", void 0);
  30118. __decorate([
  30119. BABYLON.serialize()
  30120. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30121. __decorate([
  30122. BABYLON.serialize("coordinatesMode")
  30123. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30124. __decorate([
  30125. BABYLON.serialize()
  30126. ], BaseTexture.prototype, "wrapU", void 0);
  30127. __decorate([
  30128. BABYLON.serialize()
  30129. ], BaseTexture.prototype, "wrapV", void 0);
  30130. __decorate([
  30131. BABYLON.serialize()
  30132. ], BaseTexture.prototype, "wrapR", void 0);
  30133. __decorate([
  30134. BABYLON.serialize()
  30135. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30136. __decorate([
  30137. BABYLON.serialize()
  30138. ], BaseTexture.prototype, "isCube", void 0);
  30139. __decorate([
  30140. BABYLON.serialize()
  30141. ], BaseTexture.prototype, "is3D", void 0);
  30142. __decorate([
  30143. BABYLON.serialize()
  30144. ], BaseTexture.prototype, "gammaSpace", void 0);
  30145. __decorate([
  30146. BABYLON.serialize()
  30147. ], BaseTexture.prototype, "invertZ", void 0);
  30148. __decorate([
  30149. BABYLON.serialize()
  30150. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30151. __decorate([
  30152. BABYLON.serialize()
  30153. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30154. __decorate([
  30155. BABYLON.serialize()
  30156. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30157. __decorate([
  30158. BABYLON.serialize()
  30159. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30160. return BaseTexture;
  30161. }());
  30162. BABYLON.BaseTexture = BaseTexture;
  30163. })(BABYLON || (BABYLON = {}));
  30164. //# sourceMappingURL=babylon.baseTexture.js.map
  30165. var BABYLON;
  30166. (function (BABYLON) {
  30167. var Texture = /** @class */ (function (_super) {
  30168. __extends(Texture, _super);
  30169. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30170. if (noMipmap === void 0) { noMipmap = false; }
  30171. if (invertY === void 0) { invertY = true; }
  30172. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30173. if (onLoad === void 0) { onLoad = null; }
  30174. if (onError === void 0) { onError = null; }
  30175. if (buffer === void 0) { buffer = null; }
  30176. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30177. var _this = _super.call(this, scene) || this;
  30178. _this.uOffset = 0;
  30179. _this.vOffset = 0;
  30180. _this.uScale = 1.0;
  30181. _this.vScale = 1.0;
  30182. _this.uAng = 0;
  30183. _this.vAng = 0;
  30184. _this.wAng = 0;
  30185. _this._isBlocking = true;
  30186. _this.name = url || "";
  30187. _this.url = url;
  30188. _this._noMipmap = noMipmap;
  30189. _this._invertY = invertY;
  30190. _this._samplingMode = samplingMode;
  30191. _this._buffer = buffer;
  30192. _this._deleteBuffer = deleteBuffer;
  30193. if (format) {
  30194. _this._format = format;
  30195. }
  30196. scene = _this.getScene();
  30197. if (!scene) {
  30198. return _this;
  30199. }
  30200. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30201. var load = function () {
  30202. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30203. _this.onLoadObservable.notifyObservers(_this);
  30204. }
  30205. if (onLoad) {
  30206. onLoad();
  30207. }
  30208. if (!_this.isBlocking && scene) {
  30209. scene.resetCachedMaterial();
  30210. }
  30211. };
  30212. if (!_this.url) {
  30213. _this._delayedOnLoad = load;
  30214. _this._delayedOnError = onError;
  30215. return _this;
  30216. }
  30217. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30218. if (!_this._texture) {
  30219. if (!scene.useDelayedTextureLoading) {
  30220. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30221. if (deleteBuffer) {
  30222. delete _this._buffer;
  30223. }
  30224. }
  30225. else {
  30226. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30227. _this._delayedOnLoad = load;
  30228. _this._delayedOnError = onError;
  30229. }
  30230. }
  30231. else {
  30232. if (_this._texture.isReady) {
  30233. BABYLON.Tools.SetImmediate(function () { return load(); });
  30234. }
  30235. else {
  30236. _this._texture.onLoadedObservable.add(load);
  30237. }
  30238. }
  30239. return _this;
  30240. }
  30241. Object.defineProperty(Texture.prototype, "noMipmap", {
  30242. get: function () {
  30243. return this._noMipmap;
  30244. },
  30245. enumerable: true,
  30246. configurable: true
  30247. });
  30248. Object.defineProperty(Texture.prototype, "isBlocking", {
  30249. get: function () {
  30250. return this._isBlocking;
  30251. },
  30252. set: function (value) {
  30253. this._isBlocking = value;
  30254. },
  30255. enumerable: true,
  30256. configurable: true
  30257. });
  30258. Object.defineProperty(Texture.prototype, "samplingMode", {
  30259. get: function () {
  30260. return this._samplingMode;
  30261. },
  30262. enumerable: true,
  30263. configurable: true
  30264. });
  30265. Texture.prototype.updateURL = function (url) {
  30266. this.url = url;
  30267. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30268. this.delayLoad();
  30269. };
  30270. Texture.prototype.delayLoad = function () {
  30271. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30272. return;
  30273. }
  30274. var scene = this.getScene();
  30275. if (!scene) {
  30276. return;
  30277. }
  30278. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30279. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30280. if (!this._texture) {
  30281. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30282. if (this._deleteBuffer) {
  30283. delete this._buffer;
  30284. }
  30285. }
  30286. else {
  30287. if (this._delayedOnLoad) {
  30288. if (this._texture.isReady) {
  30289. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30290. }
  30291. else {
  30292. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30293. }
  30294. }
  30295. }
  30296. this._delayedOnLoad = null;
  30297. this._delayedOnError = null;
  30298. };
  30299. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30300. if (!this._texture) {
  30301. return;
  30302. }
  30303. var scene = this.getScene();
  30304. if (!scene) {
  30305. return;
  30306. }
  30307. this._samplingMode = samplingMode;
  30308. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30309. };
  30310. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30311. x *= this.uScale;
  30312. y *= this.vScale;
  30313. x -= 0.5 * this.uScale;
  30314. y -= 0.5 * this.vScale;
  30315. z -= 0.5;
  30316. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30317. t.x += 0.5 * this.uScale + this.uOffset;
  30318. t.y += 0.5 * this.vScale + this.vOffset;
  30319. t.z += 0.5;
  30320. };
  30321. Texture.prototype.getTextureMatrix = function () {
  30322. var _this = this;
  30323. if (this.uOffset === this._cachedUOffset &&
  30324. this.vOffset === this._cachedVOffset &&
  30325. this.uScale === this._cachedUScale &&
  30326. this.vScale === this._cachedVScale &&
  30327. this.uAng === this._cachedUAng &&
  30328. this.vAng === this._cachedVAng &&
  30329. this.wAng === this._cachedWAng) {
  30330. return this._cachedTextureMatrix;
  30331. }
  30332. this._cachedUOffset = this.uOffset;
  30333. this._cachedVOffset = this.vOffset;
  30334. this._cachedUScale = this.uScale;
  30335. this._cachedVScale = this.vScale;
  30336. this._cachedUAng = this.uAng;
  30337. this._cachedVAng = this.vAng;
  30338. this._cachedWAng = this.wAng;
  30339. if (!this._cachedTextureMatrix) {
  30340. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30341. this._rowGenerationMatrix = new BABYLON.Matrix();
  30342. this._t0 = BABYLON.Vector3.Zero();
  30343. this._t1 = BABYLON.Vector3.Zero();
  30344. this._t2 = BABYLON.Vector3.Zero();
  30345. }
  30346. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30347. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30348. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30349. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30350. this._t1.subtractInPlace(this._t0);
  30351. this._t2.subtractInPlace(this._t0);
  30352. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30353. this._cachedTextureMatrix.m[0] = this._t1.x;
  30354. this._cachedTextureMatrix.m[1] = this._t1.y;
  30355. this._cachedTextureMatrix.m[2] = this._t1.z;
  30356. this._cachedTextureMatrix.m[4] = this._t2.x;
  30357. this._cachedTextureMatrix.m[5] = this._t2.y;
  30358. this._cachedTextureMatrix.m[6] = this._t2.z;
  30359. this._cachedTextureMatrix.m[8] = this._t0.x;
  30360. this._cachedTextureMatrix.m[9] = this._t0.y;
  30361. this._cachedTextureMatrix.m[10] = this._t0.z;
  30362. var scene = this.getScene();
  30363. if (!scene) {
  30364. return this._cachedTextureMatrix;
  30365. }
  30366. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30367. return mat.hasTexture(_this);
  30368. });
  30369. return this._cachedTextureMatrix;
  30370. };
  30371. Texture.prototype.getReflectionTextureMatrix = function () {
  30372. var _this = this;
  30373. var scene = this.getScene();
  30374. if (!scene) {
  30375. return this._cachedTextureMatrix;
  30376. }
  30377. if (this.uOffset === this._cachedUOffset &&
  30378. this.vOffset === this._cachedVOffset &&
  30379. this.uScale === this._cachedUScale &&
  30380. this.vScale === this._cachedVScale &&
  30381. this.coordinatesMode === this._cachedCoordinatesMode) {
  30382. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30383. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30384. return this._cachedTextureMatrix;
  30385. }
  30386. }
  30387. else {
  30388. return this._cachedTextureMatrix;
  30389. }
  30390. }
  30391. if (!this._cachedTextureMatrix) {
  30392. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30393. }
  30394. if (!this._projectionModeMatrix) {
  30395. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30396. }
  30397. this._cachedUOffset = this.uOffset;
  30398. this._cachedVOffset = this.vOffset;
  30399. this._cachedUScale = this.uScale;
  30400. this._cachedVScale = this.vScale;
  30401. this._cachedCoordinatesMode = this.coordinatesMode;
  30402. switch (this.coordinatesMode) {
  30403. case Texture.PLANAR_MODE:
  30404. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30405. this._cachedTextureMatrix[0] = this.uScale;
  30406. this._cachedTextureMatrix[5] = this.vScale;
  30407. this._cachedTextureMatrix[12] = this.uOffset;
  30408. this._cachedTextureMatrix[13] = this.vOffset;
  30409. break;
  30410. case Texture.PROJECTION_MODE:
  30411. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30412. this._projectionModeMatrix.m[0] = 0.5;
  30413. this._projectionModeMatrix.m[5] = -0.5;
  30414. this._projectionModeMatrix.m[10] = 0.0;
  30415. this._projectionModeMatrix.m[12] = 0.5;
  30416. this._projectionModeMatrix.m[13] = 0.5;
  30417. this._projectionModeMatrix.m[14] = 1.0;
  30418. this._projectionModeMatrix.m[15] = 1.0;
  30419. var projectionMatrix = scene.getProjectionMatrix();
  30420. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30421. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30422. break;
  30423. default:
  30424. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30425. break;
  30426. }
  30427. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30428. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30429. });
  30430. return this._cachedTextureMatrix;
  30431. };
  30432. Texture.prototype.clone = function () {
  30433. var _this = this;
  30434. return BABYLON.SerializationHelper.Clone(function () {
  30435. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30436. }, this);
  30437. };
  30438. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30439. get: function () {
  30440. if (!this._onLoadObservable) {
  30441. this._onLoadObservable = new BABYLON.Observable();
  30442. }
  30443. return this._onLoadObservable;
  30444. },
  30445. enumerable: true,
  30446. configurable: true
  30447. });
  30448. Texture.prototype.serialize = function () {
  30449. var serializationObject = _super.prototype.serialize.call(this);
  30450. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30451. serializationObject.base64String = this._buffer;
  30452. serializationObject.name = serializationObject.name.replace("data:", "");
  30453. }
  30454. serializationObject.invertY = this._invertY;
  30455. serializationObject.samplingMode = this.samplingMode;
  30456. return serializationObject;
  30457. };
  30458. Texture.prototype.getClassName = function () {
  30459. return "Texture";
  30460. };
  30461. Texture.prototype.dispose = function () {
  30462. _super.prototype.dispose.call(this);
  30463. if (this.onLoadObservable) {
  30464. this.onLoadObservable.clear();
  30465. this._onLoadObservable = null;
  30466. }
  30467. this._delayedOnLoad = null;
  30468. this._delayedOnError = null;
  30469. };
  30470. // Statics
  30471. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30472. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30473. if (onLoad === void 0) { onLoad = null; }
  30474. if (onError === void 0) { onError = null; }
  30475. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30476. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30477. };
  30478. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30479. if (parsedTexture.customType) {
  30480. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30481. // Update Sampling Mode
  30482. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30483. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30484. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30485. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30486. }
  30487. }
  30488. return parsedCustomTexture;
  30489. }
  30490. if (parsedTexture.isCube) {
  30491. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30492. }
  30493. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30494. return null;
  30495. }
  30496. var texture = BABYLON.SerializationHelper.Parse(function () {
  30497. var generateMipMaps = true;
  30498. if (parsedTexture.noMipmap) {
  30499. generateMipMaps = false;
  30500. }
  30501. if (parsedTexture.mirrorPlane) {
  30502. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30503. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30504. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30505. return mirrorTexture;
  30506. }
  30507. else if (parsedTexture.isRenderTarget) {
  30508. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30509. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30510. return renderTargetTexture;
  30511. }
  30512. else {
  30513. var texture;
  30514. if (parsedTexture.base64String) {
  30515. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30516. }
  30517. else {
  30518. var url = rootUrl + parsedTexture.name;
  30519. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30520. url = parsedTexture.url;
  30521. }
  30522. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30523. }
  30524. return texture;
  30525. }
  30526. }, parsedTexture, scene);
  30527. // Update Sampling Mode
  30528. if (parsedTexture.samplingMode) {
  30529. var sampling = parsedTexture.samplingMode;
  30530. if (texture._samplingMode !== sampling) {
  30531. texture.updateSamplingMode(sampling);
  30532. }
  30533. }
  30534. // Animations
  30535. if (parsedTexture.animations) {
  30536. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30537. var parsedAnimation = parsedTexture.animations[animationIndex];
  30538. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30539. }
  30540. }
  30541. return texture;
  30542. };
  30543. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30544. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30545. if (noMipmap === void 0) { noMipmap = false; }
  30546. if (invertY === void 0) { invertY = true; }
  30547. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30548. if (onLoad === void 0) { onLoad = null; }
  30549. if (onError === void 0) { onError = null; }
  30550. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30551. if (name.substr(0, 5) !== "data:") {
  30552. name = "data:" + name;
  30553. }
  30554. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30555. };
  30556. // Constants
  30557. Texture.NEAREST_SAMPLINGMODE = 1;
  30558. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30559. Texture.BILINEAR_SAMPLINGMODE = 2;
  30560. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30561. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30562. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30563. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30564. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30565. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30566. Texture.NEAREST_LINEAR = 7;
  30567. Texture.NEAREST_NEAREST = 8;
  30568. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30569. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30570. Texture.LINEAR_LINEAR = 11;
  30571. Texture.LINEAR_NEAREST = 12;
  30572. Texture.EXPLICIT_MODE = 0;
  30573. Texture.SPHERICAL_MODE = 1;
  30574. Texture.PLANAR_MODE = 2;
  30575. Texture.CUBIC_MODE = 3;
  30576. Texture.PROJECTION_MODE = 4;
  30577. Texture.SKYBOX_MODE = 5;
  30578. Texture.INVCUBIC_MODE = 6;
  30579. Texture.EQUIRECTANGULAR_MODE = 7;
  30580. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30581. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30582. Texture.CLAMP_ADDRESSMODE = 0;
  30583. Texture.WRAP_ADDRESSMODE = 1;
  30584. Texture.MIRROR_ADDRESSMODE = 2;
  30585. /**
  30586. * 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
  30587. */
  30588. Texture.UseSerializedUrlIfAny = false;
  30589. __decorate([
  30590. BABYLON.serialize()
  30591. ], Texture.prototype, "url", void 0);
  30592. __decorate([
  30593. BABYLON.serialize()
  30594. ], Texture.prototype, "uOffset", void 0);
  30595. __decorate([
  30596. BABYLON.serialize()
  30597. ], Texture.prototype, "vOffset", void 0);
  30598. __decorate([
  30599. BABYLON.serialize()
  30600. ], Texture.prototype, "uScale", void 0);
  30601. __decorate([
  30602. BABYLON.serialize()
  30603. ], Texture.prototype, "vScale", void 0);
  30604. __decorate([
  30605. BABYLON.serialize()
  30606. ], Texture.prototype, "uAng", void 0);
  30607. __decorate([
  30608. BABYLON.serialize()
  30609. ], Texture.prototype, "vAng", void 0);
  30610. __decorate([
  30611. BABYLON.serialize()
  30612. ], Texture.prototype, "wAng", void 0);
  30613. __decorate([
  30614. BABYLON.serialize()
  30615. ], Texture.prototype, "isBlocking", null);
  30616. return Texture;
  30617. }(BABYLON.BaseTexture));
  30618. BABYLON.Texture = Texture;
  30619. })(BABYLON || (BABYLON = {}));
  30620. //# sourceMappingURL=babylon.texture.js.map
  30621. var BABYLON;
  30622. (function (BABYLON) {
  30623. var _InstancesBatch = /** @class */ (function () {
  30624. function _InstancesBatch() {
  30625. this.mustReturn = false;
  30626. this.visibleInstances = new Array();
  30627. this.renderSelf = new Array();
  30628. }
  30629. return _InstancesBatch;
  30630. }());
  30631. BABYLON._InstancesBatch = _InstancesBatch;
  30632. var Mesh = /** @class */ (function (_super) {
  30633. __extends(Mesh, _super);
  30634. /**
  30635. * @constructor
  30636. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30637. * @param {Scene} scene The scene to add this mesh to.
  30638. * @param {Node} parent The parent of this mesh, if it has one
  30639. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30640. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30641. * When false, achieved by calling a clone(), also passing False.
  30642. * This will make creation of children, recursive.
  30643. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30644. */
  30645. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30646. if (scene === void 0) { scene = null; }
  30647. if (parent === void 0) { parent = null; }
  30648. if (source === void 0) { source = null; }
  30649. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30650. var _this = _super.call(this, name, scene) || this;
  30651. // Events
  30652. /**
  30653. * An event triggered before rendering the mesh
  30654. */
  30655. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30656. /**
  30657. * An event triggered after rendering the mesh
  30658. */
  30659. _this.onAfterRenderObservable = new BABYLON.Observable();
  30660. /**
  30661. * An event triggered before drawing the mesh
  30662. */
  30663. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30664. // Members
  30665. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30666. _this.instances = new Array();
  30667. _this._LODLevels = new Array();
  30668. _this._visibleInstances = {};
  30669. _this._renderIdForInstances = new Array();
  30670. _this._batchCache = new _InstancesBatch();
  30671. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30672. // Use by builder only to know what orientation were the mesh build in.
  30673. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30674. _this.overrideMaterialSideOrientation = null;
  30675. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30676. // Will be used to save a source mesh reference, If any
  30677. _this._source = null;
  30678. scene = _this.getScene();
  30679. if (source) {
  30680. // Source mesh
  30681. _this._source = source;
  30682. // Geometry
  30683. if (source._geometry) {
  30684. source._geometry.applyToMesh(_this);
  30685. }
  30686. // Deep copy
  30687. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30688. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30689. // Metadata
  30690. if (source.metadata && source.metadata.clone) {
  30691. _this.metadata = source.metadata.clone();
  30692. }
  30693. else {
  30694. _this.metadata = source.metadata;
  30695. }
  30696. // Tags
  30697. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30698. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30699. }
  30700. // Parent
  30701. _this.parent = source.parent;
  30702. // Pivot
  30703. _this.setPivotMatrix(source.getPivotMatrix());
  30704. _this.id = name + "." + source.id;
  30705. // Material
  30706. _this.material = source.material;
  30707. var index;
  30708. if (!doNotCloneChildren) {
  30709. // Children
  30710. var directDescendants = source.getDescendants(true);
  30711. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30712. var child = directDescendants[index_1];
  30713. if (child.clone) {
  30714. child.clone(name + "." + child.name, _this);
  30715. }
  30716. }
  30717. }
  30718. // Physics clone
  30719. var physicsEngine = _this.getScene().getPhysicsEngine();
  30720. if (clonePhysicsImpostor && physicsEngine) {
  30721. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30722. if (impostor) {
  30723. _this.physicsImpostor = impostor.clone(_this);
  30724. }
  30725. }
  30726. // Particles
  30727. for (index = 0; index < scene.particleSystems.length; index++) {
  30728. var system = scene.particleSystems[index];
  30729. if (system.emitter === source) {
  30730. system.clone(system.name, _this);
  30731. }
  30732. }
  30733. _this.computeWorldMatrix(true);
  30734. }
  30735. // Parent
  30736. if (parent !== null) {
  30737. _this.parent = parent;
  30738. }
  30739. return _this;
  30740. }
  30741. Object.defineProperty(Mesh, "FRONTSIDE", {
  30742. /**
  30743. * Mesh side orientation : usually the external or front surface
  30744. */
  30745. get: function () {
  30746. return Mesh._FRONTSIDE;
  30747. },
  30748. enumerable: true,
  30749. configurable: true
  30750. });
  30751. Object.defineProperty(Mesh, "BACKSIDE", {
  30752. /**
  30753. * Mesh side orientation : usually the internal or back surface
  30754. */
  30755. get: function () {
  30756. return Mesh._BACKSIDE;
  30757. },
  30758. enumerable: true,
  30759. configurable: true
  30760. });
  30761. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30762. /**
  30763. * Mesh side orientation : both internal and external or front and back surfaces
  30764. */
  30765. get: function () {
  30766. return Mesh._DOUBLESIDE;
  30767. },
  30768. enumerable: true,
  30769. configurable: true
  30770. });
  30771. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30772. /**
  30773. * Mesh side orientation : by default, `FRONTSIDE`
  30774. */
  30775. get: function () {
  30776. return Mesh._DEFAULTSIDE;
  30777. },
  30778. enumerable: true,
  30779. configurable: true
  30780. });
  30781. Object.defineProperty(Mesh, "NO_CAP", {
  30782. /**
  30783. * Mesh cap setting : no cap
  30784. */
  30785. get: function () {
  30786. return Mesh._NO_CAP;
  30787. },
  30788. enumerable: true,
  30789. configurable: true
  30790. });
  30791. Object.defineProperty(Mesh, "CAP_START", {
  30792. /**
  30793. * Mesh cap setting : one cap at the beginning of the mesh
  30794. */
  30795. get: function () {
  30796. return Mesh._CAP_START;
  30797. },
  30798. enumerable: true,
  30799. configurable: true
  30800. });
  30801. Object.defineProperty(Mesh, "CAP_END", {
  30802. /**
  30803. * Mesh cap setting : one cap at the end of the mesh
  30804. */
  30805. get: function () {
  30806. return Mesh._CAP_END;
  30807. },
  30808. enumerable: true,
  30809. configurable: true
  30810. });
  30811. Object.defineProperty(Mesh, "CAP_ALL", {
  30812. /**
  30813. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  30814. */
  30815. get: function () {
  30816. return Mesh._CAP_ALL;
  30817. },
  30818. enumerable: true,
  30819. configurable: true
  30820. });
  30821. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  30822. set: function (callback) {
  30823. if (this._onBeforeDrawObserver) {
  30824. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  30825. }
  30826. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  30827. },
  30828. enumerable: true,
  30829. configurable: true
  30830. });
  30831. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  30832. get: function () {
  30833. return this._morphTargetManager;
  30834. },
  30835. set: function (value) {
  30836. if (this._morphTargetManager === value) {
  30837. return;
  30838. }
  30839. this._morphTargetManager = value;
  30840. this._syncGeometryWithMorphTargetManager();
  30841. },
  30842. enumerable: true,
  30843. configurable: true
  30844. });
  30845. Object.defineProperty(Mesh.prototype, "source", {
  30846. get: function () {
  30847. return this._source;
  30848. },
  30849. enumerable: true,
  30850. configurable: true
  30851. });
  30852. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  30853. get: function () {
  30854. return this._unIndexed;
  30855. },
  30856. set: function (value) {
  30857. if (this._unIndexed !== value) {
  30858. this._unIndexed = value;
  30859. this._markSubMeshesAsAttributesDirty();
  30860. }
  30861. },
  30862. enumerable: true,
  30863. configurable: true
  30864. });
  30865. // Methods
  30866. /**
  30867. * Returns the string "Mesh".
  30868. */
  30869. Mesh.prototype.getClassName = function () {
  30870. return "Mesh";
  30871. };
  30872. /**
  30873. * Returns a string.
  30874. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30875. */
  30876. Mesh.prototype.toString = function (fullDetails) {
  30877. var ret = _super.prototype.toString.call(this, fullDetails);
  30878. ret += ", n vertices: " + this.getTotalVertices();
  30879. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  30880. if (this.animations) {
  30881. for (var i = 0; i < this.animations.length; i++) {
  30882. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  30883. }
  30884. }
  30885. if (fullDetails) {
  30886. if (this._geometry) {
  30887. var ib = this.getIndices();
  30888. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30889. if (vb && ib) {
  30890. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  30891. }
  30892. }
  30893. else {
  30894. ret += ", flat shading: UNKNOWN";
  30895. }
  30896. }
  30897. return ret;
  30898. };
  30899. Mesh.prototype._unBindEffect = function () {
  30900. _super.prototype._unBindEffect.call(this);
  30901. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  30902. var instance = _a[_i];
  30903. instance._unBindEffect();
  30904. }
  30905. };
  30906. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  30907. /**
  30908. * True if the mesh has some Levels Of Details (LOD).
  30909. * Returns a boolean.
  30910. */
  30911. get: function () {
  30912. return this._LODLevels.length > 0;
  30913. },
  30914. enumerable: true,
  30915. configurable: true
  30916. });
  30917. /**
  30918. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  30919. * @returns an array of {BABYLON.MeshLODLevel}
  30920. */
  30921. Mesh.prototype.getLODLevels = function () {
  30922. return this._LODLevels;
  30923. };
  30924. Mesh.prototype._sortLODLevels = function () {
  30925. this._LODLevels.sort(function (a, b) {
  30926. if (a.distance < b.distance) {
  30927. return 1;
  30928. }
  30929. if (a.distance > b.distance) {
  30930. return -1;
  30931. }
  30932. return 0;
  30933. });
  30934. };
  30935. /**
  30936. * Add a mesh as LOD level triggered at the given distance.
  30937. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30938. * @param {number} distance The distance from the center of the object to show this level
  30939. * @param {Mesh} mesh The mesh to be added as LOD level
  30940. * @return {Mesh} This mesh (for chaining)
  30941. */
  30942. Mesh.prototype.addLODLevel = function (distance, mesh) {
  30943. if (mesh && mesh._masterMesh) {
  30944. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  30945. return this;
  30946. }
  30947. var level = new BABYLON.MeshLODLevel(distance, mesh);
  30948. this._LODLevels.push(level);
  30949. if (mesh) {
  30950. mesh._masterMesh = this;
  30951. }
  30952. this._sortLODLevels();
  30953. return this;
  30954. };
  30955. /**
  30956. * Returns the LOD level mesh at the passed distance or null if not found.
  30957. * It is related to the method `addLODLevel(distance, mesh)`.
  30958. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30959. * Returns an object Mesh or `null`.
  30960. */
  30961. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  30962. for (var index = 0; index < this._LODLevels.length; index++) {
  30963. var level = this._LODLevels[index];
  30964. if (level.distance === distance) {
  30965. return level.mesh;
  30966. }
  30967. }
  30968. return null;
  30969. };
  30970. /**
  30971. * Remove a mesh from the LOD array
  30972. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30973. * @param {Mesh} mesh The mesh to be removed.
  30974. * @return {Mesh} This mesh (for chaining)
  30975. */
  30976. Mesh.prototype.removeLODLevel = function (mesh) {
  30977. for (var index = 0; index < this._LODLevels.length; index++) {
  30978. if (this._LODLevels[index].mesh === mesh) {
  30979. this._LODLevels.splice(index, 1);
  30980. if (mesh) {
  30981. mesh._masterMesh = null;
  30982. }
  30983. }
  30984. }
  30985. this._sortLODLevels();
  30986. return this;
  30987. };
  30988. /**
  30989. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  30990. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  30991. */
  30992. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  30993. if (!this._LODLevels || this._LODLevels.length === 0) {
  30994. return this;
  30995. }
  30996. var bSphere;
  30997. if (boundingSphere) {
  30998. bSphere = boundingSphere;
  30999. }
  31000. else {
  31001. var boundingInfo = this.getBoundingInfo();
  31002. bSphere = boundingInfo.boundingSphere;
  31003. }
  31004. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31005. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31006. if (this.onLODLevelSelection) {
  31007. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31008. }
  31009. return this;
  31010. }
  31011. for (var index = 0; index < this._LODLevels.length; index++) {
  31012. var level = this._LODLevels[index];
  31013. if (level.distance < distanceToCamera) {
  31014. if (level.mesh) {
  31015. level.mesh._preActivate();
  31016. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31017. }
  31018. if (this.onLODLevelSelection) {
  31019. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31020. }
  31021. return level.mesh;
  31022. }
  31023. }
  31024. if (this.onLODLevelSelection) {
  31025. this.onLODLevelSelection(distanceToCamera, this, this);
  31026. }
  31027. return this;
  31028. };
  31029. Object.defineProperty(Mesh.prototype, "geometry", {
  31030. /**
  31031. * Returns the mesh internal Geometry object.
  31032. */
  31033. get: function () {
  31034. return this._geometry;
  31035. },
  31036. enumerable: true,
  31037. configurable: true
  31038. });
  31039. /**
  31040. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31041. */
  31042. Mesh.prototype.getTotalVertices = function () {
  31043. if (this._geometry === null || this._geometry === undefined) {
  31044. return 0;
  31045. }
  31046. return this._geometry.getTotalVertices();
  31047. };
  31048. /**
  31049. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31050. * 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.
  31051. * You can force the copy with forceCopy === true
  31052. * Returns null if the mesh has no geometry or no vertex buffer.
  31053. * Possible `kind` values :
  31054. * - BABYLON.VertexBuffer.PositionKind
  31055. * - BABYLON.VertexBuffer.UVKind
  31056. * - BABYLON.VertexBuffer.UV2Kind
  31057. * - BABYLON.VertexBuffer.UV3Kind
  31058. * - BABYLON.VertexBuffer.UV4Kind
  31059. * - BABYLON.VertexBuffer.UV5Kind
  31060. * - BABYLON.VertexBuffer.UV6Kind
  31061. * - BABYLON.VertexBuffer.ColorKind
  31062. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31063. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31064. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31065. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31066. */
  31067. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31068. if (!this._geometry) {
  31069. return null;
  31070. }
  31071. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31072. };
  31073. /**
  31074. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31075. * Returns `null` if the mesh has no geometry.
  31076. * Possible `kind` values :
  31077. * - BABYLON.VertexBuffer.PositionKind
  31078. * - BABYLON.VertexBuffer.UVKind
  31079. * - BABYLON.VertexBuffer.UV2Kind
  31080. * - BABYLON.VertexBuffer.UV3Kind
  31081. * - BABYLON.VertexBuffer.UV4Kind
  31082. * - BABYLON.VertexBuffer.UV5Kind
  31083. * - BABYLON.VertexBuffer.UV6Kind
  31084. * - BABYLON.VertexBuffer.ColorKind
  31085. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31086. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31087. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31088. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31089. */
  31090. Mesh.prototype.getVertexBuffer = function (kind) {
  31091. if (!this._geometry) {
  31092. return null;
  31093. }
  31094. return this._geometry.getVertexBuffer(kind);
  31095. };
  31096. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31097. if (!this._geometry) {
  31098. if (this._delayInfo) {
  31099. return this._delayInfo.indexOf(kind) !== -1;
  31100. }
  31101. return false;
  31102. }
  31103. return this._geometry.isVerticesDataPresent(kind);
  31104. };
  31105. /**
  31106. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31107. * Possible `kind` values :
  31108. * - BABYLON.VertexBuffer.PositionKind
  31109. * - BABYLON.VertexBuffer.UVKind
  31110. * - BABYLON.VertexBuffer.UV2Kind
  31111. * - BABYLON.VertexBuffer.UV3Kind
  31112. * - BABYLON.VertexBuffer.UV4Kind
  31113. * - BABYLON.VertexBuffer.UV5Kind
  31114. * - BABYLON.VertexBuffer.UV6Kind
  31115. * - BABYLON.VertexBuffer.ColorKind
  31116. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31117. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31118. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31119. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31120. */
  31121. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31122. if (!this._geometry) {
  31123. if (this._delayInfo) {
  31124. return this._delayInfo.indexOf(kind) !== -1;
  31125. }
  31126. return false;
  31127. }
  31128. return this._geometry.isVertexBufferUpdatable(kind);
  31129. };
  31130. /**
  31131. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31132. * Possible `kind` values :
  31133. * - BABYLON.VertexBuffer.PositionKind
  31134. * - BABYLON.VertexBuffer.UVKind
  31135. * - BABYLON.VertexBuffer.UV2Kind
  31136. * - BABYLON.VertexBuffer.UV3Kind
  31137. * - BABYLON.VertexBuffer.UV4Kind
  31138. * - BABYLON.VertexBuffer.UV5Kind
  31139. * - BABYLON.VertexBuffer.UV6Kind
  31140. * - BABYLON.VertexBuffer.ColorKind
  31141. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31142. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31143. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31144. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31145. */
  31146. Mesh.prototype.getVerticesDataKinds = function () {
  31147. if (!this._geometry) {
  31148. var result = new Array();
  31149. if (this._delayInfo) {
  31150. this._delayInfo.forEach(function (kind, index, array) {
  31151. result.push(kind);
  31152. });
  31153. }
  31154. return result;
  31155. }
  31156. return this._geometry.getVerticesDataKinds();
  31157. };
  31158. /**
  31159. * Returns a positive integer : the total number of indices in this mesh geometry.
  31160. * Returns zero if the mesh has no geometry.
  31161. */
  31162. Mesh.prototype.getTotalIndices = function () {
  31163. if (!this._geometry) {
  31164. return 0;
  31165. }
  31166. return this._geometry.getTotalIndices();
  31167. };
  31168. /**
  31169. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31170. * 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.
  31171. * Returns an empty array if the mesh has no geometry.
  31172. */
  31173. Mesh.prototype.getIndices = function (copyWhenShared) {
  31174. if (!this._geometry) {
  31175. return [];
  31176. }
  31177. return this._geometry.getIndices(copyWhenShared);
  31178. };
  31179. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31180. get: function () {
  31181. return this._masterMesh !== null && this._masterMesh !== undefined;
  31182. },
  31183. enumerable: true,
  31184. configurable: true
  31185. });
  31186. /**
  31187. * Determine if the current mesh is ready to be rendered
  31188. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31189. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31190. * @returns true if all associated assets are ready (material, textures, shaders)
  31191. */
  31192. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31193. if (completeCheck === void 0) { completeCheck = false; }
  31194. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31195. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31196. return false;
  31197. }
  31198. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31199. return false;
  31200. }
  31201. if (!this.subMeshes || this.subMeshes.length === 0) {
  31202. return true;
  31203. }
  31204. if (!completeCheck) {
  31205. return true;
  31206. }
  31207. var engine = this.getEngine();
  31208. var scene = this.getScene();
  31209. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31210. this.computeWorldMatrix();
  31211. var mat = this.material || scene.defaultMaterial;
  31212. if (mat) {
  31213. if (mat.storeEffectOnSubMeshes) {
  31214. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31215. var subMesh = _a[_i];
  31216. var effectiveMaterial = subMesh.getMaterial();
  31217. if (effectiveMaterial) {
  31218. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31219. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31220. return false;
  31221. }
  31222. }
  31223. else {
  31224. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31225. return false;
  31226. }
  31227. }
  31228. }
  31229. }
  31230. }
  31231. else {
  31232. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31233. return false;
  31234. }
  31235. }
  31236. }
  31237. // Shadows
  31238. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31239. var light = _c[_b];
  31240. var generator = light.getShadowGenerator();
  31241. if (generator) {
  31242. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31243. var subMesh = _e[_d];
  31244. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31245. return false;
  31246. }
  31247. }
  31248. }
  31249. }
  31250. // LOD
  31251. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31252. var lod = _g[_f];
  31253. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31254. return false;
  31255. }
  31256. }
  31257. return true;
  31258. };
  31259. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31260. /**
  31261. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31262. * This property is pertinent only for updatable parametric shapes.
  31263. */
  31264. get: function () {
  31265. return this._areNormalsFrozen;
  31266. },
  31267. enumerable: true,
  31268. configurable: true
  31269. });
  31270. /**
  31271. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31272. * It has no effect at all on other shapes.
  31273. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31274. * Returns the Mesh.
  31275. */
  31276. Mesh.prototype.freezeNormals = function () {
  31277. this._areNormalsFrozen = true;
  31278. return this;
  31279. };
  31280. /**
  31281. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31282. * It has no effect at all on other shapes.
  31283. * It reactivates the mesh normals computation if it was previously frozen.
  31284. * Returns the Mesh.
  31285. */
  31286. Mesh.prototype.unfreezeNormals = function () {
  31287. this._areNormalsFrozen = false;
  31288. return this;
  31289. };
  31290. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31291. /**
  31292. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31293. */
  31294. set: function (count) {
  31295. this._overridenInstanceCount = count;
  31296. },
  31297. enumerable: true,
  31298. configurable: true
  31299. });
  31300. // Methods
  31301. Mesh.prototype._preActivate = function () {
  31302. var sceneRenderId = this.getScene().getRenderId();
  31303. if (this._preActivateId === sceneRenderId) {
  31304. return this;
  31305. }
  31306. this._preActivateId = sceneRenderId;
  31307. this._visibleInstances = null;
  31308. return this;
  31309. };
  31310. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31311. if (this._visibleInstances) {
  31312. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31313. }
  31314. return this;
  31315. };
  31316. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31317. if (!this._visibleInstances) {
  31318. this._visibleInstances = {};
  31319. this._visibleInstances.defaultRenderId = renderId;
  31320. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31321. }
  31322. if (!this._visibleInstances[renderId]) {
  31323. this._visibleInstances[renderId] = new Array();
  31324. }
  31325. this._visibleInstances[renderId].push(instance);
  31326. return this;
  31327. };
  31328. /**
  31329. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31330. * This means the mesh underlying bounding box and sphere are recomputed.
  31331. * Returns the Mesh.
  31332. */
  31333. Mesh.prototype.refreshBoundingInfo = function () {
  31334. return this._refreshBoundingInfo(false);
  31335. };
  31336. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31337. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31338. return this;
  31339. }
  31340. var data = this._getPositionData(applySkeleton);
  31341. if (data) {
  31342. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31343. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31344. }
  31345. if (this.subMeshes) {
  31346. for (var index = 0; index < this.subMeshes.length; index++) {
  31347. this.subMeshes[index].refreshBoundingInfo();
  31348. }
  31349. }
  31350. this._updateBoundingInfo();
  31351. return this;
  31352. };
  31353. Mesh.prototype._getPositionData = function (applySkeleton) {
  31354. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31355. if (data && applySkeleton && this.skeleton) {
  31356. data = BABYLON.Tools.Slice(data);
  31357. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31358. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31359. if (matricesWeightsData && matricesIndicesData) {
  31360. var needExtras = this.numBoneInfluencers > 4;
  31361. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31362. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31363. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31364. var tempVector = BABYLON.Tmp.Vector3[0];
  31365. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31366. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31367. var matWeightIdx = 0;
  31368. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31369. finalMatrix.reset();
  31370. var inf;
  31371. var weight;
  31372. for (inf = 0; inf < 4; inf++) {
  31373. weight = matricesWeightsData[matWeightIdx + inf];
  31374. if (weight <= 0)
  31375. break;
  31376. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31377. finalMatrix.addToSelf(tempMatrix);
  31378. }
  31379. if (needExtras) {
  31380. for (inf = 0; inf < 4; inf++) {
  31381. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31382. if (weight <= 0)
  31383. break;
  31384. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31385. finalMatrix.addToSelf(tempMatrix);
  31386. }
  31387. }
  31388. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31389. tempVector.toArray(data, index);
  31390. }
  31391. }
  31392. }
  31393. return data;
  31394. };
  31395. Mesh.prototype._createGlobalSubMesh = function (force) {
  31396. var totalVertices = this.getTotalVertices();
  31397. if (!totalVertices || !this.getIndices()) {
  31398. return null;
  31399. }
  31400. // Check if we need to recreate the submeshes
  31401. if (this.subMeshes && this.subMeshes.length > 0) {
  31402. var ib = this.getIndices();
  31403. if (!ib) {
  31404. return null;
  31405. }
  31406. var totalIndices = ib.length;
  31407. var needToRecreate = false;
  31408. if (force) {
  31409. needToRecreate = true;
  31410. }
  31411. else {
  31412. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31413. var submesh = _a[_i];
  31414. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31415. needToRecreate = true;
  31416. break;
  31417. }
  31418. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31419. needToRecreate = true;
  31420. break;
  31421. }
  31422. }
  31423. }
  31424. if (!needToRecreate) {
  31425. return this.subMeshes[0];
  31426. }
  31427. }
  31428. this.releaseSubMeshes();
  31429. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31430. };
  31431. Mesh.prototype.subdivide = function (count) {
  31432. if (count < 1) {
  31433. return;
  31434. }
  31435. var totalIndices = this.getTotalIndices();
  31436. var subdivisionSize = (totalIndices / count) | 0;
  31437. var offset = 0;
  31438. // Ensure that subdivisionSize is a multiple of 3
  31439. while (subdivisionSize % 3 !== 0) {
  31440. subdivisionSize++;
  31441. }
  31442. this.releaseSubMeshes();
  31443. for (var index = 0; index < count; index++) {
  31444. if (offset >= totalIndices) {
  31445. break;
  31446. }
  31447. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31448. offset += subdivisionSize;
  31449. }
  31450. this.synchronizeInstances();
  31451. };
  31452. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31453. if (updatable === void 0) { updatable = false; }
  31454. if (!this._geometry) {
  31455. var vertexData = new BABYLON.VertexData();
  31456. vertexData.set(data, kind);
  31457. var scene = this.getScene();
  31458. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31459. }
  31460. else {
  31461. this._geometry.setVerticesData(kind, data, updatable, stride);
  31462. }
  31463. return this;
  31464. };
  31465. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31466. if (updatable === void 0) { updatable = true; }
  31467. var vb = this.getVertexBuffer(kind);
  31468. if (!vb || vb.isUpdatable() === updatable) {
  31469. return;
  31470. }
  31471. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31472. };
  31473. /**
  31474. * Sets the mesh VertexBuffer.
  31475. * Returns the Mesh.
  31476. */
  31477. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31478. if (!this._geometry) {
  31479. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31480. }
  31481. this._geometry.setVerticesBuffer(buffer);
  31482. return this;
  31483. };
  31484. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31485. if (!this._geometry) {
  31486. return this;
  31487. }
  31488. if (!makeItUnique) {
  31489. this._geometry.updateVerticesData(kind, data, updateExtends);
  31490. }
  31491. else {
  31492. this.makeGeometryUnique();
  31493. this.updateVerticesData(kind, data, updateExtends, false);
  31494. }
  31495. return this;
  31496. };
  31497. /**
  31498. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31499. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31500. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31501. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31502. * Returns the Mesh.
  31503. */
  31504. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31505. if (computeNormals === void 0) { computeNormals = true; }
  31506. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31507. if (!positions) {
  31508. return this;
  31509. }
  31510. positionFunction(positions);
  31511. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31512. if (computeNormals) {
  31513. var indices = this.getIndices();
  31514. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31515. if (!normals) {
  31516. return this;
  31517. }
  31518. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31519. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31520. }
  31521. return this;
  31522. };
  31523. /**
  31524. * Creates a un-shared specific occurence of the geometry for the mesh.
  31525. * Returns the Mesh.
  31526. */
  31527. Mesh.prototype.makeGeometryUnique = function () {
  31528. if (!this._geometry) {
  31529. return this;
  31530. }
  31531. var oldGeometry = this._geometry;
  31532. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31533. oldGeometry.releaseForMesh(this, true);
  31534. geometry.applyToMesh(this);
  31535. return this;
  31536. };
  31537. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31538. if (totalVertices === void 0) { totalVertices = null; }
  31539. if (updatable === void 0) { updatable = false; }
  31540. if (!this._geometry) {
  31541. var vertexData = new BABYLON.VertexData();
  31542. vertexData.indices = indices;
  31543. var scene = this.getScene();
  31544. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31545. }
  31546. else {
  31547. this._geometry.setIndices(indices, totalVertices, updatable);
  31548. }
  31549. return this;
  31550. };
  31551. /**
  31552. * Update the current index buffer
  31553. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31554. * Returns the Mesh.
  31555. */
  31556. Mesh.prototype.updateIndices = function (indices, offset) {
  31557. if (!this._geometry) {
  31558. return this;
  31559. }
  31560. this._geometry.updateIndices(indices, offset);
  31561. return this;
  31562. };
  31563. /**
  31564. * Invert the geometry to move from a right handed system to a left handed one.
  31565. * Returns the Mesh.
  31566. */
  31567. Mesh.prototype.toLeftHanded = function () {
  31568. if (!this._geometry) {
  31569. return this;
  31570. }
  31571. this._geometry.toLeftHanded();
  31572. return this;
  31573. };
  31574. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31575. if (!this._geometry) {
  31576. return this;
  31577. }
  31578. var engine = this.getScene().getEngine();
  31579. // Wireframe
  31580. var indexToBind;
  31581. if (this._unIndexed) {
  31582. indexToBind = null;
  31583. }
  31584. else {
  31585. switch (fillMode) {
  31586. case BABYLON.Material.PointFillMode:
  31587. indexToBind = null;
  31588. break;
  31589. case BABYLON.Material.WireFrameFillMode:
  31590. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31591. break;
  31592. default:
  31593. case BABYLON.Material.TriangleFillMode:
  31594. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31595. break;
  31596. }
  31597. }
  31598. // VBOs
  31599. this._geometry._bind(effect, indexToBind);
  31600. return this;
  31601. };
  31602. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31603. if (alternate === void 0) { alternate = false; }
  31604. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31605. return this;
  31606. }
  31607. this.onBeforeDrawObservable.notifyObservers(this);
  31608. var scene = this.getScene();
  31609. var engine = scene.getEngine();
  31610. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31611. // or triangles as points
  31612. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31613. }
  31614. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31615. // Triangles as wireframe
  31616. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31617. }
  31618. else {
  31619. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31620. }
  31621. if (scene._isAlternateRenderingEnabled && !alternate) {
  31622. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31623. if (!effect || !scene.activeCamera) {
  31624. return this;
  31625. }
  31626. scene._switchToAlternateCameraConfiguration(true);
  31627. this._effectiveMaterial.bindView(effect);
  31628. this._effectiveMaterial.bindViewProjection(effect);
  31629. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31630. this._draw(subMesh, fillMode, instancesCount, true);
  31631. engine.setViewport(scene.activeCamera.viewport);
  31632. scene._switchToAlternateCameraConfiguration(false);
  31633. this._effectiveMaterial.bindView(effect);
  31634. this._effectiveMaterial.bindViewProjection(effect);
  31635. }
  31636. return this;
  31637. };
  31638. /**
  31639. * Registers for this mesh a javascript function called just before the rendering process.
  31640. * This function is passed the current mesh.
  31641. * Return the Mesh.
  31642. */
  31643. Mesh.prototype.registerBeforeRender = function (func) {
  31644. this.onBeforeRenderObservable.add(func);
  31645. return this;
  31646. };
  31647. /**
  31648. * Disposes a previously registered javascript function called before the rendering.
  31649. * This function is passed the current mesh.
  31650. * Returns the Mesh.
  31651. */
  31652. Mesh.prototype.unregisterBeforeRender = function (func) {
  31653. this.onBeforeRenderObservable.removeCallback(func);
  31654. return this;
  31655. };
  31656. /**
  31657. * Registers for this mesh a javascript function called just after the rendering is complete.
  31658. * This function is passed the current mesh.
  31659. * Returns the Mesh.
  31660. */
  31661. Mesh.prototype.registerAfterRender = function (func) {
  31662. this.onAfterRenderObservable.add(func);
  31663. return this;
  31664. };
  31665. /**
  31666. * Disposes a previously registered javascript function called after the rendering.
  31667. * This function is passed the current mesh.
  31668. * Return the Mesh.
  31669. */
  31670. Mesh.prototype.unregisterAfterRender = function (func) {
  31671. this.onAfterRenderObservable.removeCallback(func);
  31672. return this;
  31673. };
  31674. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31675. var scene = this.getScene();
  31676. this._batchCache.mustReturn = false;
  31677. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31678. this._batchCache.visibleInstances[subMeshId] = null;
  31679. if (this._visibleInstances) {
  31680. var currentRenderId = scene.getRenderId();
  31681. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31682. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31683. var selfRenderId = this._renderId;
  31684. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31685. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31686. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31687. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31688. }
  31689. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31690. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31691. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31692. this._batchCache.mustReturn = true;
  31693. return this._batchCache;
  31694. }
  31695. if (currentRenderId !== selfRenderId) {
  31696. this._batchCache.renderSelf[subMeshId] = false;
  31697. }
  31698. }
  31699. this._renderIdForInstances[subMeshId] = currentRenderId;
  31700. }
  31701. return this._batchCache;
  31702. };
  31703. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31704. var visibleInstances = batch.visibleInstances[subMesh._id];
  31705. if (!visibleInstances) {
  31706. return this;
  31707. }
  31708. var matricesCount = visibleInstances.length + 1;
  31709. var bufferSize = matricesCount * 16 * 4;
  31710. var currentInstancesBufferSize = this._instancesBufferSize;
  31711. var instancesBuffer = this._instancesBuffer;
  31712. while (this._instancesBufferSize < bufferSize) {
  31713. this._instancesBufferSize *= 2;
  31714. }
  31715. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31716. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31717. }
  31718. var offset = 0;
  31719. var instancesCount = 0;
  31720. var world = this.getWorldMatrix();
  31721. if (batch.renderSelf[subMesh._id]) {
  31722. world.copyToArray(this._instancesData, offset);
  31723. offset += 16;
  31724. instancesCount++;
  31725. }
  31726. if (visibleInstances) {
  31727. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31728. var instance = visibleInstances[instanceIndex];
  31729. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31730. offset += 16;
  31731. instancesCount++;
  31732. }
  31733. }
  31734. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31735. if (instancesBuffer) {
  31736. instancesBuffer.dispose();
  31737. }
  31738. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31739. this._instancesBuffer = instancesBuffer;
  31740. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31741. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31742. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31743. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31744. }
  31745. else {
  31746. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31747. }
  31748. this._bind(subMesh, effect, fillMode);
  31749. this._draw(subMesh, fillMode, instancesCount);
  31750. engine.unbindInstanceAttributes();
  31751. return this;
  31752. };
  31753. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31754. var scene = this.getScene();
  31755. var engine = scene.getEngine();
  31756. if (hardwareInstancedRendering) {
  31757. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31758. }
  31759. else {
  31760. if (batch.renderSelf[subMesh._id]) {
  31761. // Draw
  31762. if (onBeforeDraw) {
  31763. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31764. }
  31765. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31766. }
  31767. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31768. if (visibleInstancesForSubMesh) {
  31769. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31770. var instance = visibleInstancesForSubMesh[instanceIndex];
  31771. // World
  31772. var world = instance.getWorldMatrix();
  31773. if (onBeforeDraw) {
  31774. onBeforeDraw(true, world, effectiveMaterial);
  31775. }
  31776. // Draw
  31777. this._draw(subMesh, fillMode);
  31778. }
  31779. }
  31780. }
  31781. return this;
  31782. };
  31783. /**
  31784. * Triggers the draw call for the mesh.
  31785. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31786. * Returns the Mesh.
  31787. */
  31788. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31789. this._checkOcclusionQuery();
  31790. if (this._isOccluded) {
  31791. return this;
  31792. }
  31793. var scene = this.getScene();
  31794. // Managing instances
  31795. var batch = this._getInstancesRenderList(subMesh._id);
  31796. if (batch.mustReturn) {
  31797. return this;
  31798. }
  31799. // Checking geometry state
  31800. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31801. return this;
  31802. }
  31803. this.onBeforeRenderObservable.notifyObservers(this);
  31804. var engine = scene.getEngine();
  31805. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31806. // Material
  31807. var material = subMesh.getMaterial();
  31808. if (!material) {
  31809. return this;
  31810. }
  31811. this._effectiveMaterial = material;
  31812. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31813. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31814. return this;
  31815. }
  31816. }
  31817. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31818. return this;
  31819. }
  31820. // Alpha mode
  31821. if (enableAlphaMode) {
  31822. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  31823. }
  31824. // Outline - step 1
  31825. var savedDepthWrite = engine.getDepthWrite();
  31826. if (this.renderOutline) {
  31827. engine.setDepthWrite(false);
  31828. scene.getOutlineRenderer().render(subMesh, batch);
  31829. engine.setDepthWrite(savedDepthWrite);
  31830. }
  31831. var effect;
  31832. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31833. effect = subMesh.effect;
  31834. }
  31835. else {
  31836. effect = this._effectiveMaterial.getEffect();
  31837. }
  31838. if (!effect) {
  31839. return this;
  31840. }
  31841. var sideOrientation = this.overrideMaterialSideOrientation;
  31842. if (sideOrientation == null) {
  31843. sideOrientation = this._effectiveMaterial.sideOrientation;
  31844. if (this._getWorldMatrixDeterminant() < 0) {
  31845. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  31846. }
  31847. }
  31848. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  31849. if (this._effectiveMaterial.forceDepthWrite) {
  31850. engine.setDepthWrite(true);
  31851. }
  31852. // Bind
  31853. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  31854. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  31855. this._bind(subMesh, effect, fillMode);
  31856. }
  31857. var world = this.getWorldMatrix();
  31858. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  31859. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  31860. }
  31861. else {
  31862. this._effectiveMaterial.bind(world, this);
  31863. }
  31864. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  31865. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  31866. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31867. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  31868. }
  31869. // Draw
  31870. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  31871. // Unbind
  31872. this._effectiveMaterial.unbind();
  31873. // Outline - step 2
  31874. if (this.renderOutline && savedDepthWrite) {
  31875. engine.setDepthWrite(true);
  31876. engine.setColorWrite(false);
  31877. scene.getOutlineRenderer().render(subMesh, batch);
  31878. engine.setColorWrite(true);
  31879. }
  31880. // Overlay
  31881. if (this.renderOverlay) {
  31882. var currentMode = engine.getAlphaMode();
  31883. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31884. scene.getOutlineRenderer().render(subMesh, batch, true);
  31885. engine.setAlphaMode(currentMode);
  31886. }
  31887. this.onAfterRenderObservable.notifyObservers(this);
  31888. return this;
  31889. };
  31890. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  31891. if (isInstance && effectiveMaterial) {
  31892. effectiveMaterial.bindOnlyWorldMatrix(world);
  31893. }
  31894. };
  31895. /**
  31896. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  31897. */
  31898. Mesh.prototype.getEmittedParticleSystems = function () {
  31899. var results = new Array();
  31900. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31901. var particleSystem = this.getScene().particleSystems[index];
  31902. if (particleSystem.emitter === this) {
  31903. results.push(particleSystem);
  31904. }
  31905. }
  31906. return results;
  31907. };
  31908. /**
  31909. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  31910. */
  31911. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  31912. var results = new Array();
  31913. var descendants = this.getDescendants();
  31914. descendants.push(this);
  31915. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  31916. var particleSystem = this.getScene().particleSystems[index];
  31917. var emitter = particleSystem.emitter;
  31918. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  31919. results.push(particleSystem);
  31920. }
  31921. }
  31922. return results;
  31923. };
  31924. Mesh.prototype._checkDelayState = function () {
  31925. var scene = this.getScene();
  31926. if (this._geometry) {
  31927. this._geometry.load(scene);
  31928. }
  31929. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31930. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  31931. this._queueLoad(scene);
  31932. }
  31933. return this;
  31934. };
  31935. Mesh.prototype._queueLoad = function (scene) {
  31936. var _this = this;
  31937. scene._addPendingData(this);
  31938. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  31939. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  31940. if (data instanceof ArrayBuffer) {
  31941. _this._delayLoadingFunction(data, _this);
  31942. }
  31943. else {
  31944. _this._delayLoadingFunction(JSON.parse(data), _this);
  31945. }
  31946. _this.instances.forEach(function (instance) {
  31947. instance._syncSubMeshes();
  31948. });
  31949. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31950. scene._removePendingData(_this);
  31951. }, function () { }, scene.database, getBinaryData);
  31952. return this;
  31953. };
  31954. /**
  31955. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  31956. */
  31957. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  31958. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31959. return false;
  31960. }
  31961. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  31962. return false;
  31963. }
  31964. this._checkDelayState();
  31965. return true;
  31966. };
  31967. /**
  31968. * Sets the mesh material by the material or multiMaterial `id` property.
  31969. * The material `id` is a string identifying the material or the multiMaterial.
  31970. * This method returns the Mesh.
  31971. */
  31972. Mesh.prototype.setMaterialByID = function (id) {
  31973. var materials = this.getScene().materials;
  31974. var index;
  31975. for (index = materials.length - 1; index > -1; index--) {
  31976. if (materials[index].id === id) {
  31977. this.material = materials[index];
  31978. return this;
  31979. }
  31980. }
  31981. // Multi
  31982. var multiMaterials = this.getScene().multiMaterials;
  31983. for (index = multiMaterials.length - 1; index > -1; index--) {
  31984. if (multiMaterials[index].id === id) {
  31985. this.material = multiMaterials[index];
  31986. return this;
  31987. }
  31988. }
  31989. return this;
  31990. };
  31991. /**
  31992. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  31993. */
  31994. Mesh.prototype.getAnimatables = function () {
  31995. var results = new Array();
  31996. if (this.material) {
  31997. results.push(this.material);
  31998. }
  31999. if (this.skeleton) {
  32000. results.push(this.skeleton);
  32001. }
  32002. return results;
  32003. };
  32004. /**
  32005. * Modifies the mesh geometry according to the passed transformation matrix.
  32006. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32007. * The mesh normals are modified accordingly the same transformation.
  32008. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  32009. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32010. * Returns the Mesh.
  32011. */
  32012. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32013. // Position
  32014. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32015. return this;
  32016. }
  32017. var submeshes = this.subMeshes.splice(0);
  32018. this._resetPointsArrayCache();
  32019. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32020. var temp = new Array();
  32021. var index;
  32022. for (index = 0; index < data.length; index += 3) {
  32023. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32024. }
  32025. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32026. // Normals
  32027. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32028. return this;
  32029. }
  32030. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32031. temp = [];
  32032. for (index = 0; index < data.length; index += 3) {
  32033. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32034. }
  32035. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32036. // flip faces?
  32037. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32038. this.flipFaces();
  32039. }
  32040. // Restore submeshes
  32041. this.releaseSubMeshes();
  32042. this.subMeshes = submeshes;
  32043. return this;
  32044. };
  32045. /**
  32046. * Modifies the mesh geometry according to its own current World Matrix.
  32047. * The mesh World Matrix is then reset.
  32048. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32049. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32050. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32051. * Returns the Mesh.
  32052. */
  32053. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32054. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32055. this.scaling.copyFromFloats(1, 1, 1);
  32056. this.position.copyFromFloats(0, 0, 0);
  32057. this.rotation.copyFromFloats(0, 0, 0);
  32058. //only if quaternion is already set
  32059. if (this.rotationQuaternion) {
  32060. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32061. }
  32062. this._worldMatrix = BABYLON.Matrix.Identity();
  32063. return this;
  32064. };
  32065. Object.defineProperty(Mesh.prototype, "_positions", {
  32066. // Cache
  32067. get: function () {
  32068. if (this._geometry) {
  32069. return this._geometry._positions;
  32070. }
  32071. return null;
  32072. },
  32073. enumerable: true,
  32074. configurable: true
  32075. });
  32076. Mesh.prototype._resetPointsArrayCache = function () {
  32077. if (this._geometry) {
  32078. this._geometry._resetPointsArrayCache();
  32079. }
  32080. return this;
  32081. };
  32082. Mesh.prototype._generatePointsArray = function () {
  32083. if (this._geometry) {
  32084. return this._geometry._generatePointsArray();
  32085. }
  32086. return false;
  32087. };
  32088. /**
  32089. * Returns a new Mesh object generated from the current mesh properties.
  32090. * This method must not get confused with createInstance().
  32091. * The parameter `name` is a string, the name given to the new mesh.
  32092. * The optional parameter `newParent` can be any Node object (default `null`).
  32093. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32094. * 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.
  32095. */
  32096. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32097. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32098. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32099. };
  32100. /**
  32101. * Releases resources associated with this mesh.
  32102. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32103. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32104. */
  32105. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32106. var _this = this;
  32107. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32108. this.morphTargetManager = null;
  32109. if (this._geometry) {
  32110. this._geometry.releaseForMesh(this, true);
  32111. }
  32112. // Sources
  32113. var meshes = this.getScene().meshes;
  32114. meshes.forEach(function (abstractMesh) {
  32115. var mesh = abstractMesh;
  32116. if (mesh._source && mesh._source === _this) {
  32117. mesh._source = null;
  32118. }
  32119. });
  32120. this._source = null;
  32121. // Instances
  32122. if (this._instancesBuffer) {
  32123. this._instancesBuffer.dispose();
  32124. this._instancesBuffer = null;
  32125. }
  32126. while (this.instances.length) {
  32127. this.instances[0].dispose();
  32128. }
  32129. // Effect layers.
  32130. var effectLayers = this.getScene().effectLayers;
  32131. for (var i = 0; i < effectLayers.length; i++) {
  32132. var effectLayer = effectLayers[i];
  32133. if (effectLayer) {
  32134. effectLayer._disposeMesh(this);
  32135. }
  32136. }
  32137. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32138. };
  32139. /**
  32140. * Modifies the mesh geometry according to a displacement map.
  32141. * 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.
  32142. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32143. * This method returns nothing.
  32144. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32145. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32146. * 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.
  32147. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32148. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32149. *
  32150. * Returns the Mesh.
  32151. */
  32152. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32153. var _this = this;
  32154. var scene = this.getScene();
  32155. var onload = function (img) {
  32156. // Getting height map data
  32157. var canvas = document.createElement("canvas");
  32158. var context = canvas.getContext("2d");
  32159. var heightMapWidth = img.width;
  32160. var heightMapHeight = img.height;
  32161. canvas.width = heightMapWidth;
  32162. canvas.height = heightMapHeight;
  32163. context.drawImage(img, 0, 0);
  32164. // Create VertexData from map data
  32165. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32166. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32167. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32168. //execute success callback, if set
  32169. if (onSuccess) {
  32170. onSuccess(_this);
  32171. }
  32172. };
  32173. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32174. return this;
  32175. };
  32176. /**
  32177. * Modifies the mesh geometry according to a displacementMap buffer.
  32178. * 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.
  32179. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32180. * This method returns nothing.
  32181. * 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.
  32182. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32183. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32184. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32185. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32186. *
  32187. * Returns the Mesh.
  32188. */
  32189. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32190. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32191. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32192. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32193. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32194. return this;
  32195. }
  32196. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32197. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32198. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32199. var position = BABYLON.Vector3.Zero();
  32200. var normal = BABYLON.Vector3.Zero();
  32201. var uv = BABYLON.Vector2.Zero();
  32202. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32203. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32204. for (var index = 0; index < positions.length; index += 3) {
  32205. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32206. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32207. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32208. // Compute height
  32209. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32210. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32211. var pos = (u + v * heightMapWidth) * 4;
  32212. var r = buffer[pos] / 255.0;
  32213. var g = buffer[pos + 1] / 255.0;
  32214. var b = buffer[pos + 2] / 255.0;
  32215. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32216. normal.normalize();
  32217. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32218. position = position.add(normal);
  32219. position.toArray(positions, index);
  32220. }
  32221. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32222. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32223. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32224. return this;
  32225. };
  32226. /**
  32227. * Modify the mesh to get a flat shading rendering.
  32228. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32229. * This method returns the Mesh.
  32230. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32231. */
  32232. Mesh.prototype.convertToFlatShadedMesh = function () {
  32233. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32234. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32235. var kinds = this.getVerticesDataKinds();
  32236. var vbs = {};
  32237. var data = {};
  32238. var newdata = {};
  32239. var updatableNormals = false;
  32240. var kindIndex;
  32241. var kind;
  32242. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32243. kind = kinds[kindIndex];
  32244. var vertexBuffer = this.getVertexBuffer(kind);
  32245. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32246. updatableNormals = vertexBuffer.isUpdatable();
  32247. kinds.splice(kindIndex, 1);
  32248. kindIndex--;
  32249. continue;
  32250. }
  32251. vbs[kind] = vertexBuffer;
  32252. data[kind] = vbs[kind].getData();
  32253. newdata[kind] = [];
  32254. }
  32255. // Save previous submeshes
  32256. var previousSubmeshes = this.subMeshes.slice(0);
  32257. var indices = this.getIndices();
  32258. var totalIndices = this.getTotalIndices();
  32259. // Generating unique vertices per face
  32260. var index;
  32261. for (index = 0; index < totalIndices; index++) {
  32262. var vertexIndex = indices[index];
  32263. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32264. kind = kinds[kindIndex];
  32265. var stride = vbs[kind].getStrideSize();
  32266. for (var offset = 0; offset < stride; offset++) {
  32267. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32268. }
  32269. }
  32270. }
  32271. // Updating faces & normal
  32272. var normals = [];
  32273. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32274. for (index = 0; index < totalIndices; index += 3) {
  32275. indices[index] = index;
  32276. indices[index + 1] = index + 1;
  32277. indices[index + 2] = index + 2;
  32278. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32279. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32280. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32281. var p1p2 = p1.subtract(p2);
  32282. var p3p2 = p3.subtract(p2);
  32283. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32284. // Store same normals for every vertex
  32285. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32286. normals.push(normal.x);
  32287. normals.push(normal.y);
  32288. normals.push(normal.z);
  32289. }
  32290. }
  32291. this.setIndices(indices);
  32292. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32293. // Updating vertex buffers
  32294. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32295. kind = kinds[kindIndex];
  32296. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32297. }
  32298. // Updating submeshes
  32299. this.releaseSubMeshes();
  32300. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32301. var previousOne = previousSubmeshes[submeshIndex];
  32302. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32303. }
  32304. this.synchronizeInstances();
  32305. return this;
  32306. };
  32307. /**
  32308. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32309. * In other words, more vertices, no more indices and a single bigger VBO.
  32310. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32311. * Returns the Mesh.
  32312. */
  32313. Mesh.prototype.convertToUnIndexedMesh = function () {
  32314. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32315. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32316. var kinds = this.getVerticesDataKinds();
  32317. var vbs = {};
  32318. var data = {};
  32319. var newdata = {};
  32320. var kindIndex;
  32321. var kind;
  32322. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32323. kind = kinds[kindIndex];
  32324. var vertexBuffer = this.getVertexBuffer(kind);
  32325. vbs[kind] = vertexBuffer;
  32326. data[kind] = vbs[kind].getData();
  32327. newdata[kind] = [];
  32328. }
  32329. // Save previous submeshes
  32330. var previousSubmeshes = this.subMeshes.slice(0);
  32331. var indices = this.getIndices();
  32332. var totalIndices = this.getTotalIndices();
  32333. // Generating unique vertices per face
  32334. var index;
  32335. for (index = 0; index < totalIndices; index++) {
  32336. var vertexIndex = indices[index];
  32337. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32338. kind = kinds[kindIndex];
  32339. var stride = vbs[kind].getStrideSize();
  32340. for (var offset = 0; offset < stride; offset++) {
  32341. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32342. }
  32343. }
  32344. }
  32345. // Updating indices
  32346. for (index = 0; index < totalIndices; index += 3) {
  32347. indices[index] = index;
  32348. indices[index + 1] = index + 1;
  32349. indices[index + 2] = index + 2;
  32350. }
  32351. this.setIndices(indices);
  32352. // Updating vertex buffers
  32353. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32354. kind = kinds[kindIndex];
  32355. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32356. }
  32357. // Updating submeshes
  32358. this.releaseSubMeshes();
  32359. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32360. var previousOne = previousSubmeshes[submeshIndex];
  32361. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32362. }
  32363. this._unIndexed = true;
  32364. this.synchronizeInstances();
  32365. return this;
  32366. };
  32367. /**
  32368. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32369. * This method returns the Mesh.
  32370. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32371. */
  32372. Mesh.prototype.flipFaces = function (flipNormals) {
  32373. if (flipNormals === void 0) { flipNormals = false; }
  32374. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32375. var i;
  32376. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32377. for (i = 0; i < vertex_data.normals.length; i++) {
  32378. vertex_data.normals[i] *= -1;
  32379. }
  32380. }
  32381. if (vertex_data.indices) {
  32382. var temp;
  32383. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32384. // reassign indices
  32385. temp = vertex_data.indices[i + 1];
  32386. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32387. vertex_data.indices[i + 2] = temp;
  32388. }
  32389. }
  32390. vertex_data.applyToMesh(this);
  32391. return this;
  32392. };
  32393. // Instances
  32394. /**
  32395. * Creates a new InstancedMesh object from the mesh model.
  32396. * An instance shares the same properties and the same material than its model.
  32397. * Only these properties of each instance can then be set individually :
  32398. * - position
  32399. * - rotation
  32400. * - rotationQuaternion
  32401. * - setPivotMatrix
  32402. * - scaling
  32403. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32404. * Warning : this method is not supported for Line mesh and LineSystem
  32405. */
  32406. Mesh.prototype.createInstance = function (name) {
  32407. return new BABYLON.InstancedMesh(name, this);
  32408. };
  32409. /**
  32410. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32411. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32412. * This method returns the Mesh.
  32413. */
  32414. Mesh.prototype.synchronizeInstances = function () {
  32415. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32416. var instance = this.instances[instanceIndex];
  32417. instance._syncSubMeshes();
  32418. }
  32419. return this;
  32420. };
  32421. /**
  32422. * Simplify the mesh according to the given array of settings.
  32423. * Function will return immediately and will simplify async. It returns the Mesh.
  32424. * @param settings a collection of simplification settings.
  32425. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32426. * @param type the type of simplification to run.
  32427. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32428. */
  32429. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32430. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32431. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32432. this.getScene().simplificationQueue.addTask({
  32433. settings: settings,
  32434. parallelProcessing: parallelProcessing,
  32435. mesh: this,
  32436. simplificationType: simplificationType,
  32437. successCallback: successCallback
  32438. });
  32439. return this;
  32440. };
  32441. /**
  32442. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32443. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32444. * This should be used together with the simplification to avoid disappearing triangles.
  32445. * Returns the Mesh.
  32446. * @param successCallback an optional success callback to be called after the optimization finished.
  32447. */
  32448. Mesh.prototype.optimizeIndices = function (successCallback) {
  32449. var _this = this;
  32450. var indices = this.getIndices();
  32451. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32452. if (!positions || !indices) {
  32453. return this;
  32454. }
  32455. var vectorPositions = new Array();
  32456. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32457. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32458. }
  32459. var dupes = new Array();
  32460. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32461. var realPos = vectorPositions.length - 1 - iteration;
  32462. var testedPosition = vectorPositions[realPos];
  32463. for (var j = 0; j < realPos; ++j) {
  32464. var againstPosition = vectorPositions[j];
  32465. if (testedPosition.equals(againstPosition)) {
  32466. dupes[realPos] = j;
  32467. break;
  32468. }
  32469. }
  32470. }, function () {
  32471. for (var i = 0; i < indices.length; ++i) {
  32472. indices[i] = dupes[indices[i]] || indices[i];
  32473. }
  32474. //indices are now reordered
  32475. var originalSubMeshes = _this.subMeshes.slice(0);
  32476. _this.setIndices(indices);
  32477. _this.subMeshes = originalSubMeshes;
  32478. if (successCallback) {
  32479. successCallback(_this);
  32480. }
  32481. });
  32482. return this;
  32483. };
  32484. Mesh.prototype.serialize = function (serializationObject) {
  32485. serializationObject.name = this.name;
  32486. serializationObject.id = this.id;
  32487. serializationObject.type = this.getClassName();
  32488. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32489. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32490. }
  32491. serializationObject.position = this.position.asArray();
  32492. if (this.rotationQuaternion) {
  32493. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32494. }
  32495. else if (this.rotation) {
  32496. serializationObject.rotation = this.rotation.asArray();
  32497. }
  32498. serializationObject.scaling = this.scaling.asArray();
  32499. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32500. serializationObject.isEnabled = this.isEnabled(false);
  32501. serializationObject.isVisible = this.isVisible;
  32502. serializationObject.infiniteDistance = this.infiniteDistance;
  32503. serializationObject.pickable = this.isPickable;
  32504. serializationObject.receiveShadows = this.receiveShadows;
  32505. serializationObject.billboardMode = this.billboardMode;
  32506. serializationObject.visibility = this.visibility;
  32507. serializationObject.checkCollisions = this.checkCollisions;
  32508. serializationObject.isBlocker = this.isBlocker;
  32509. // Parent
  32510. if (this.parent) {
  32511. serializationObject.parentId = this.parent.id;
  32512. }
  32513. // Geometry
  32514. serializationObject.isUnIndexed = this.isUnIndexed;
  32515. var geometry = this._geometry;
  32516. if (geometry) {
  32517. var geometryId = geometry.id;
  32518. serializationObject.geometryId = geometryId;
  32519. // SubMeshes
  32520. serializationObject.subMeshes = [];
  32521. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32522. var subMesh = this.subMeshes[subIndex];
  32523. serializationObject.subMeshes.push({
  32524. materialIndex: subMesh.materialIndex,
  32525. verticesStart: subMesh.verticesStart,
  32526. verticesCount: subMesh.verticesCount,
  32527. indexStart: subMesh.indexStart,
  32528. indexCount: subMesh.indexCount
  32529. });
  32530. }
  32531. }
  32532. // Material
  32533. if (this.material) {
  32534. serializationObject.materialId = this.material.id;
  32535. }
  32536. else {
  32537. this.material = null;
  32538. }
  32539. // Morph targets
  32540. if (this.morphTargetManager) {
  32541. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32542. }
  32543. // Skeleton
  32544. if (this.skeleton) {
  32545. serializationObject.skeletonId = this.skeleton.id;
  32546. }
  32547. // Physics
  32548. //TODO implement correct serialization for physics impostors.
  32549. var impostor = this.getPhysicsImpostor();
  32550. if (impostor) {
  32551. serializationObject.physicsMass = impostor.getParam("mass");
  32552. serializationObject.physicsFriction = impostor.getParam("friction");
  32553. serializationObject.physicsRestitution = impostor.getParam("mass");
  32554. serializationObject.physicsImpostor = impostor.type;
  32555. }
  32556. // Metadata
  32557. if (this.metadata) {
  32558. serializationObject.metadata = this.metadata;
  32559. }
  32560. // Instances
  32561. serializationObject.instances = [];
  32562. for (var index = 0; index < this.instances.length; index++) {
  32563. var instance = this.instances[index];
  32564. var serializationInstance = {
  32565. name: instance.name,
  32566. id: instance.id,
  32567. position: instance.position.asArray(),
  32568. scaling: instance.scaling.asArray()
  32569. };
  32570. if (instance.rotationQuaternion) {
  32571. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32572. }
  32573. else if (instance.rotation) {
  32574. serializationInstance.rotation = instance.rotation.asArray();
  32575. }
  32576. serializationObject.instances.push(serializationInstance);
  32577. // Animations
  32578. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32579. serializationInstance.ranges = instance.serializeAnimationRanges();
  32580. }
  32581. //
  32582. // Animations
  32583. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32584. serializationObject.ranges = this.serializeAnimationRanges();
  32585. // Layer mask
  32586. serializationObject.layerMask = this.layerMask;
  32587. // Alpha
  32588. serializationObject.alphaIndex = this.alphaIndex;
  32589. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32590. // Overlay
  32591. serializationObject.overlayAlpha = this.overlayAlpha;
  32592. serializationObject.overlayColor = this.overlayColor.asArray();
  32593. serializationObject.renderOverlay = this.renderOverlay;
  32594. // Fog
  32595. serializationObject.applyFog = this.applyFog;
  32596. // Action Manager
  32597. if (this.actionManager) {
  32598. serializationObject.actions = this.actionManager.serialize(this.name);
  32599. }
  32600. };
  32601. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32602. if (!this.geometry) {
  32603. return;
  32604. }
  32605. this._markSubMeshesAsAttributesDirty();
  32606. var morphTargetManager = this._morphTargetManager;
  32607. if (morphTargetManager && morphTargetManager.vertexCount) {
  32608. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32609. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32610. this.morphTargetManager = null;
  32611. return;
  32612. }
  32613. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32614. var morphTarget = morphTargetManager.getActiveTarget(index);
  32615. var positions = morphTarget.getPositions();
  32616. if (!positions) {
  32617. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32618. return;
  32619. }
  32620. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32621. var normals = morphTarget.getNormals();
  32622. if (normals) {
  32623. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32624. }
  32625. var tangents = morphTarget.getTangents();
  32626. if (tangents) {
  32627. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32628. }
  32629. }
  32630. }
  32631. else {
  32632. var index = 0;
  32633. // Positions
  32634. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32635. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32636. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32637. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32638. }
  32639. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32640. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32641. }
  32642. index++;
  32643. }
  32644. }
  32645. };
  32646. // Statics
  32647. /**
  32648. * Returns a new Mesh object parsed from the source provided.
  32649. * The parameter `parsedMesh` is the source.
  32650. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32651. */
  32652. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32653. var mesh;
  32654. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32655. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32656. }
  32657. else {
  32658. mesh = new Mesh(parsedMesh.name, scene);
  32659. }
  32660. mesh.id = parsedMesh.id;
  32661. if (BABYLON.Tags) {
  32662. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32663. }
  32664. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32665. if (parsedMesh.metadata !== undefined) {
  32666. mesh.metadata = parsedMesh.metadata;
  32667. }
  32668. if (parsedMesh.rotationQuaternion) {
  32669. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32670. }
  32671. else if (parsedMesh.rotation) {
  32672. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32673. }
  32674. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32675. if (parsedMesh.localMatrix) {
  32676. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32677. }
  32678. else if (parsedMesh.pivotMatrix) {
  32679. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32680. }
  32681. mesh.setEnabled(parsedMesh.isEnabled);
  32682. mesh.isVisible = parsedMesh.isVisible;
  32683. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32684. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32685. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32686. if (parsedMesh.applyFog !== undefined) {
  32687. mesh.applyFog = parsedMesh.applyFog;
  32688. }
  32689. if (parsedMesh.pickable !== undefined) {
  32690. mesh.isPickable = parsedMesh.pickable;
  32691. }
  32692. if (parsedMesh.alphaIndex !== undefined) {
  32693. mesh.alphaIndex = parsedMesh.alphaIndex;
  32694. }
  32695. mesh.receiveShadows = parsedMesh.receiveShadows;
  32696. mesh.billboardMode = parsedMesh.billboardMode;
  32697. if (parsedMesh.visibility !== undefined) {
  32698. mesh.visibility = parsedMesh.visibility;
  32699. }
  32700. mesh.checkCollisions = parsedMesh.checkCollisions;
  32701. if (parsedMesh.isBlocker !== undefined) {
  32702. mesh.isBlocker = parsedMesh.isBlocker;
  32703. }
  32704. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32705. // freezeWorldMatrix
  32706. if (parsedMesh.freezeWorldMatrix) {
  32707. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32708. }
  32709. // Parent
  32710. if (parsedMesh.parentId) {
  32711. mesh._waitingParentId = parsedMesh.parentId;
  32712. }
  32713. // Actions
  32714. if (parsedMesh.actions !== undefined) {
  32715. mesh._waitingActions = parsedMesh.actions;
  32716. }
  32717. // Overlay
  32718. if (parsedMesh.overlayAlpha !== undefined) {
  32719. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32720. }
  32721. if (parsedMesh.overlayColor !== undefined) {
  32722. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32723. }
  32724. if (parsedMesh.renderOverlay !== undefined) {
  32725. mesh.renderOverlay = parsedMesh.renderOverlay;
  32726. }
  32727. // Geometry
  32728. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32729. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32730. if (parsedMesh.delayLoadingFile) {
  32731. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32732. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32733. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32734. if (parsedMesh._binaryInfo) {
  32735. mesh._binaryInfo = parsedMesh._binaryInfo;
  32736. }
  32737. mesh._delayInfo = [];
  32738. if (parsedMesh.hasUVs) {
  32739. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32740. }
  32741. if (parsedMesh.hasUVs2) {
  32742. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32743. }
  32744. if (parsedMesh.hasUVs3) {
  32745. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32746. }
  32747. if (parsedMesh.hasUVs4) {
  32748. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32749. }
  32750. if (parsedMesh.hasUVs5) {
  32751. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32752. }
  32753. if (parsedMesh.hasUVs6) {
  32754. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32755. }
  32756. if (parsedMesh.hasColors) {
  32757. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32758. }
  32759. if (parsedMesh.hasMatricesIndices) {
  32760. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32761. }
  32762. if (parsedMesh.hasMatricesWeights) {
  32763. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32764. }
  32765. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32766. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32767. mesh._checkDelayState();
  32768. }
  32769. }
  32770. else {
  32771. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32772. }
  32773. // Material
  32774. if (parsedMesh.materialId) {
  32775. mesh.setMaterialByID(parsedMesh.materialId);
  32776. }
  32777. else {
  32778. mesh.material = null;
  32779. }
  32780. // Morph targets
  32781. if (parsedMesh.morphTargetManagerId > -1) {
  32782. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32783. }
  32784. // Skeleton
  32785. if (parsedMesh.skeletonId > -1) {
  32786. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32787. if (parsedMesh.numBoneInfluencers) {
  32788. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32789. }
  32790. }
  32791. // Animations
  32792. if (parsedMesh.animations) {
  32793. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32794. var parsedAnimation = parsedMesh.animations[animationIndex];
  32795. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32796. }
  32797. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32798. }
  32799. if (parsedMesh.autoAnimate) {
  32800. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32801. }
  32802. // Layer Mask
  32803. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32804. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32805. }
  32806. else {
  32807. mesh.layerMask = 0x0FFFFFFF;
  32808. }
  32809. // Physics
  32810. if (parsedMesh.physicsImpostor) {
  32811. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  32812. mass: parsedMesh.physicsMass,
  32813. friction: parsedMesh.physicsFriction,
  32814. restitution: parsedMesh.physicsRestitution
  32815. }, scene);
  32816. }
  32817. // Instances
  32818. if (parsedMesh.instances) {
  32819. for (var index = 0; index < parsedMesh.instances.length; index++) {
  32820. var parsedInstance = parsedMesh.instances[index];
  32821. var instance = mesh.createInstance(parsedInstance.name);
  32822. if (parsedInstance.id) {
  32823. instance.id = parsedInstance.id;
  32824. }
  32825. if (BABYLON.Tags) {
  32826. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  32827. }
  32828. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  32829. if (parsedInstance.parentId) {
  32830. instance._waitingParentId = parsedInstance.parentId;
  32831. }
  32832. if (parsedInstance.rotationQuaternion) {
  32833. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  32834. }
  32835. else if (parsedInstance.rotation) {
  32836. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  32837. }
  32838. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  32839. instance.checkCollisions = mesh.checkCollisions;
  32840. if (parsedMesh.animations) {
  32841. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32842. parsedAnimation = parsedMesh.animations[animationIndex];
  32843. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32844. }
  32845. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  32846. }
  32847. }
  32848. }
  32849. return mesh;
  32850. };
  32851. /**
  32852. * Creates a ribbon mesh.
  32853. * Please consider using the same method from the MeshBuilder class instead.
  32854. * 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.
  32855. *
  32856. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  32857. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  32858. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  32859. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  32860. * 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.
  32861. * 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.
  32862. * 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
  32863. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32864. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32865. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32866. */
  32867. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  32868. if (closeArray === void 0) { closeArray = false; }
  32869. if (updatable === void 0) { updatable = false; }
  32870. return BABYLON.MeshBuilder.CreateRibbon(name, {
  32871. pathArray: pathArray,
  32872. closeArray: closeArray,
  32873. closePath: closePath,
  32874. offset: offset,
  32875. updatable: updatable,
  32876. sideOrientation: sideOrientation,
  32877. instance: instance
  32878. }, scene);
  32879. };
  32880. /**
  32881. * Creates a plane polygonal mesh. By default, this is a disc.
  32882. * Please consider using the same method from the MeshBuilder class instead.
  32883. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  32884. * 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.
  32885. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32886. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32887. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32888. */
  32889. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  32890. if (scene === void 0) { scene = null; }
  32891. var options = {
  32892. radius: radius,
  32893. tessellation: tessellation,
  32894. sideOrientation: sideOrientation,
  32895. updatable: updatable
  32896. };
  32897. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  32898. };
  32899. /**
  32900. * Creates a box mesh.
  32901. * Please consider using the same method from the MeshBuilder class instead.
  32902. * The parameter `size` sets the size (float) of each box side (default 1).
  32903. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32904. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32905. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32906. */
  32907. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  32908. if (scene === void 0) { scene = null; }
  32909. var options = {
  32910. size: size,
  32911. sideOrientation: sideOrientation,
  32912. updatable: updatable
  32913. };
  32914. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  32915. };
  32916. /**
  32917. * Creates a sphere mesh.
  32918. * Please consider using the same method from the MeshBuilder class instead.
  32919. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  32920. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  32921. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32922. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32924. */
  32925. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  32926. var options = {
  32927. segments: segments,
  32928. diameterX: diameter,
  32929. diameterY: diameter,
  32930. diameterZ: diameter,
  32931. sideOrientation: sideOrientation,
  32932. updatable: updatable
  32933. };
  32934. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  32935. };
  32936. /**
  32937. * Creates a cylinder or a cone mesh.
  32938. * Please consider using the same method from the MeshBuilder class instead.
  32939. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  32940. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  32941. * 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.
  32942. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  32943. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  32944. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32945. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32946. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32947. */
  32948. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  32949. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  32950. if (scene !== undefined) {
  32951. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  32952. updatable = scene;
  32953. }
  32954. scene = subdivisions;
  32955. subdivisions = 1;
  32956. }
  32957. var options = {
  32958. height: height,
  32959. diameterTop: diameterTop,
  32960. diameterBottom: diameterBottom,
  32961. tessellation: tessellation,
  32962. subdivisions: subdivisions,
  32963. sideOrientation: sideOrientation,
  32964. updatable: updatable
  32965. };
  32966. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  32967. };
  32968. // Torus (Code from SharpDX.org)
  32969. /**
  32970. * Creates a torus mesh.
  32971. * Please consider using the same method from the MeshBuilder class instead.
  32972. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  32973. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  32974. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  32975. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32976. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32977. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32978. */
  32979. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  32980. var options = {
  32981. diameter: diameter,
  32982. thickness: thickness,
  32983. tessellation: tessellation,
  32984. sideOrientation: sideOrientation,
  32985. updatable: updatable
  32986. };
  32987. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  32988. };
  32989. /**
  32990. * Creates a torus knot mesh.
  32991. * Please consider using the same method from the MeshBuilder class instead.
  32992. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  32993. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  32994. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  32995. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  32996. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  32997. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  32998. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  32999. */
  33000. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33001. var options = {
  33002. radius: radius,
  33003. tube: tube,
  33004. radialSegments: radialSegments,
  33005. tubularSegments: tubularSegments,
  33006. p: p,
  33007. q: q,
  33008. sideOrientation: sideOrientation,
  33009. updatable: updatable
  33010. };
  33011. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33012. };
  33013. /**
  33014. * Creates a line mesh.
  33015. * Please consider using the same method from the MeshBuilder class instead.
  33016. * 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.
  33017. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33018. * The parameter `points` is an array successive Vector3.
  33019. * 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
  33020. * When updating an instance, remember that only point positions can change, not the number of points.
  33021. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33022. */
  33023. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33024. if (scene === void 0) { scene = null; }
  33025. if (updatable === void 0) { updatable = false; }
  33026. if (instance === void 0) { instance = null; }
  33027. var options = {
  33028. points: points,
  33029. updatable: updatable,
  33030. instance: instance
  33031. };
  33032. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33033. };
  33034. /**
  33035. * Creates a dashed line mesh.
  33036. * Please consider using the same method from the MeshBuilder class instead.
  33037. * 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.
  33038. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33039. * The parameter `points` is an array successive Vector3.
  33040. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33041. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33042. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33043. * 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
  33044. * When updating an instance, remember that only point positions can change, not the number of points.
  33045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33046. */
  33047. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33048. if (scene === void 0) { scene = null; }
  33049. var options = {
  33050. points: points,
  33051. dashSize: dashSize,
  33052. gapSize: gapSize,
  33053. dashNb: dashNb,
  33054. updatable: updatable,
  33055. instance: instance
  33056. };
  33057. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33058. };
  33059. /**
  33060. * Creates a polygon mesh.
  33061. * Please consider using the same method from the MeshBuilder class instead.
  33062. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33063. * 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.
  33064. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33065. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33066. * Remember you can only change the shape positions, not their number when updating a polygon.
  33067. */
  33068. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33069. var options = {
  33070. shape: shape,
  33071. holes: holes,
  33072. updatable: updatable,
  33073. sideOrientation: sideOrientation
  33074. };
  33075. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33076. };
  33077. /**
  33078. * Creates an extruded polygon mesh, with depth in the Y direction.
  33079. * Please consider using the same method from the MeshBuilder class instead.
  33080. */
  33081. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33082. var options = {
  33083. shape: shape,
  33084. holes: holes,
  33085. depth: depth,
  33086. updatable: updatable,
  33087. sideOrientation: sideOrientation
  33088. };
  33089. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33090. };
  33091. /**
  33092. * Creates an extruded shape mesh.
  33093. * 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.
  33094. * Please consider using the same method from the MeshBuilder class instead.
  33095. *
  33096. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33097. * 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
  33098. * extruded along the Z axis.
  33099. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33100. * 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.
  33101. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33102. * 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
  33103. * 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
  33104. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33105. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33106. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33107. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33108. */
  33109. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33110. if (scene === void 0) { scene = null; }
  33111. var options = {
  33112. shape: shape,
  33113. path: path,
  33114. scale: scale,
  33115. rotation: rotation,
  33116. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33117. sideOrientation: sideOrientation,
  33118. instance: instance,
  33119. updatable: updatable
  33120. };
  33121. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33122. };
  33123. /**
  33124. * Creates an custom extruded shape mesh.
  33125. * 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.
  33126. * Please consider using the same method from the MeshBuilder class instead.
  33127. *
  33128. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  33129. * 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
  33130. * extruded along the Z axis.
  33131. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33132. * 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
  33133. * and the distance of this point from the begining of the path :
  33134. * ```javascript
  33135. * var rotationFunction = function(i, distance) {
  33136. * // do things
  33137. * return rotationValue; }
  33138. * ```
  33139. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33140. * 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
  33141. * and the distance of this point from the begining of the path :
  33142. * ```javascript
  33143. * var scaleFunction = function(i, distance) {
  33144. * // do things
  33145. * return scaleValue;}
  33146. * ```
  33147. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33148. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33149. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33150. * 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
  33151. * 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
  33152. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33153. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33154. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33155. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33156. */
  33157. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33158. var options = {
  33159. shape: shape,
  33160. path: path,
  33161. scaleFunction: scaleFunction,
  33162. rotationFunction: rotationFunction,
  33163. ribbonCloseArray: ribbonCloseArray,
  33164. ribbonClosePath: ribbonClosePath,
  33165. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33166. sideOrientation: sideOrientation,
  33167. instance: instance,
  33168. updatable: updatable
  33169. };
  33170. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33171. };
  33172. /**
  33173. * Creates lathe mesh.
  33174. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33175. * Please consider using the same method from the MeshBuilder class instead.
  33176. * 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
  33177. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33178. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33179. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33180. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33181. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33182. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33183. */
  33184. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33185. var options = {
  33186. shape: shape,
  33187. radius: radius,
  33188. tessellation: tessellation,
  33189. sideOrientation: sideOrientation,
  33190. updatable: updatable
  33191. };
  33192. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33193. };
  33194. /**
  33195. * Creates a plane mesh.
  33196. * Please consider using the same method from the MeshBuilder class instead.
  33197. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33198. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33199. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33201. */
  33202. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33203. var options = {
  33204. size: size,
  33205. width: size,
  33206. height: size,
  33207. sideOrientation: sideOrientation,
  33208. updatable: updatable
  33209. };
  33210. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33211. };
  33212. /**
  33213. * Creates a ground mesh.
  33214. * Please consider using the same method from the MeshBuilder class instead.
  33215. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33216. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33217. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33218. */
  33219. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33220. var options = {
  33221. width: width,
  33222. height: height,
  33223. subdivisions: subdivisions,
  33224. updatable: updatable
  33225. };
  33226. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33227. };
  33228. /**
  33229. * Creates a tiled ground mesh.
  33230. * Please consider using the same method from the MeshBuilder class instead.
  33231. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33232. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33233. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33234. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33235. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33236. * numbers of subdivisions on the ground width and height of each tile.
  33237. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33238. */
  33239. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33240. var options = {
  33241. xmin: xmin,
  33242. zmin: zmin,
  33243. xmax: xmax,
  33244. zmax: zmax,
  33245. subdivisions: subdivisions,
  33246. precision: precision,
  33247. updatable: updatable
  33248. };
  33249. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33250. };
  33251. /**
  33252. * Creates a ground mesh from a height map.
  33253. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  33254. * Please consider using the same method from the MeshBuilder class instead.
  33255. * The parameter `url` sets the URL of the height map image resource.
  33256. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33257. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33258. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33259. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33260. * 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).
  33261. * This function is passed the newly built mesh :
  33262. * ```javascript
  33263. * function(mesh) { // do things
  33264. * return; }
  33265. * ```
  33266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33267. */
  33268. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33269. var options = {
  33270. width: width,
  33271. height: height,
  33272. subdivisions: subdivisions,
  33273. minHeight: minHeight,
  33274. maxHeight: maxHeight,
  33275. updatable: updatable,
  33276. onReady: onReady
  33277. };
  33278. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33279. };
  33280. /**
  33281. * Creates a tube mesh.
  33282. * 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.
  33283. * Please consider using the same method from the MeshBuilder class instead.
  33284. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33285. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33286. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33287. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33288. * 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.
  33289. * It must return a radius value (positive float) :
  33290. * ```javascript
  33291. * var radiusFunction = function(i, distance) {
  33292. * // do things
  33293. * return radius; }
  33294. * ```
  33295. * 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
  33296. * 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
  33297. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33298. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33299. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33300. */
  33301. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33302. var options = {
  33303. path: path,
  33304. radius: radius,
  33305. tessellation: tessellation,
  33306. radiusFunction: radiusFunction,
  33307. arc: 1,
  33308. cap: cap,
  33309. updatable: updatable,
  33310. sideOrientation: sideOrientation,
  33311. instance: instance
  33312. };
  33313. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33314. };
  33315. /**
  33316. * Creates a polyhedron mesh.
  33317. * Please consider using the same method from the MeshBuilder class instead.
  33318. * 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
  33319. * to choose the wanted type.
  33320. * The parameter `size` (positive float, default 1) sets the polygon size.
  33321. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33322. * 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`.
  33323. * 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
  33324. * 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)`).
  33325. * 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
  33326. * 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.
  33327. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33328. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33329. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33330. */
  33331. Mesh.CreatePolyhedron = function (name, options, scene) {
  33332. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33333. };
  33334. /**
  33335. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33336. * Please consider using the same method from the MeshBuilder class instead.
  33337. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33338. * 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`).
  33339. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33340. * 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.
  33341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33342. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  33343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33344. */
  33345. Mesh.CreateIcoSphere = function (name, options, scene) {
  33346. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33347. };
  33348. /**
  33349. * Creates a decal mesh.
  33350. * Please consider using the same method from the MeshBuilder class instead.
  33351. * 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.
  33352. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33353. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33354. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33355. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33356. */
  33357. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33358. var options = {
  33359. position: position,
  33360. normal: normal,
  33361. size: size,
  33362. angle: angle
  33363. };
  33364. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33365. };
  33366. // Skeletons
  33367. /**
  33368. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33369. */
  33370. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33371. if (!this._sourcePositions) {
  33372. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33373. if (!source) {
  33374. return this._sourcePositions;
  33375. }
  33376. this._sourcePositions = new Float32Array(source);
  33377. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33378. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33379. }
  33380. }
  33381. return this._sourcePositions;
  33382. };
  33383. /**
  33384. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33385. */
  33386. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33387. if (!this._sourceNormals) {
  33388. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33389. if (!source) {
  33390. return this._sourceNormals;
  33391. }
  33392. this._sourceNormals = new Float32Array(source);
  33393. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33394. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33395. }
  33396. }
  33397. return this._sourceNormals;
  33398. };
  33399. /**
  33400. * Updates the vertex buffer by applying transformation from the bones.
  33401. * Returns the Mesh.
  33402. *
  33403. * @param {skeleton} skeleton to apply
  33404. */
  33405. Mesh.prototype.applySkeleton = function (skeleton) {
  33406. if (!this.geometry) {
  33407. return this;
  33408. }
  33409. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33410. return this;
  33411. }
  33412. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33413. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33414. return this;
  33415. }
  33416. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33417. return this;
  33418. }
  33419. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33420. return this;
  33421. }
  33422. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33423. return this;
  33424. }
  33425. if (!this._sourcePositions) {
  33426. var submeshes = this.subMeshes.slice();
  33427. this.setPositionsForCPUSkinning();
  33428. this.subMeshes = submeshes;
  33429. }
  33430. if (!this._sourceNormals) {
  33431. this.setNormalsForCPUSkinning();
  33432. }
  33433. // positionsData checks for not being Float32Array will only pass at most once
  33434. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33435. if (!positionsData) {
  33436. return this;
  33437. }
  33438. if (!(positionsData instanceof Float32Array)) {
  33439. positionsData = new Float32Array(positionsData);
  33440. }
  33441. // normalsData checks for not being Float32Array will only pass at most once
  33442. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33443. if (!normalsData) {
  33444. return this;
  33445. }
  33446. if (!(normalsData instanceof Float32Array)) {
  33447. normalsData = new Float32Array(normalsData);
  33448. }
  33449. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33450. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33451. if (!matricesWeightsData || !matricesIndicesData) {
  33452. return this;
  33453. }
  33454. var needExtras = this.numBoneInfluencers > 4;
  33455. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33456. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33457. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33458. var tempVector3 = BABYLON.Vector3.Zero();
  33459. var finalMatrix = new BABYLON.Matrix();
  33460. var tempMatrix = new BABYLON.Matrix();
  33461. var matWeightIdx = 0;
  33462. var inf;
  33463. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33464. var weight;
  33465. for (inf = 0; inf < 4; inf++) {
  33466. weight = matricesWeightsData[matWeightIdx + inf];
  33467. if (weight > 0) {
  33468. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33469. finalMatrix.addToSelf(tempMatrix);
  33470. }
  33471. else
  33472. break;
  33473. }
  33474. if (needExtras) {
  33475. for (inf = 0; inf < 4; inf++) {
  33476. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33477. if (weight > 0) {
  33478. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33479. finalMatrix.addToSelf(tempMatrix);
  33480. }
  33481. else
  33482. break;
  33483. }
  33484. }
  33485. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33486. tempVector3.toArray(positionsData, index);
  33487. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33488. tempVector3.toArray(normalsData, index);
  33489. finalMatrix.reset();
  33490. }
  33491. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33492. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33493. return this;
  33494. };
  33495. // Tools
  33496. /**
  33497. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33498. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33499. */
  33500. Mesh.MinMax = function (meshes) {
  33501. var minVector = null;
  33502. var maxVector = null;
  33503. meshes.forEach(function (mesh, index, array) {
  33504. var boundingInfo = mesh.getBoundingInfo();
  33505. var boundingBox = boundingInfo.boundingBox;
  33506. if (!minVector || !maxVector) {
  33507. minVector = boundingBox.minimumWorld;
  33508. maxVector = boundingBox.maximumWorld;
  33509. }
  33510. else {
  33511. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33512. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33513. }
  33514. });
  33515. if (!minVector || !maxVector) {
  33516. return {
  33517. min: BABYLON.Vector3.Zero(),
  33518. max: BABYLON.Vector3.Zero()
  33519. };
  33520. }
  33521. return {
  33522. min: minVector,
  33523. max: maxVector
  33524. };
  33525. };
  33526. /**
  33527. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33528. */
  33529. Mesh.Center = function (meshesOrMinMaxVector) {
  33530. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33531. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33532. };
  33533. /**
  33534. * Merge the array of meshes into a single mesh for performance reasons.
  33535. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33536. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33537. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33538. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33539. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33540. */
  33541. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33542. if (disposeSource === void 0) { disposeSource = true; }
  33543. var index;
  33544. if (!allow32BitsIndices) {
  33545. var totalVertices = 0;
  33546. // Counting vertices
  33547. for (index = 0; index < meshes.length; index++) {
  33548. if (meshes[index]) {
  33549. totalVertices += meshes[index].getTotalVertices();
  33550. if (totalVertices > 65536) {
  33551. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33552. return null;
  33553. }
  33554. }
  33555. }
  33556. }
  33557. // Merge
  33558. var vertexData = null;
  33559. var otherVertexData;
  33560. var indiceArray = new Array();
  33561. var source = null;
  33562. for (index = 0; index < meshes.length; index++) {
  33563. if (meshes[index]) {
  33564. meshes[index].computeWorldMatrix(true);
  33565. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33566. otherVertexData.transform(meshes[index].getWorldMatrix());
  33567. if (vertexData) {
  33568. vertexData.merge(otherVertexData);
  33569. }
  33570. else {
  33571. vertexData = otherVertexData;
  33572. source = meshes[index];
  33573. }
  33574. if (subdivideWithSubMeshes) {
  33575. indiceArray.push(meshes[index].getTotalIndices());
  33576. }
  33577. }
  33578. }
  33579. source = source;
  33580. if (!meshSubclass) {
  33581. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33582. }
  33583. vertexData.applyToMesh(meshSubclass);
  33584. // Setting properties
  33585. meshSubclass.material = source.material;
  33586. meshSubclass.checkCollisions = source.checkCollisions;
  33587. // Cleaning
  33588. if (disposeSource) {
  33589. for (index = 0; index < meshes.length; index++) {
  33590. if (meshes[index]) {
  33591. meshes[index].dispose();
  33592. }
  33593. }
  33594. }
  33595. // Subdivide
  33596. if (subdivideWithSubMeshes) {
  33597. //-- Suppresions du submesh global
  33598. meshSubclass.releaseSubMeshes();
  33599. index = 0;
  33600. var offset = 0;
  33601. //-- aplique la subdivision en fonction du tableau d'indices
  33602. while (index < indiceArray.length) {
  33603. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33604. offset += indiceArray[index];
  33605. index++;
  33606. }
  33607. }
  33608. return meshSubclass;
  33609. };
  33610. // Consts
  33611. Mesh._FRONTSIDE = 0;
  33612. Mesh._BACKSIDE = 1;
  33613. Mesh._DOUBLESIDE = 2;
  33614. Mesh._DEFAULTSIDE = 0;
  33615. Mesh._NO_CAP = 0;
  33616. Mesh._CAP_START = 1;
  33617. Mesh._CAP_END = 2;
  33618. Mesh._CAP_ALL = 3;
  33619. return Mesh;
  33620. }(BABYLON.AbstractMesh));
  33621. BABYLON.Mesh = Mesh;
  33622. })(BABYLON || (BABYLON = {}));
  33623. //# sourceMappingURL=babylon.mesh.js.map
  33624. var BABYLON;
  33625. (function (BABYLON) {
  33626. var BaseSubMesh = /** @class */ (function () {
  33627. function BaseSubMesh() {
  33628. }
  33629. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33630. get: function () {
  33631. return this._materialEffect;
  33632. },
  33633. enumerable: true,
  33634. configurable: true
  33635. });
  33636. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33637. if (defines === void 0) { defines = null; }
  33638. if (this._materialEffect === effect) {
  33639. if (!effect) {
  33640. this._materialDefines = null;
  33641. }
  33642. return;
  33643. }
  33644. this._materialDefines = defines;
  33645. this._materialEffect = effect;
  33646. };
  33647. return BaseSubMesh;
  33648. }());
  33649. BABYLON.BaseSubMesh = BaseSubMesh;
  33650. var SubMesh = /** @class */ (function (_super) {
  33651. __extends(SubMesh, _super);
  33652. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33653. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33654. var _this = _super.call(this) || this;
  33655. _this.materialIndex = materialIndex;
  33656. _this.verticesStart = verticesStart;
  33657. _this.verticesCount = verticesCount;
  33658. _this.indexStart = indexStart;
  33659. _this.indexCount = indexCount;
  33660. _this._renderId = 0;
  33661. _this._mesh = mesh;
  33662. _this._renderingMesh = renderingMesh || mesh;
  33663. mesh.subMeshes.push(_this);
  33664. _this._trianglePlanes = [];
  33665. _this._id = mesh.subMeshes.length - 1;
  33666. if (createBoundingBox) {
  33667. _this.refreshBoundingInfo();
  33668. mesh.computeWorldMatrix(true);
  33669. }
  33670. return _this;
  33671. }
  33672. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33673. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33674. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33675. };
  33676. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33677. get: function () {
  33678. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33679. },
  33680. enumerable: true,
  33681. configurable: true
  33682. });
  33683. /**
  33684. * Returns the submesh BoudingInfo object.
  33685. */
  33686. SubMesh.prototype.getBoundingInfo = function () {
  33687. if (this.IsGlobal) {
  33688. return this._mesh.getBoundingInfo();
  33689. }
  33690. return this._boundingInfo;
  33691. };
  33692. /**
  33693. * Sets the submesh BoundingInfo.
  33694. * Return the SubMesh.
  33695. */
  33696. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33697. this._boundingInfo = boundingInfo;
  33698. return this;
  33699. };
  33700. /**
  33701. * Returns the mesh of the current submesh.
  33702. */
  33703. SubMesh.prototype.getMesh = function () {
  33704. return this._mesh;
  33705. };
  33706. /**
  33707. * Returns the rendering mesh of the submesh.
  33708. */
  33709. SubMesh.prototype.getRenderingMesh = function () {
  33710. return this._renderingMesh;
  33711. };
  33712. /**
  33713. * Returns the submesh material.
  33714. */
  33715. SubMesh.prototype.getMaterial = function () {
  33716. var rootMaterial = this._renderingMesh.material;
  33717. if (rootMaterial === null || rootMaterial === undefined) {
  33718. return this._mesh.getScene().defaultMaterial;
  33719. }
  33720. else if (rootMaterial.getSubMaterial) {
  33721. var multiMaterial = rootMaterial;
  33722. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33723. if (this._currentMaterial !== effectiveMaterial) {
  33724. this._currentMaterial = effectiveMaterial;
  33725. this._materialDefines = null;
  33726. }
  33727. return effectiveMaterial;
  33728. }
  33729. return rootMaterial;
  33730. };
  33731. // Methods
  33732. /**
  33733. * Sets a new updated BoundingInfo object to the submesh.
  33734. * Returns the SubMesh.
  33735. */
  33736. SubMesh.prototype.refreshBoundingInfo = function () {
  33737. this._lastColliderWorldVertices = null;
  33738. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33739. return this;
  33740. }
  33741. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33742. if (!data) {
  33743. this._boundingInfo = this._mesh.getBoundingInfo();
  33744. return this;
  33745. }
  33746. var indices = this._renderingMesh.getIndices();
  33747. var extend;
  33748. //is this the only submesh?
  33749. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33750. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33751. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33752. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33753. }
  33754. else {
  33755. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33756. }
  33757. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33758. return this;
  33759. };
  33760. SubMesh.prototype._checkCollision = function (collider) {
  33761. var boundingInfo = this.getBoundingInfo();
  33762. return boundingInfo._checkCollision(collider);
  33763. };
  33764. /**
  33765. * Updates the submesh BoundingInfo.
  33766. * Returns the Submesh.
  33767. */
  33768. SubMesh.prototype.updateBoundingInfo = function (world) {
  33769. var boundingInfo = this.getBoundingInfo();
  33770. if (!boundingInfo) {
  33771. this.refreshBoundingInfo();
  33772. boundingInfo = this.getBoundingInfo();
  33773. }
  33774. boundingInfo.update(world);
  33775. return this;
  33776. };
  33777. /**
  33778. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33779. * Boolean returned.
  33780. */
  33781. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33782. var boundingInfo = this.getBoundingInfo();
  33783. if (!boundingInfo) {
  33784. return false;
  33785. }
  33786. return boundingInfo.isInFrustum(frustumPlanes);
  33787. };
  33788. /**
  33789. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33790. * Boolean returned.
  33791. */
  33792. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33793. var boundingInfo = this.getBoundingInfo();
  33794. if (!boundingInfo) {
  33795. return false;
  33796. }
  33797. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33798. };
  33799. /**
  33800. * Renders the submesh.
  33801. * Returns it.
  33802. */
  33803. SubMesh.prototype.render = function (enableAlphaMode) {
  33804. this._renderingMesh.render(this, enableAlphaMode);
  33805. return this;
  33806. };
  33807. /**
  33808. * Returns a new Index Buffer.
  33809. * Type returned : WebGLBuffer.
  33810. */
  33811. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  33812. if (!this._linesIndexBuffer) {
  33813. var linesIndices = [];
  33814. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33815. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  33816. }
  33817. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  33818. this.linesIndexCount = linesIndices.length;
  33819. }
  33820. return this._linesIndexBuffer;
  33821. };
  33822. /**
  33823. * True is the passed Ray intersects the submesh bounding box.
  33824. * Boolean returned.
  33825. */
  33826. SubMesh.prototype.canIntersects = function (ray) {
  33827. var boundingInfo = this.getBoundingInfo();
  33828. if (!boundingInfo) {
  33829. return false;
  33830. }
  33831. return ray.intersectsBox(boundingInfo.boundingBox);
  33832. };
  33833. /**
  33834. * Returns an object IntersectionInfo.
  33835. */
  33836. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  33837. var intersectInfo = null;
  33838. var material = this.getMaterial();
  33839. if (!material) {
  33840. return null;
  33841. }
  33842. switch (material.fillMode) {
  33843. case BABYLON.Material.PointListDrawMode:
  33844. case BABYLON.Material.LineListDrawMode:
  33845. case BABYLON.Material.LineLoopDrawMode:
  33846. case BABYLON.Material.LineStripDrawMode:
  33847. case BABYLON.Material.TriangleFanDrawMode:
  33848. case BABYLON.Material.TriangleStripDrawMode:
  33849. return null;
  33850. }
  33851. // LineMesh first as it's also a Mesh...
  33852. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  33853. var lineMesh = this._mesh;
  33854. // Line test
  33855. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  33856. var p0 = positions[indices[index]];
  33857. var p1 = positions[indices[index + 1]];
  33858. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  33859. if (length < 0) {
  33860. continue;
  33861. }
  33862. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  33863. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  33864. if (fastCheck) {
  33865. break;
  33866. }
  33867. }
  33868. }
  33869. }
  33870. else {
  33871. // Triangles test
  33872. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  33873. var p0 = positions[indices[index]];
  33874. var p1 = positions[indices[index + 1]];
  33875. var p2 = positions[indices[index + 2]];
  33876. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  33877. if (currentIntersectInfo) {
  33878. if (currentIntersectInfo.distance < 0) {
  33879. continue;
  33880. }
  33881. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  33882. intersectInfo = currentIntersectInfo;
  33883. intersectInfo.faceId = index / 3;
  33884. if (fastCheck) {
  33885. break;
  33886. }
  33887. }
  33888. }
  33889. }
  33890. }
  33891. return intersectInfo;
  33892. };
  33893. SubMesh.prototype._rebuild = function () {
  33894. if (this._linesIndexBuffer) {
  33895. this._linesIndexBuffer = null;
  33896. }
  33897. };
  33898. // Clone
  33899. /**
  33900. * Creates a new Submesh from the passed Mesh.
  33901. */
  33902. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  33903. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  33904. if (!this.IsGlobal) {
  33905. var boundingInfo = this.getBoundingInfo();
  33906. if (!boundingInfo) {
  33907. return result;
  33908. }
  33909. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  33910. }
  33911. return result;
  33912. };
  33913. // Dispose
  33914. /**
  33915. * Disposes the Submesh.
  33916. * Returns nothing.
  33917. */
  33918. SubMesh.prototype.dispose = function () {
  33919. if (this._linesIndexBuffer) {
  33920. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  33921. this._linesIndexBuffer = null;
  33922. }
  33923. // Remove from mesh
  33924. var index = this._mesh.subMeshes.indexOf(this);
  33925. this._mesh.subMeshes.splice(index, 1);
  33926. };
  33927. // Statics
  33928. /**
  33929. * Creates a new Submesh from the passed parameters :
  33930. * - materialIndex (integer) : the index of the main mesh material.
  33931. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  33932. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  33933. * - mesh (Mesh) : the main mesh to create the submesh from.
  33934. * - renderingMesh (optional Mesh) : rendering mesh.
  33935. */
  33936. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  33937. var minVertexIndex = Number.MAX_VALUE;
  33938. var maxVertexIndex = -Number.MAX_VALUE;
  33939. renderingMesh = (renderingMesh || mesh);
  33940. var indices = renderingMesh.getIndices();
  33941. for (var index = startIndex; index < startIndex + indexCount; index++) {
  33942. var vertexIndex = indices[index];
  33943. if (vertexIndex < minVertexIndex)
  33944. minVertexIndex = vertexIndex;
  33945. if (vertexIndex > maxVertexIndex)
  33946. maxVertexIndex = vertexIndex;
  33947. }
  33948. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  33949. };
  33950. return SubMesh;
  33951. }(BaseSubMesh));
  33952. BABYLON.SubMesh = SubMesh;
  33953. })(BABYLON || (BABYLON = {}));
  33954. //# sourceMappingURL=babylon.subMesh.js.map
  33955. var __assign = (this && this.__assign) || Object.assign || function(t) {
  33956. for (var s, i = 1, n = arguments.length; i < n; i++) {
  33957. s = arguments[i];
  33958. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  33959. t[p] = s[p];
  33960. }
  33961. return t;
  33962. };
  33963. var BABYLON;
  33964. (function (BABYLON) {
  33965. /**
  33966. * Manages the defines for the Material
  33967. */
  33968. var MaterialDefines = /** @class */ (function () {
  33969. function MaterialDefines() {
  33970. this._isDirty = true;
  33971. /** @ignore */
  33972. this._areLightsDirty = true;
  33973. /** @ignore */
  33974. this._areAttributesDirty = true;
  33975. /** @ignore */
  33976. this._areTexturesDirty = true;
  33977. /** @ignore */
  33978. this._areFresnelDirty = true;
  33979. /** @ignore */
  33980. this._areMiscDirty = true;
  33981. /** @ignore */
  33982. this._areImageProcessingDirty = true;
  33983. /** @ignore */
  33984. this._normals = false;
  33985. /** @ignore */
  33986. this._uvs = false;
  33987. /** @ignore */
  33988. this._needNormals = false;
  33989. /** @ignore */
  33990. this._needUVs = false;
  33991. }
  33992. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  33993. /**
  33994. * Specifies if the material needs to be re-calculated
  33995. */
  33996. get: function () {
  33997. return this._isDirty;
  33998. },
  33999. enumerable: true,
  34000. configurable: true
  34001. });
  34002. /**
  34003. * Marks the material to indicate that it has been re-calculated
  34004. */
  34005. MaterialDefines.prototype.markAsProcessed = function () {
  34006. this._isDirty = false;
  34007. this._areAttributesDirty = false;
  34008. this._areTexturesDirty = false;
  34009. this._areFresnelDirty = false;
  34010. this._areLightsDirty = false;
  34011. this._areMiscDirty = false;
  34012. this._areImageProcessingDirty = false;
  34013. };
  34014. /**
  34015. * Marks the material to indicate that it needs to be re-calculated
  34016. */
  34017. MaterialDefines.prototype.markAsUnprocessed = function () {
  34018. this._isDirty = true;
  34019. };
  34020. /**
  34021. * Marks the material to indicate all of its defines need to be re-calculated
  34022. */
  34023. MaterialDefines.prototype.markAllAsDirty = function () {
  34024. this._areTexturesDirty = true;
  34025. this._areAttributesDirty = true;
  34026. this._areLightsDirty = true;
  34027. this._areFresnelDirty = true;
  34028. this._areMiscDirty = true;
  34029. this._areImageProcessingDirty = true;
  34030. this._isDirty = true;
  34031. };
  34032. /**
  34033. * Marks the material to indicate that image processing needs to be re-calculated
  34034. */
  34035. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34036. this._areImageProcessingDirty = true;
  34037. this._isDirty = true;
  34038. };
  34039. /**
  34040. * Marks the material to indicate the lights need to be re-calculated
  34041. */
  34042. MaterialDefines.prototype.markAsLightDirty = function () {
  34043. this._areLightsDirty = true;
  34044. this._isDirty = true;
  34045. };
  34046. /**
  34047. * Marks the attribute state as changed
  34048. */
  34049. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34050. this._areAttributesDirty = true;
  34051. this._isDirty = true;
  34052. };
  34053. /**
  34054. * Marks the texture state as changed
  34055. */
  34056. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34057. this._areTexturesDirty = true;
  34058. this._isDirty = true;
  34059. };
  34060. /**
  34061. * Marks the fresnel state as changed
  34062. */
  34063. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34064. this._areFresnelDirty = true;
  34065. this._isDirty = true;
  34066. };
  34067. /**
  34068. * Marks the misc state as changed
  34069. */
  34070. MaterialDefines.prototype.markAsMiscDirty = function () {
  34071. this._areMiscDirty = true;
  34072. this._isDirty = true;
  34073. };
  34074. /**
  34075. * Rebuilds the material defines
  34076. */
  34077. MaterialDefines.prototype.rebuild = function () {
  34078. if (this._keys) {
  34079. delete this._keys;
  34080. }
  34081. this._keys = [];
  34082. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34083. var key = _a[_i];
  34084. if (key[0] === "_") {
  34085. continue;
  34086. }
  34087. this._keys.push(key);
  34088. }
  34089. };
  34090. /**
  34091. * Specifies if two material defines are equal
  34092. * @param other - A material define instance to compare to
  34093. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34094. */
  34095. MaterialDefines.prototype.isEqual = function (other) {
  34096. if (this._keys.length !== other._keys.length) {
  34097. return false;
  34098. }
  34099. for (var index = 0; index < this._keys.length; index++) {
  34100. var prop = this._keys[index];
  34101. if (this[prop] !== other[prop]) {
  34102. return false;
  34103. }
  34104. }
  34105. return true;
  34106. };
  34107. /**
  34108. * Clones this instance's defines to another instance
  34109. * @param other - material defines to clone values to
  34110. */
  34111. MaterialDefines.prototype.cloneTo = function (other) {
  34112. if (this._keys.length !== other._keys.length) {
  34113. other._keys = this._keys.slice(0);
  34114. }
  34115. for (var index = 0; index < this._keys.length; index++) {
  34116. var prop = this._keys[index];
  34117. other[prop] = this[prop];
  34118. }
  34119. };
  34120. /**
  34121. * Resets the material define values
  34122. */
  34123. MaterialDefines.prototype.reset = function () {
  34124. for (var index = 0; index < this._keys.length; index++) {
  34125. var prop = this._keys[index];
  34126. var type = typeof this[prop];
  34127. switch (type) {
  34128. case "number":
  34129. this[prop] = 0;
  34130. break;
  34131. case "string":
  34132. this[prop] = "";
  34133. break;
  34134. default:
  34135. this[prop] = false;
  34136. break;
  34137. }
  34138. }
  34139. };
  34140. /**
  34141. * Converts the material define values to a string
  34142. * @returns - String of material define information
  34143. */
  34144. MaterialDefines.prototype.toString = function () {
  34145. var result = "";
  34146. for (var index = 0; index < this._keys.length; index++) {
  34147. var prop = this._keys[index];
  34148. var value = this[prop];
  34149. var type = typeof value;
  34150. switch (type) {
  34151. case "number":
  34152. case "string":
  34153. result += "#define " + prop + " " + value + "\n";
  34154. break;
  34155. default:
  34156. if (value) {
  34157. result += "#define " + prop + "\n";
  34158. }
  34159. break;
  34160. }
  34161. }
  34162. return result;
  34163. };
  34164. return MaterialDefines;
  34165. }());
  34166. BABYLON.MaterialDefines = MaterialDefines;
  34167. /**
  34168. * Base class for the main features of a material in Babylon.js
  34169. */
  34170. var Material = /** @class */ (function () {
  34171. /**
  34172. * Creates a material instance
  34173. * @param name defines the name of the material
  34174. * @param scene defines the scene to reference
  34175. * @param doNotAdd specifies if the material should be added to the scene
  34176. */
  34177. function Material(name, scene, doNotAdd) {
  34178. /**
  34179. * Specifies if the ready state should be checked on each call
  34180. */
  34181. this.checkReadyOnEveryCall = false;
  34182. /**
  34183. * Specifies if the ready state should be checked once
  34184. */
  34185. this.checkReadyOnlyOnce = false;
  34186. /**
  34187. * The state of the material
  34188. */
  34189. this.state = "";
  34190. /**
  34191. * The alpha value of the material
  34192. */
  34193. this._alpha = 1.0;
  34194. /**
  34195. * Specifies if back face culling is enabled
  34196. */
  34197. this._backFaceCulling = true;
  34198. /**
  34199. * Specifies if the material should be serialized
  34200. */
  34201. this.doNotSerialize = false;
  34202. /**
  34203. * Specifies if the effect should be stored on sub meshes
  34204. */
  34205. this.storeEffectOnSubMeshes = false;
  34206. /**
  34207. * An event triggered when the material is disposed
  34208. */
  34209. this.onDisposeObservable = new BABYLON.Observable();
  34210. /**
  34211. * An event triggered when the material is bound
  34212. */
  34213. this.onBindObservable = new BABYLON.Observable();
  34214. /**
  34215. * An event triggered when the material is unbound
  34216. */
  34217. this.onUnBindObservable = new BABYLON.Observable();
  34218. /**
  34219. * Stores the value of the alpha mode
  34220. */
  34221. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34222. /**
  34223. * Stores the state of the need depth pre-pass value
  34224. */
  34225. this._needDepthPrePass = false;
  34226. /**
  34227. * Specifies if depth writing should be disabled
  34228. */
  34229. this.disableDepthWrite = false;
  34230. /**
  34231. * Specifies if depth writing should be forced
  34232. */
  34233. this.forceDepthWrite = false;
  34234. /**
  34235. * Specifies if there should be a separate pass for culling
  34236. */
  34237. this.separateCullingPass = false;
  34238. /**
  34239. * Stores the state specifing if fog should be enabled
  34240. */
  34241. this._fogEnabled = true;
  34242. /**
  34243. * Stores the size of points
  34244. */
  34245. this.pointSize = 1.0;
  34246. /**
  34247. * Stores the z offset value
  34248. */
  34249. this.zOffset = 0;
  34250. /**
  34251. * Specifies if the material was previously ready
  34252. */
  34253. this._wasPreviouslyReady = false;
  34254. /**
  34255. * Stores the fill mode state
  34256. */
  34257. this._fillMode = Material.TriangleFillMode;
  34258. this.name = name;
  34259. this.id = name || BABYLON.Tools.RandomId();
  34260. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34261. if (this._scene.useRightHandedSystem) {
  34262. this.sideOrientation = Material.ClockWiseSideOrientation;
  34263. }
  34264. else {
  34265. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34266. }
  34267. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34268. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34269. if (!doNotAdd) {
  34270. this._scene.materials.push(this);
  34271. }
  34272. }
  34273. Object.defineProperty(Material, "TriangleFillMode", {
  34274. /**
  34275. * Returns the triangle fill mode
  34276. */
  34277. get: function () {
  34278. return Material._TriangleFillMode;
  34279. },
  34280. enumerable: true,
  34281. configurable: true
  34282. });
  34283. Object.defineProperty(Material, "WireFrameFillMode", {
  34284. /**
  34285. * Returns the wireframe mode
  34286. */
  34287. get: function () {
  34288. return Material._WireFrameFillMode;
  34289. },
  34290. enumerable: true,
  34291. configurable: true
  34292. });
  34293. Object.defineProperty(Material, "PointFillMode", {
  34294. /**
  34295. * Returns the point fill mode
  34296. */
  34297. get: function () {
  34298. return Material._PointFillMode;
  34299. },
  34300. enumerable: true,
  34301. configurable: true
  34302. });
  34303. Object.defineProperty(Material, "PointListDrawMode", {
  34304. /**
  34305. * Returns the point list draw mode
  34306. */
  34307. get: function () {
  34308. return Material._PointListDrawMode;
  34309. },
  34310. enumerable: true,
  34311. configurable: true
  34312. });
  34313. Object.defineProperty(Material, "LineListDrawMode", {
  34314. /**
  34315. * Returns the line list draw mode
  34316. */
  34317. get: function () {
  34318. return Material._LineListDrawMode;
  34319. },
  34320. enumerable: true,
  34321. configurable: true
  34322. });
  34323. Object.defineProperty(Material, "LineLoopDrawMode", {
  34324. /**
  34325. * Returns the line loop draw mode
  34326. */
  34327. get: function () {
  34328. return Material._LineLoopDrawMode;
  34329. },
  34330. enumerable: true,
  34331. configurable: true
  34332. });
  34333. Object.defineProperty(Material, "LineStripDrawMode", {
  34334. /**
  34335. * Returns the line strip draw mode
  34336. */
  34337. get: function () {
  34338. return Material._LineStripDrawMode;
  34339. },
  34340. enumerable: true,
  34341. configurable: true
  34342. });
  34343. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34344. /**
  34345. * Returns the triangle strip draw mode
  34346. */
  34347. get: function () {
  34348. return Material._TriangleStripDrawMode;
  34349. },
  34350. enumerable: true,
  34351. configurable: true
  34352. });
  34353. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34354. /**
  34355. * Returns the triangle fan draw mode
  34356. */
  34357. get: function () {
  34358. return Material._TriangleFanDrawMode;
  34359. },
  34360. enumerable: true,
  34361. configurable: true
  34362. });
  34363. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34364. /**
  34365. * Returns the clock-wise side orientation
  34366. */
  34367. get: function () {
  34368. return Material._ClockWiseSideOrientation;
  34369. },
  34370. enumerable: true,
  34371. configurable: true
  34372. });
  34373. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34374. /**
  34375. * Returns the counter clock-wise side orientation
  34376. */
  34377. get: function () {
  34378. return Material._CounterClockWiseSideOrientation;
  34379. },
  34380. enumerable: true,
  34381. configurable: true
  34382. });
  34383. Object.defineProperty(Material, "TextureDirtyFlag", {
  34384. /**
  34385. * Returns the dirty texture flag value
  34386. */
  34387. get: function () {
  34388. return Material._TextureDirtyFlag;
  34389. },
  34390. enumerable: true,
  34391. configurable: true
  34392. });
  34393. Object.defineProperty(Material, "LightDirtyFlag", {
  34394. /**
  34395. * Returns the dirty light flag value
  34396. */
  34397. get: function () {
  34398. return Material._LightDirtyFlag;
  34399. },
  34400. enumerable: true,
  34401. configurable: true
  34402. });
  34403. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34404. /**
  34405. * Returns the dirty fresnel flag value
  34406. */
  34407. get: function () {
  34408. return Material._FresnelDirtyFlag;
  34409. },
  34410. enumerable: true,
  34411. configurable: true
  34412. });
  34413. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34414. /**
  34415. * Returns the dirty attributes flag value
  34416. */
  34417. get: function () {
  34418. return Material._AttributesDirtyFlag;
  34419. },
  34420. enumerable: true,
  34421. configurable: true
  34422. });
  34423. Object.defineProperty(Material, "MiscDirtyFlag", {
  34424. /**
  34425. * Returns the dirty misc flag value
  34426. */
  34427. get: function () {
  34428. return Material._MiscDirtyFlag;
  34429. },
  34430. enumerable: true,
  34431. configurable: true
  34432. });
  34433. Object.defineProperty(Material.prototype, "alpha", {
  34434. /**
  34435. * Gets the alpha value of the material
  34436. */
  34437. get: function () {
  34438. return this._alpha;
  34439. },
  34440. /**
  34441. * Sets the alpha value of the material
  34442. */
  34443. set: function (value) {
  34444. if (this._alpha === value) {
  34445. return;
  34446. }
  34447. this._alpha = value;
  34448. this.markAsDirty(Material.MiscDirtyFlag);
  34449. },
  34450. enumerable: true,
  34451. configurable: true
  34452. });
  34453. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34454. /**
  34455. * Gets the back-face culling state
  34456. */
  34457. get: function () {
  34458. return this._backFaceCulling;
  34459. },
  34460. /**
  34461. * Sets the back-face culling state
  34462. */
  34463. set: function (value) {
  34464. if (this._backFaceCulling === value) {
  34465. return;
  34466. }
  34467. this._backFaceCulling = value;
  34468. this.markAsDirty(Material.TextureDirtyFlag);
  34469. },
  34470. enumerable: true,
  34471. configurable: true
  34472. });
  34473. Object.defineProperty(Material.prototype, "onDispose", {
  34474. /**
  34475. * Called during a dispose event
  34476. */
  34477. set: function (callback) {
  34478. if (this._onDisposeObserver) {
  34479. this.onDisposeObservable.remove(this._onDisposeObserver);
  34480. }
  34481. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34482. },
  34483. enumerable: true,
  34484. configurable: true
  34485. });
  34486. Object.defineProperty(Material.prototype, "onBind", {
  34487. /**
  34488. * Called during a bind event
  34489. */
  34490. set: function (callback) {
  34491. if (this._onBindObserver) {
  34492. this.onBindObservable.remove(this._onBindObserver);
  34493. }
  34494. this._onBindObserver = this.onBindObservable.add(callback);
  34495. },
  34496. enumerable: true,
  34497. configurable: true
  34498. });
  34499. Object.defineProperty(Material.prototype, "alphaMode", {
  34500. /**
  34501. * Gets the value of the alpha mode
  34502. */
  34503. get: function () {
  34504. return this._alphaMode;
  34505. },
  34506. /**
  34507. * Sets the value of the alpha mode.
  34508. *
  34509. * | Value | Type | Description |
  34510. * | --- | --- | --- |
  34511. * | 0 | ALPHA_DISABLE | |
  34512. * | 1 | ALPHA_ADD | |
  34513. * | 2 | ALPHA_COMBINE | |
  34514. * | 3 | ALPHA_SUBTRACT | |
  34515. * | 4 | ALPHA_MULTIPLY | |
  34516. * | 5 | ALPHA_MAXIMIZED | |
  34517. * | 6 | ALPHA_ONEONE | |
  34518. * | 7 | ALPHA_PREMULTIPLIED | |
  34519. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34520. * | 9 | ALPHA_INTERPOLATE | |
  34521. * | 10 | ALPHA_SCREENMODE | |
  34522. *
  34523. */
  34524. set: function (value) {
  34525. if (this._alphaMode === value) {
  34526. return;
  34527. }
  34528. this._alphaMode = value;
  34529. this.markAsDirty(Material.TextureDirtyFlag);
  34530. },
  34531. enumerable: true,
  34532. configurable: true
  34533. });
  34534. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34535. /**
  34536. * Gets the depth pre-pass value
  34537. */
  34538. get: function () {
  34539. return this._needDepthPrePass;
  34540. },
  34541. /**
  34542. * Sets the need depth pre-pass value
  34543. */
  34544. set: function (value) {
  34545. if (this._needDepthPrePass === value) {
  34546. return;
  34547. }
  34548. this._needDepthPrePass = value;
  34549. if (this._needDepthPrePass) {
  34550. this.checkReadyOnEveryCall = true;
  34551. }
  34552. },
  34553. enumerable: true,
  34554. configurable: true
  34555. });
  34556. Object.defineProperty(Material.prototype, "fogEnabled", {
  34557. /**
  34558. * Gets the value of the fog enabled state
  34559. */
  34560. get: function () {
  34561. return this._fogEnabled;
  34562. },
  34563. /**
  34564. * Sets the state for enabling fog
  34565. */
  34566. set: function (value) {
  34567. if (this._fogEnabled === value) {
  34568. return;
  34569. }
  34570. this._fogEnabled = value;
  34571. this.markAsDirty(Material.MiscDirtyFlag);
  34572. },
  34573. enumerable: true,
  34574. configurable: true
  34575. });
  34576. Object.defineProperty(Material.prototype, "wireframe", {
  34577. /**
  34578. * Gets a value specifying if wireframe mode is enabled
  34579. */
  34580. get: function () {
  34581. switch (this._fillMode) {
  34582. case Material.WireFrameFillMode:
  34583. case Material.LineListDrawMode:
  34584. case Material.LineLoopDrawMode:
  34585. case Material.LineStripDrawMode:
  34586. return true;
  34587. }
  34588. return this._scene.forceWireframe;
  34589. },
  34590. /**
  34591. * Sets the state of wireframe mode
  34592. */
  34593. set: function (value) {
  34594. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34595. },
  34596. enumerable: true,
  34597. configurable: true
  34598. });
  34599. Object.defineProperty(Material.prototype, "pointsCloud", {
  34600. /**
  34601. * Gets the value specifying if point clouds are enabled
  34602. */
  34603. get: function () {
  34604. switch (this._fillMode) {
  34605. case Material.PointFillMode:
  34606. case Material.PointListDrawMode:
  34607. return true;
  34608. }
  34609. return this._scene.forcePointsCloud;
  34610. },
  34611. /**
  34612. * Sets the state of point cloud mode
  34613. */
  34614. set: function (value) {
  34615. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34616. },
  34617. enumerable: true,
  34618. configurable: true
  34619. });
  34620. Object.defineProperty(Material.prototype, "fillMode", {
  34621. /**
  34622. * Gets the material fill mode
  34623. */
  34624. get: function () {
  34625. return this._fillMode;
  34626. },
  34627. /**
  34628. * Sets the material fill mode
  34629. */
  34630. set: function (value) {
  34631. if (this._fillMode === value) {
  34632. return;
  34633. }
  34634. this._fillMode = value;
  34635. this.markAsDirty(Material.MiscDirtyFlag);
  34636. },
  34637. enumerable: true,
  34638. configurable: true
  34639. });
  34640. /**
  34641. * Returns a string representation of the current material
  34642. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34643. * @returns a string with material information
  34644. */
  34645. Material.prototype.toString = function (fullDetails) {
  34646. var ret = "Name: " + this.name;
  34647. if (fullDetails) {
  34648. }
  34649. return ret;
  34650. };
  34651. /**
  34652. * Gets the class name of the material
  34653. * @returns a string with the class name of the material
  34654. */
  34655. Material.prototype.getClassName = function () {
  34656. return "Material";
  34657. };
  34658. Object.defineProperty(Material.prototype, "isFrozen", {
  34659. /**
  34660. * Specifies if updates for the material been locked
  34661. */
  34662. get: function () {
  34663. return this.checkReadyOnlyOnce;
  34664. },
  34665. enumerable: true,
  34666. configurable: true
  34667. });
  34668. /**
  34669. * Locks updates for the material
  34670. */
  34671. Material.prototype.freeze = function () {
  34672. this.checkReadyOnlyOnce = true;
  34673. };
  34674. /**
  34675. * Unlocks updates for the material
  34676. */
  34677. Material.prototype.unfreeze = function () {
  34678. this.checkReadyOnlyOnce = false;
  34679. };
  34680. /**
  34681. * Specifies if the material is ready to be used
  34682. * @param mesh defines the mesh to check
  34683. * @param useInstances specifies if instances should be used
  34684. * @returns a boolean indicating if the material is ready to be used
  34685. */
  34686. Material.prototype.isReady = function (mesh, useInstances) {
  34687. return true;
  34688. };
  34689. /**
  34690. * Specifies that the submesh is ready to be used
  34691. * @param mesh defines the mesh to check
  34692. * @param subMesh defines which submesh to check
  34693. * @param useInstances specifies that instances should be used
  34694. * @returns a boolean indicating that the submesh is ready or not
  34695. */
  34696. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34697. return false;
  34698. };
  34699. /**
  34700. * Returns the material effect
  34701. * @returns the effect associated with the material
  34702. */
  34703. Material.prototype.getEffect = function () {
  34704. return this._effect;
  34705. };
  34706. /**
  34707. * Returns the current scene
  34708. * @returns a Scene
  34709. */
  34710. Material.prototype.getScene = function () {
  34711. return this._scene;
  34712. };
  34713. /**
  34714. * Specifies if the material will require alpha blending
  34715. * @returns a boolean specifying if alpha blending is needed
  34716. */
  34717. Material.prototype.needAlphaBlending = function () {
  34718. return (this.alpha < 1.0);
  34719. };
  34720. /**
  34721. * Specifies if the mesh will require alpha blending
  34722. * @param mesh defines the mesh to check
  34723. * @returns a boolean specifying if alpha blending is needed for the mesh
  34724. */
  34725. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34726. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34727. };
  34728. /**
  34729. * Specifies if this material should be rendered in alpha test mode
  34730. * @returns a boolean specifying if an alpha test is needed.
  34731. */
  34732. Material.prototype.needAlphaTesting = function () {
  34733. return false;
  34734. };
  34735. /**
  34736. * Gets the texture used for the alpha test
  34737. * @returns the texture to use for alpha testing
  34738. */
  34739. Material.prototype.getAlphaTestTexture = function () {
  34740. return null;
  34741. };
  34742. /**
  34743. * Marks the material to indicate that it needs to be re-calculated
  34744. */
  34745. Material.prototype.markDirty = function () {
  34746. this._wasPreviouslyReady = false;
  34747. };
  34748. /** @ignore */
  34749. Material.prototype._preBind = function (effect, overrideOrientation) {
  34750. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34751. var engine = this._scene.getEngine();
  34752. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34753. var reverse = orientation === Material.ClockWiseSideOrientation;
  34754. engine.enableEffect(effect ? effect : this._effect);
  34755. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34756. return reverse;
  34757. };
  34758. /**
  34759. * Binds the material to the mesh
  34760. * @param world defines the world transformation matrix
  34761. * @param mesh defines the mesh to bind the material to
  34762. */
  34763. Material.prototype.bind = function (world, mesh) {
  34764. };
  34765. /**
  34766. * Binds the submesh to the material
  34767. * @param world defines the world transformation matrix
  34768. * @param mesh defines the mesh containing the submesh
  34769. * @param subMesh defines the submesh to bind the material to
  34770. */
  34771. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34772. };
  34773. /**
  34774. * Binds the world matrix to the material
  34775. * @param world defines the world transformation matrix
  34776. */
  34777. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34778. };
  34779. /**
  34780. * Binds the scene's uniform buffer to the effect.
  34781. * @param effect defines the effect to bind to the scene uniform buffer
  34782. * @param sceneUbo defines the uniform buffer storing scene data
  34783. */
  34784. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34785. sceneUbo.bindToEffect(effect, "Scene");
  34786. };
  34787. /**
  34788. * Binds the view matrix to the effect
  34789. * @param effect defines the effect to bind the view matrix to
  34790. */
  34791. Material.prototype.bindView = function (effect) {
  34792. if (!this._useUBO) {
  34793. effect.setMatrix("view", this.getScene().getViewMatrix());
  34794. }
  34795. else {
  34796. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34797. }
  34798. };
  34799. /**
  34800. * Binds the view projection matrix to the effect
  34801. * @param effect defines the effect to bind the view projection matrix to
  34802. */
  34803. Material.prototype.bindViewProjection = function (effect) {
  34804. if (!this._useUBO) {
  34805. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34806. }
  34807. else {
  34808. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34809. }
  34810. };
  34811. /**
  34812. * Specifies if material alpha testing should be turned on for the mesh
  34813. * @param mesh defines the mesh to check
  34814. */
  34815. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  34816. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  34817. };
  34818. /**
  34819. * Processes to execute after binding the material to a mesh
  34820. * @param mesh defines the rendered mesh
  34821. */
  34822. Material.prototype._afterBind = function (mesh) {
  34823. this._scene._cachedMaterial = this;
  34824. if (mesh) {
  34825. this._scene._cachedVisibility = mesh.visibility;
  34826. }
  34827. else {
  34828. this._scene._cachedVisibility = 1;
  34829. }
  34830. if (mesh) {
  34831. this.onBindObservable.notifyObservers(mesh);
  34832. }
  34833. if (this.disableDepthWrite) {
  34834. var engine = this._scene.getEngine();
  34835. this._cachedDepthWriteState = engine.getDepthWrite();
  34836. engine.setDepthWrite(false);
  34837. }
  34838. };
  34839. /**
  34840. * Unbinds the material from the mesh
  34841. */
  34842. Material.prototype.unbind = function () {
  34843. this.onUnBindObservable.notifyObservers(this);
  34844. if (this.disableDepthWrite) {
  34845. var engine = this._scene.getEngine();
  34846. engine.setDepthWrite(this._cachedDepthWriteState);
  34847. }
  34848. };
  34849. /**
  34850. * Gets the active textures from the material
  34851. * @returns an array of textures
  34852. */
  34853. Material.prototype.getActiveTextures = function () {
  34854. return [];
  34855. };
  34856. /**
  34857. * Specifies if the material uses a texture
  34858. * @param texture defines the texture to check against the material
  34859. * @returns a boolean specifying if the material uses the texture
  34860. */
  34861. Material.prototype.hasTexture = function (texture) {
  34862. return false;
  34863. };
  34864. /**
  34865. * Makes a duplicate of the material, and gives it a new name
  34866. * @param name defines the new name for the duplicated material
  34867. * @returns the cloned material
  34868. */
  34869. Material.prototype.clone = function (name) {
  34870. return null;
  34871. };
  34872. /**
  34873. * Gets the meshes bound to the material
  34874. * @returns an array of meshes bound to the material
  34875. */
  34876. Material.prototype.getBindedMeshes = function () {
  34877. var result = new Array();
  34878. for (var index = 0; index < this._scene.meshes.length; index++) {
  34879. var mesh = this._scene.meshes[index];
  34880. if (mesh.material === this) {
  34881. result.push(mesh);
  34882. }
  34883. }
  34884. return result;
  34885. };
  34886. /**
  34887. * Force shader compilation
  34888. * @param mesh defines the mesh associated with this material
  34889. * @param onCompiled defines a function to execute once the material is compiled
  34890. * @param options defines the options to configure the compilation
  34891. */
  34892. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  34893. var _this = this;
  34894. var localOptions = __assign({ clipPlane: false }, options);
  34895. var subMesh = new BABYLON.BaseSubMesh();
  34896. var scene = this.getScene();
  34897. var checkReady = function () {
  34898. if (!_this._scene || !_this._scene.getEngine()) {
  34899. return;
  34900. }
  34901. if (subMesh._materialDefines) {
  34902. subMesh._materialDefines._renderId = -1;
  34903. }
  34904. var clipPlaneState = scene.clipPlane;
  34905. if (localOptions.clipPlane) {
  34906. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  34907. }
  34908. if (_this.storeEffectOnSubMeshes) {
  34909. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  34910. if (onCompiled) {
  34911. onCompiled(_this);
  34912. }
  34913. }
  34914. else {
  34915. setTimeout(checkReady, 16);
  34916. }
  34917. }
  34918. else {
  34919. if (_this.isReady(mesh)) {
  34920. if (onCompiled) {
  34921. onCompiled(_this);
  34922. }
  34923. }
  34924. else {
  34925. setTimeout(checkReady, 16);
  34926. }
  34927. }
  34928. if (localOptions.clipPlane) {
  34929. scene.clipPlane = clipPlaneState;
  34930. }
  34931. };
  34932. checkReady();
  34933. };
  34934. /**
  34935. * Force shader compilation
  34936. * @param mesh defines the mesh that will use this material
  34937. * @param options defines additional options for compiling the shaders
  34938. * @returns a promise that resolves when the compilation completes
  34939. */
  34940. Material.prototype.forceCompilationAsync = function (mesh, options) {
  34941. var _this = this;
  34942. return new Promise(function (resolve) {
  34943. _this.forceCompilation(mesh, function () {
  34944. resolve();
  34945. }, options);
  34946. });
  34947. };
  34948. /**
  34949. * Marks a define in the material to indicate that it needs to be re-computed
  34950. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  34951. */
  34952. Material.prototype.markAsDirty = function (flag) {
  34953. if (flag & Material.TextureDirtyFlag) {
  34954. this._markAllSubMeshesAsTexturesDirty();
  34955. }
  34956. if (flag & Material.LightDirtyFlag) {
  34957. this._markAllSubMeshesAsLightsDirty();
  34958. }
  34959. if (flag & Material.FresnelDirtyFlag) {
  34960. this._markAllSubMeshesAsFresnelDirty();
  34961. }
  34962. if (flag & Material.AttributesDirtyFlag) {
  34963. this._markAllSubMeshesAsAttributesDirty();
  34964. }
  34965. if (flag & Material.MiscDirtyFlag) {
  34966. this._markAllSubMeshesAsMiscDirty();
  34967. }
  34968. this.getScene().resetCachedMaterial();
  34969. };
  34970. /**
  34971. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  34972. * @param func defines a function which checks material defines against the submeshes
  34973. */
  34974. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  34975. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  34976. var mesh = _a[_i];
  34977. if (!mesh.subMeshes) {
  34978. continue;
  34979. }
  34980. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  34981. var subMesh = _c[_b];
  34982. if (subMesh.getMaterial() !== this) {
  34983. continue;
  34984. }
  34985. if (!subMesh._materialDefines) {
  34986. continue;
  34987. }
  34988. func(subMesh._materialDefines);
  34989. }
  34990. }
  34991. };
  34992. /**
  34993. * Indicates that image processing needs to be re-calculated for all submeshes
  34994. */
  34995. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  34996. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  34997. };
  34998. /**
  34999. * Indicates that textures need to be re-calculated for all submeshes
  35000. */
  35001. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35002. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35003. };
  35004. /**
  35005. * Indicates that fresnel needs to be re-calculated for all submeshes
  35006. */
  35007. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35008. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35009. };
  35010. /**
  35011. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35012. */
  35013. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35014. this._markAllSubMeshesAsDirty(function (defines) {
  35015. defines.markAsFresnelDirty();
  35016. defines.markAsMiscDirty();
  35017. });
  35018. };
  35019. /**
  35020. * Indicates that lights need to be re-calculated for all submeshes
  35021. */
  35022. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35023. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35024. };
  35025. /**
  35026. * Indicates that attributes need to be re-calculated for all submeshes
  35027. */
  35028. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35029. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35030. };
  35031. /**
  35032. * Indicates that misc needs to be re-calculated for all submeshes
  35033. */
  35034. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35035. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35036. };
  35037. /**
  35038. * Indicates that textures and misc need to be re-calculated for all submeshes
  35039. */
  35040. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35041. this._markAllSubMeshesAsDirty(function (defines) {
  35042. defines.markAsTexturesDirty();
  35043. defines.markAsMiscDirty();
  35044. });
  35045. };
  35046. /**
  35047. * Disposes the material
  35048. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35049. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35050. */
  35051. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35052. // Animations
  35053. this.getScene().stopAnimation(this);
  35054. this.getScene().freeProcessedMaterials();
  35055. // Remove from scene
  35056. var index = this._scene.materials.indexOf(this);
  35057. if (index >= 0) {
  35058. this._scene.materials.splice(index, 1);
  35059. }
  35060. // Remove from meshes
  35061. for (index = 0; index < this._scene.meshes.length; index++) {
  35062. var mesh = this._scene.meshes[index];
  35063. if (mesh.material === this) {
  35064. mesh.material = null;
  35065. if (mesh.geometry) {
  35066. var geometry = (mesh.geometry);
  35067. if (this.storeEffectOnSubMeshes) {
  35068. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35069. var subMesh = _a[_i];
  35070. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35071. if (forceDisposeEffect && subMesh._materialEffect) {
  35072. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35073. }
  35074. }
  35075. }
  35076. else {
  35077. geometry._releaseVertexArrayObject(this._effect);
  35078. }
  35079. }
  35080. }
  35081. }
  35082. this._uniformBuffer.dispose();
  35083. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35084. if (forceDisposeEffect && this._effect) {
  35085. if (!this.storeEffectOnSubMeshes) {
  35086. this._scene.getEngine()._releaseEffect(this._effect);
  35087. }
  35088. this._effect = null;
  35089. }
  35090. // Callback
  35091. this.onDisposeObservable.notifyObservers(this);
  35092. this.onDisposeObservable.clear();
  35093. this.onBindObservable.clear();
  35094. this.onUnBindObservable.clear();
  35095. };
  35096. /**
  35097. * Serializes this material
  35098. * @returns the serialized material object
  35099. */
  35100. Material.prototype.serialize = function () {
  35101. return BABYLON.SerializationHelper.Serialize(this);
  35102. };
  35103. /**
  35104. * Creates a MultiMaterial from parsed MultiMaterial data.
  35105. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35106. * @param scene defines the hosting scene
  35107. * @returns a new MultiMaterial
  35108. */
  35109. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35110. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35111. multiMaterial.id = parsedMultiMaterial.id;
  35112. if (BABYLON.Tags) {
  35113. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35114. }
  35115. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35116. var subMatId = parsedMultiMaterial.materials[matIndex];
  35117. if (subMatId) {
  35118. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35119. }
  35120. else {
  35121. multiMaterial.subMaterials.push(null);
  35122. }
  35123. }
  35124. return multiMaterial;
  35125. };
  35126. /**
  35127. * Creates a material from parsed material data
  35128. * @param parsedMaterial defines parsed material data
  35129. * @param scene defines the hosting scene
  35130. * @param rootUrl defines the root URL to use to load textures
  35131. * @returns a new material
  35132. */
  35133. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35134. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35135. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35136. }
  35137. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35138. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35139. if (!BABYLON.LegacyPBRMaterial) {
  35140. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35141. return;
  35142. }
  35143. }
  35144. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35145. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35146. ;
  35147. };
  35148. // Triangle views
  35149. Material._TriangleFillMode = 0;
  35150. Material._WireFrameFillMode = 1;
  35151. Material._PointFillMode = 2;
  35152. // Draw modes
  35153. Material._PointListDrawMode = 3;
  35154. Material._LineListDrawMode = 4;
  35155. Material._LineLoopDrawMode = 5;
  35156. Material._LineStripDrawMode = 6;
  35157. Material._TriangleStripDrawMode = 7;
  35158. Material._TriangleFanDrawMode = 8;
  35159. /**
  35160. * Stores the clock-wise side orientation
  35161. */
  35162. Material._ClockWiseSideOrientation = 0;
  35163. /**
  35164. * Stores the counter clock-wise side orientation
  35165. */
  35166. Material._CounterClockWiseSideOrientation = 1;
  35167. /**
  35168. * The dirty texture flag value
  35169. */
  35170. Material._TextureDirtyFlag = 1;
  35171. /**
  35172. * The dirty light flag value
  35173. */
  35174. Material._LightDirtyFlag = 2;
  35175. /**
  35176. * The dirty fresnel flag value
  35177. */
  35178. Material._FresnelDirtyFlag = 4;
  35179. /**
  35180. * The dirty attribute flag value
  35181. */
  35182. Material._AttributesDirtyFlag = 8;
  35183. /**
  35184. * The dirty misc flag value
  35185. */
  35186. Material._MiscDirtyFlag = 16;
  35187. __decorate([
  35188. BABYLON.serialize()
  35189. ], Material.prototype, "id", void 0);
  35190. __decorate([
  35191. BABYLON.serialize()
  35192. ], Material.prototype, "name", void 0);
  35193. __decorate([
  35194. BABYLON.serialize()
  35195. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35196. __decorate([
  35197. BABYLON.serialize()
  35198. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35199. __decorate([
  35200. BABYLON.serialize()
  35201. ], Material.prototype, "state", void 0);
  35202. __decorate([
  35203. BABYLON.serialize("alpha")
  35204. ], Material.prototype, "_alpha", void 0);
  35205. __decorate([
  35206. BABYLON.serialize("backFaceCulling")
  35207. ], Material.prototype, "_backFaceCulling", void 0);
  35208. __decorate([
  35209. BABYLON.serialize()
  35210. ], Material.prototype, "sideOrientation", void 0);
  35211. __decorate([
  35212. BABYLON.serialize("alphaMode")
  35213. ], Material.prototype, "_alphaMode", void 0);
  35214. __decorate([
  35215. BABYLON.serialize()
  35216. ], Material.prototype, "_needDepthPrePass", void 0);
  35217. __decorate([
  35218. BABYLON.serialize()
  35219. ], Material.prototype, "disableDepthWrite", void 0);
  35220. __decorate([
  35221. BABYLON.serialize()
  35222. ], Material.prototype, "forceDepthWrite", void 0);
  35223. __decorate([
  35224. BABYLON.serialize()
  35225. ], Material.prototype, "separateCullingPass", void 0);
  35226. __decorate([
  35227. BABYLON.serialize("fogEnabled")
  35228. ], Material.prototype, "_fogEnabled", void 0);
  35229. __decorate([
  35230. BABYLON.serialize()
  35231. ], Material.prototype, "pointSize", void 0);
  35232. __decorate([
  35233. BABYLON.serialize()
  35234. ], Material.prototype, "zOffset", void 0);
  35235. __decorate([
  35236. BABYLON.serialize()
  35237. ], Material.prototype, "wireframe", null);
  35238. __decorate([
  35239. BABYLON.serialize()
  35240. ], Material.prototype, "pointsCloud", null);
  35241. __decorate([
  35242. BABYLON.serialize()
  35243. ], Material.prototype, "fillMode", null);
  35244. return Material;
  35245. }());
  35246. BABYLON.Material = Material;
  35247. })(BABYLON || (BABYLON = {}));
  35248. //# sourceMappingURL=babylon.material.js.map
  35249. var BABYLON;
  35250. (function (BABYLON) {
  35251. var UniformBuffer = /** @class */ (function () {
  35252. /**
  35253. * Uniform buffer objects.
  35254. *
  35255. * Handles blocks of uniform on the GPU.
  35256. *
  35257. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35258. *
  35259. * For more information, please refer to :
  35260. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35261. */
  35262. function UniformBuffer(engine, data, dynamic) {
  35263. this._engine = engine;
  35264. this._noUBO = !engine.supportsUniformBuffers;
  35265. this._dynamic = dynamic;
  35266. this._data = data || [];
  35267. this._uniformLocations = {};
  35268. this._uniformSizes = {};
  35269. this._uniformLocationPointer = 0;
  35270. this._needSync = false;
  35271. if (this._noUBO) {
  35272. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35273. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35274. this.updateFloat = this._updateFloatForEffect;
  35275. this.updateFloat2 = this._updateFloat2ForEffect;
  35276. this.updateFloat3 = this._updateFloat3ForEffect;
  35277. this.updateFloat4 = this._updateFloat4ForEffect;
  35278. this.updateMatrix = this._updateMatrixForEffect;
  35279. this.updateVector3 = this._updateVector3ForEffect;
  35280. this.updateVector4 = this._updateVector4ForEffect;
  35281. this.updateColor3 = this._updateColor3ForEffect;
  35282. this.updateColor4 = this._updateColor4ForEffect;
  35283. }
  35284. else {
  35285. this._engine._uniformBuffers.push(this);
  35286. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35287. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35288. this.updateFloat = this._updateFloatForUniform;
  35289. this.updateFloat2 = this._updateFloat2ForUniform;
  35290. this.updateFloat3 = this._updateFloat3ForUniform;
  35291. this.updateFloat4 = this._updateFloat4ForUniform;
  35292. this.updateMatrix = this._updateMatrixForUniform;
  35293. this.updateVector3 = this._updateVector3ForUniform;
  35294. this.updateVector4 = this._updateVector4ForUniform;
  35295. this.updateColor3 = this._updateColor3ForUniform;
  35296. this.updateColor4 = this._updateColor4ForUniform;
  35297. }
  35298. }
  35299. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35300. // Properties
  35301. /**
  35302. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35303. * or just falling back on setUniformXXX calls.
  35304. */
  35305. get: function () {
  35306. return !this._noUBO;
  35307. },
  35308. enumerable: true,
  35309. configurable: true
  35310. });
  35311. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35312. /**
  35313. * Indicates if the WebGL underlying uniform buffer is in sync
  35314. * with the javascript cache data.
  35315. */
  35316. get: function () {
  35317. return !this._needSync;
  35318. },
  35319. enumerable: true,
  35320. configurable: true
  35321. });
  35322. /**
  35323. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35324. * Also, a dynamic UniformBuffer will disable cache verification and always
  35325. * update the underlying WebGL uniform buffer to the GPU.
  35326. */
  35327. UniformBuffer.prototype.isDynamic = function () {
  35328. return this._dynamic !== undefined;
  35329. };
  35330. /**
  35331. * The data cache on JS side.
  35332. */
  35333. UniformBuffer.prototype.getData = function () {
  35334. return this._bufferData;
  35335. };
  35336. /**
  35337. * The underlying WebGL Uniform buffer.
  35338. */
  35339. UniformBuffer.prototype.getBuffer = function () {
  35340. return this._buffer;
  35341. };
  35342. /**
  35343. * std140 layout specifies how to align data within an UBO structure.
  35344. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35345. * for specs.
  35346. */
  35347. UniformBuffer.prototype._fillAlignment = function (size) {
  35348. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35349. // and 4x4 matrices
  35350. // TODO : change if other types are used
  35351. var alignment;
  35352. if (size <= 2) {
  35353. alignment = size;
  35354. }
  35355. else {
  35356. alignment = 4;
  35357. }
  35358. if ((this._uniformLocationPointer % alignment) !== 0) {
  35359. var oldPointer = this._uniformLocationPointer;
  35360. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35361. var diff = this._uniformLocationPointer - oldPointer;
  35362. for (var i = 0; i < diff; i++) {
  35363. this._data.push(0);
  35364. }
  35365. }
  35366. };
  35367. /**
  35368. * Adds an uniform in the buffer.
  35369. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35370. * for the layout to be correct !
  35371. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35372. * @param {number|number[]} size Data size, or data directly.
  35373. */
  35374. UniformBuffer.prototype.addUniform = function (name, size) {
  35375. if (this._noUBO) {
  35376. return;
  35377. }
  35378. if (this._uniformLocations[name] !== undefined) {
  35379. // Already existing uniform
  35380. return;
  35381. }
  35382. // This function must be called in the order of the shader layout !
  35383. // size can be the size of the uniform, or data directly
  35384. var data;
  35385. if (size instanceof Array) {
  35386. data = size;
  35387. size = data.length;
  35388. }
  35389. else {
  35390. size = size;
  35391. data = [];
  35392. // Fill with zeros
  35393. for (var i = 0; i < size; i++) {
  35394. data.push(0);
  35395. }
  35396. }
  35397. this._fillAlignment(size);
  35398. this._uniformSizes[name] = size;
  35399. this._uniformLocations[name] = this._uniformLocationPointer;
  35400. this._uniformLocationPointer += size;
  35401. for (var i = 0; i < size; i++) {
  35402. this._data.push(data[i]);
  35403. }
  35404. this._needSync = true;
  35405. };
  35406. /**
  35407. * Wrapper for addUniform.
  35408. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35409. * @param {Matrix} mat A 4x4 matrix.
  35410. */
  35411. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35412. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35413. };
  35414. /**
  35415. * Wrapper for addUniform.
  35416. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35417. * @param {number} x
  35418. * @param {number} y
  35419. */
  35420. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35421. var temp = [x, y];
  35422. this.addUniform(name, temp);
  35423. };
  35424. /**
  35425. * Wrapper for addUniform.
  35426. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35427. * @param {number} x
  35428. * @param {number} y
  35429. * @param {number} z
  35430. */
  35431. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35432. var temp = [x, y, z];
  35433. this.addUniform(name, temp);
  35434. };
  35435. /**
  35436. * Wrapper for addUniform.
  35437. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35438. * @param {Color3} color
  35439. */
  35440. UniformBuffer.prototype.addColor3 = function (name, color) {
  35441. var temp = new Array();
  35442. color.toArray(temp);
  35443. this.addUniform(name, temp);
  35444. };
  35445. /**
  35446. * Wrapper for addUniform.
  35447. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35448. * @param {Color3} color
  35449. * @param {number} alpha
  35450. */
  35451. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35452. var temp = new Array();
  35453. color.toArray(temp);
  35454. temp.push(alpha);
  35455. this.addUniform(name, temp);
  35456. };
  35457. /**
  35458. * Wrapper for addUniform.
  35459. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35460. * @param {Vector3} vector
  35461. */
  35462. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35463. var temp = new Array();
  35464. vector.toArray(temp);
  35465. this.addUniform(name, temp);
  35466. };
  35467. /**
  35468. * Wrapper for addUniform.
  35469. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35470. */
  35471. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35472. this.addUniform(name, 12);
  35473. };
  35474. /**
  35475. * Wrapper for addUniform.
  35476. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35477. */
  35478. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35479. this.addUniform(name, 8);
  35480. };
  35481. /**
  35482. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35483. */
  35484. UniformBuffer.prototype.create = function () {
  35485. if (this._noUBO) {
  35486. return;
  35487. }
  35488. if (this._buffer) {
  35489. return; // nothing to do
  35490. }
  35491. // See spec, alignment must be filled as a vec4
  35492. this._fillAlignment(4);
  35493. this._bufferData = new Float32Array(this._data);
  35494. this._rebuild();
  35495. this._needSync = true;
  35496. };
  35497. UniformBuffer.prototype._rebuild = function () {
  35498. if (this._noUBO) {
  35499. return;
  35500. }
  35501. if (this._dynamic) {
  35502. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35503. }
  35504. else {
  35505. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35506. }
  35507. };
  35508. /**
  35509. * Updates the WebGL Uniform Buffer on the GPU.
  35510. * If the `dynamic` flag is set to true, no cache comparison is done.
  35511. * Otherwise, the buffer will be updated only if the cache differs.
  35512. */
  35513. UniformBuffer.prototype.update = function () {
  35514. if (!this._buffer) {
  35515. this.create();
  35516. return;
  35517. }
  35518. if (!this._dynamic && !this._needSync) {
  35519. return;
  35520. }
  35521. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35522. this._needSync = false;
  35523. };
  35524. /**
  35525. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35526. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35527. * @param {number[]|Float32Array} data Flattened data
  35528. * @param {number} size Size of the data.
  35529. */
  35530. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35531. var location = this._uniformLocations[uniformName];
  35532. if (location === undefined) {
  35533. if (this._buffer) {
  35534. // Cannot add an uniform if the buffer is already created
  35535. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35536. return;
  35537. }
  35538. this.addUniform(uniformName, size);
  35539. location = this._uniformLocations[uniformName];
  35540. }
  35541. if (!this._buffer) {
  35542. this.create();
  35543. }
  35544. if (!this._dynamic) {
  35545. // Cache for static uniform buffers
  35546. var changed = false;
  35547. for (var i = 0; i < size; i++) {
  35548. if (this._bufferData[location + i] !== data[i]) {
  35549. changed = true;
  35550. this._bufferData[location + i] = data[i];
  35551. }
  35552. }
  35553. this._needSync = this._needSync || changed;
  35554. }
  35555. else {
  35556. // No cache for dynamic
  35557. for (var i = 0; i < size; i++) {
  35558. this._bufferData[location + i] = data[i];
  35559. }
  35560. }
  35561. };
  35562. // Update methods
  35563. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35564. // To match std140, matrix must be realigned
  35565. for (var i = 0; i < 3; i++) {
  35566. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35567. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35568. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35569. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35570. }
  35571. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35572. };
  35573. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35574. this._currentEffect.setMatrix3x3(name, matrix);
  35575. };
  35576. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35577. this._currentEffect.setMatrix2x2(name, matrix);
  35578. };
  35579. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35580. // To match std140, matrix must be realigned
  35581. for (var i = 0; i < 2; i++) {
  35582. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35583. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35584. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35585. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35586. }
  35587. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35588. };
  35589. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35590. this._currentEffect.setFloat(name, x);
  35591. };
  35592. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35593. UniformBuffer._tempBuffer[0] = x;
  35594. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35595. };
  35596. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35597. if (suffix === void 0) { suffix = ""; }
  35598. this._currentEffect.setFloat2(name + suffix, x, y);
  35599. };
  35600. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35601. if (suffix === void 0) { suffix = ""; }
  35602. UniformBuffer._tempBuffer[0] = x;
  35603. UniformBuffer._tempBuffer[1] = y;
  35604. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35605. };
  35606. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35607. if (suffix === void 0) { suffix = ""; }
  35608. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35609. };
  35610. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35611. if (suffix === void 0) { suffix = ""; }
  35612. UniformBuffer._tempBuffer[0] = x;
  35613. UniformBuffer._tempBuffer[1] = y;
  35614. UniformBuffer._tempBuffer[2] = z;
  35615. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35616. };
  35617. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35618. if (suffix === void 0) { suffix = ""; }
  35619. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35620. };
  35621. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35622. if (suffix === void 0) { suffix = ""; }
  35623. UniformBuffer._tempBuffer[0] = x;
  35624. UniformBuffer._tempBuffer[1] = y;
  35625. UniformBuffer._tempBuffer[2] = z;
  35626. UniformBuffer._tempBuffer[3] = w;
  35627. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35628. };
  35629. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35630. this._currentEffect.setMatrix(name, mat);
  35631. };
  35632. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35633. this.updateUniform(name, mat.toArray(), 16);
  35634. };
  35635. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35636. this._currentEffect.setVector3(name, vector);
  35637. };
  35638. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35639. vector.toArray(UniformBuffer._tempBuffer);
  35640. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35641. };
  35642. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35643. this._currentEffect.setVector4(name, vector);
  35644. };
  35645. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35646. vector.toArray(UniformBuffer._tempBuffer);
  35647. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35648. };
  35649. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35650. if (suffix === void 0) { suffix = ""; }
  35651. this._currentEffect.setColor3(name + suffix, color);
  35652. };
  35653. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35654. if (suffix === void 0) { suffix = ""; }
  35655. color.toArray(UniformBuffer._tempBuffer);
  35656. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35657. };
  35658. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35659. if (suffix === void 0) { suffix = ""; }
  35660. this._currentEffect.setColor4(name + suffix, color, alpha);
  35661. };
  35662. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35663. if (suffix === void 0) { suffix = ""; }
  35664. color.toArray(UniformBuffer._tempBuffer);
  35665. UniformBuffer._tempBuffer[3] = alpha;
  35666. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35667. };
  35668. /**
  35669. * Sets a sampler uniform on the effect.
  35670. * @param {string} name Name of the sampler.
  35671. * @param {Texture} texture
  35672. */
  35673. UniformBuffer.prototype.setTexture = function (name, texture) {
  35674. this._currentEffect.setTexture(name, texture);
  35675. };
  35676. /**
  35677. * Directly updates the value of the uniform in the cache AND on the GPU.
  35678. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35679. * @param {number[]|Float32Array} data Flattened data
  35680. */
  35681. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35682. this.updateUniform(uniformName, data, data.length);
  35683. this.update();
  35684. };
  35685. /**
  35686. * Binds this uniform buffer to an effect.
  35687. * @param {Effect} effect
  35688. * @param {string} name Name of the uniform block in the shader.
  35689. */
  35690. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35691. this._currentEffect = effect;
  35692. if (this._noUBO || !this._buffer) {
  35693. return;
  35694. }
  35695. effect.bindUniformBuffer(this._buffer, name);
  35696. };
  35697. /**
  35698. * Disposes the uniform buffer.
  35699. */
  35700. UniformBuffer.prototype.dispose = function () {
  35701. if (this._noUBO) {
  35702. return;
  35703. }
  35704. var index = this._engine._uniformBuffers.indexOf(this);
  35705. if (index !== -1) {
  35706. this._engine._uniformBuffers.splice(index, 1);
  35707. }
  35708. if (!this._buffer) {
  35709. return;
  35710. }
  35711. if (this._engine._releaseBuffer(this._buffer)) {
  35712. this._buffer = null;
  35713. }
  35714. };
  35715. // Pool for avoiding memory leaks
  35716. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35717. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35718. return UniformBuffer;
  35719. }());
  35720. BABYLON.UniformBuffer = UniformBuffer;
  35721. })(BABYLON || (BABYLON = {}));
  35722. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35723. var BABYLON;
  35724. (function (BABYLON) {
  35725. /**
  35726. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35727. */
  35728. var VertexData = /** @class */ (function () {
  35729. function VertexData() {
  35730. }
  35731. /**
  35732. * Uses the passed data array to set the set the values for the specified kind of data
  35733. * @param data a linear array of floating numbers
  35734. * @param kind the type of data that is being set, eg positions, colors etc
  35735. */
  35736. VertexData.prototype.set = function (data, kind) {
  35737. switch (kind) {
  35738. case BABYLON.VertexBuffer.PositionKind:
  35739. this.positions = data;
  35740. break;
  35741. case BABYLON.VertexBuffer.NormalKind:
  35742. this.normals = data;
  35743. break;
  35744. case BABYLON.VertexBuffer.TangentKind:
  35745. this.tangents = data;
  35746. break;
  35747. case BABYLON.VertexBuffer.UVKind:
  35748. this.uvs = data;
  35749. break;
  35750. case BABYLON.VertexBuffer.UV2Kind:
  35751. this.uvs2 = data;
  35752. break;
  35753. case BABYLON.VertexBuffer.UV3Kind:
  35754. this.uvs3 = data;
  35755. break;
  35756. case BABYLON.VertexBuffer.UV4Kind:
  35757. this.uvs4 = data;
  35758. break;
  35759. case BABYLON.VertexBuffer.UV5Kind:
  35760. this.uvs5 = data;
  35761. break;
  35762. case BABYLON.VertexBuffer.UV6Kind:
  35763. this.uvs6 = data;
  35764. break;
  35765. case BABYLON.VertexBuffer.ColorKind:
  35766. this.colors = data;
  35767. break;
  35768. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35769. this.matricesIndices = data;
  35770. break;
  35771. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35772. this.matricesWeights = data;
  35773. break;
  35774. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35775. this.matricesIndicesExtra = data;
  35776. break;
  35777. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35778. this.matricesWeightsExtra = data;
  35779. break;
  35780. }
  35781. };
  35782. /**
  35783. * Associates the vertexData to the passed Mesh.
  35784. * Sets it as updatable or not (default `false`)
  35785. * @param mesh the mesh the vertexData is applied to
  35786. * @param updatable when used and having the value true allows new data to update the vertexData
  35787. * @returns the VertexData
  35788. */
  35789. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35790. this._applyTo(mesh, updatable);
  35791. return this;
  35792. };
  35793. /**
  35794. * Associates the vertexData to the passed Geometry.
  35795. * Sets it as updatable or not (default `false`)
  35796. * @param geometry the geometry the vertexData is applied to
  35797. * @param updatable when used and having the value true allows new data to update the vertexData
  35798. * @returns VertexData
  35799. */
  35800. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35801. this._applyTo(geometry, updatable);
  35802. return this;
  35803. };
  35804. /**
  35805. * Updates the associated mesh
  35806. * @param mesh the mesh to be updated
  35807. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35808. * @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
  35809. * @returns VertexData
  35810. */
  35811. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  35812. this._update(mesh);
  35813. return this;
  35814. };
  35815. /**
  35816. * Updates the associated geometry
  35817. * @param geometry the geometry to be updated
  35818. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35819. * @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
  35820. * @returns VertexData.
  35821. */
  35822. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  35823. this._update(geometry);
  35824. return this;
  35825. };
  35826. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  35827. if (updatable === void 0) { updatable = false; }
  35828. if (this.positions) {
  35829. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  35830. }
  35831. if (this.normals) {
  35832. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  35833. }
  35834. if (this.tangents) {
  35835. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  35836. }
  35837. if (this.uvs) {
  35838. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  35839. }
  35840. if (this.uvs2) {
  35841. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  35842. }
  35843. if (this.uvs3) {
  35844. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  35845. }
  35846. if (this.uvs4) {
  35847. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  35848. }
  35849. if (this.uvs5) {
  35850. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  35851. }
  35852. if (this.uvs6) {
  35853. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  35854. }
  35855. if (this.colors) {
  35856. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  35857. }
  35858. if (this.matricesIndices) {
  35859. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  35860. }
  35861. if (this.matricesWeights) {
  35862. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  35863. }
  35864. if (this.matricesIndicesExtra) {
  35865. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  35866. }
  35867. if (this.matricesWeightsExtra) {
  35868. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  35869. }
  35870. if (this.indices) {
  35871. meshOrGeometry.setIndices(this.indices, null, updatable);
  35872. }
  35873. return this;
  35874. };
  35875. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  35876. if (this.positions) {
  35877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  35878. }
  35879. if (this.normals) {
  35880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  35881. }
  35882. if (this.tangents) {
  35883. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  35884. }
  35885. if (this.uvs) {
  35886. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  35887. }
  35888. if (this.uvs2) {
  35889. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  35890. }
  35891. if (this.uvs3) {
  35892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  35893. }
  35894. if (this.uvs4) {
  35895. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  35896. }
  35897. if (this.uvs5) {
  35898. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  35899. }
  35900. if (this.uvs6) {
  35901. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  35902. }
  35903. if (this.colors) {
  35904. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  35905. }
  35906. if (this.matricesIndices) {
  35907. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  35908. }
  35909. if (this.matricesWeights) {
  35910. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  35911. }
  35912. if (this.matricesIndicesExtra) {
  35913. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  35914. }
  35915. if (this.matricesWeightsExtra) {
  35916. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  35917. }
  35918. if (this.indices) {
  35919. meshOrGeometry.setIndices(this.indices, null);
  35920. }
  35921. return this;
  35922. };
  35923. /**
  35924. * Transforms each position and each normal of the vertexData according to the passed Matrix
  35925. * @param matrix the transforming matrix
  35926. * @returns the VertexData
  35927. */
  35928. VertexData.prototype.transform = function (matrix) {
  35929. var transformed = BABYLON.Vector3.Zero();
  35930. var index;
  35931. if (this.positions) {
  35932. var position = BABYLON.Vector3.Zero();
  35933. for (index = 0; index < this.positions.length; index += 3) {
  35934. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  35935. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  35936. this.positions[index] = transformed.x;
  35937. this.positions[index + 1] = transformed.y;
  35938. this.positions[index + 2] = transformed.z;
  35939. }
  35940. }
  35941. if (this.normals) {
  35942. var normal = BABYLON.Vector3.Zero();
  35943. for (index = 0; index < this.normals.length; index += 3) {
  35944. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  35945. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  35946. this.normals[index] = transformed.x;
  35947. this.normals[index + 1] = transformed.y;
  35948. this.normals[index + 2] = transformed.z;
  35949. }
  35950. }
  35951. if (this.tangents) {
  35952. var tangent = BABYLON.Vector4.Zero();
  35953. var tangentTransformed = BABYLON.Vector4.Zero();
  35954. for (index = 0; index < this.tangents.length; index += 4) {
  35955. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  35956. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  35957. this.tangents[index] = tangentTransformed.x;
  35958. this.tangents[index + 1] = tangentTransformed.y;
  35959. this.tangents[index + 2] = tangentTransformed.z;
  35960. this.tangents[index + 3] = tangentTransformed.w;
  35961. }
  35962. }
  35963. return this;
  35964. };
  35965. /**
  35966. * Merges the passed VertexData into the current one
  35967. * @param other the VertexData to be merged into the current one
  35968. * @returns the modified VertexData
  35969. */
  35970. VertexData.prototype.merge = function (other) {
  35971. this._validate();
  35972. other._validate();
  35973. if (!this.normals !== !other.normals ||
  35974. !this.tangents !== !other.tangents ||
  35975. !this.uvs !== !other.uvs ||
  35976. !this.uvs2 !== !other.uvs2 ||
  35977. !this.uvs3 !== !other.uvs3 ||
  35978. !this.uvs4 !== !other.uvs4 ||
  35979. !this.uvs5 !== !other.uvs5 ||
  35980. !this.uvs6 !== !other.uvs6 ||
  35981. !this.colors !== !other.colors ||
  35982. !this.matricesIndices !== !other.matricesIndices ||
  35983. !this.matricesWeights !== !other.matricesWeights ||
  35984. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  35985. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  35986. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  35987. }
  35988. if (other.indices) {
  35989. if (!this.indices) {
  35990. this.indices = [];
  35991. }
  35992. var offset = this.positions ? this.positions.length / 3 : 0;
  35993. for (var index = 0; index < other.indices.length; index++) {
  35994. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  35995. this.indices.push(other.indices[index] + offset);
  35996. }
  35997. }
  35998. this.positions = this._mergeElement(this.positions, other.positions);
  35999. this.normals = this._mergeElement(this.normals, other.normals);
  36000. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36001. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36002. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36003. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36004. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36005. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36006. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36007. this.colors = this._mergeElement(this.colors, other.colors);
  36008. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36009. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36010. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36011. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36012. return this;
  36013. };
  36014. VertexData.prototype._mergeElement = function (source, other) {
  36015. if (!source) {
  36016. return other;
  36017. }
  36018. if (!other) {
  36019. return source;
  36020. }
  36021. var len = other.length + source.length;
  36022. var isSrcTypedArray = source instanceof Float32Array;
  36023. var isOthTypedArray = other instanceof Float32Array;
  36024. // use non-loop method when the source is Float32Array
  36025. if (isSrcTypedArray) {
  36026. var ret32 = new Float32Array(len);
  36027. ret32.set(source);
  36028. ret32.set(other, source.length);
  36029. return ret32;
  36030. // source is number[], when other is also use concat
  36031. }
  36032. else if (!isOthTypedArray) {
  36033. return source.concat(other);
  36034. // source is a number[], but other is a Float32Array, loop required
  36035. }
  36036. else {
  36037. var ret = source.slice(0); // copy source to a separate array
  36038. for (var i = 0, len = other.length; i < len; i++) {
  36039. ret.push(other[i]);
  36040. }
  36041. return ret;
  36042. }
  36043. };
  36044. VertexData.prototype._validate = function () {
  36045. if (!this.positions) {
  36046. throw new Error("Positions are required");
  36047. }
  36048. var getElementCount = function (kind, values) {
  36049. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36050. if ((values.length % stride) !== 0) {
  36051. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36052. }
  36053. return values.length / stride;
  36054. };
  36055. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36056. var validateElementCount = function (kind, values) {
  36057. var elementCount = getElementCount(kind, values);
  36058. if (elementCount !== positionsElementCount) {
  36059. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36060. }
  36061. };
  36062. if (this.normals)
  36063. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36064. if (this.tangents)
  36065. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36066. if (this.uvs)
  36067. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36068. if (this.uvs2)
  36069. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36070. if (this.uvs3)
  36071. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36072. if (this.uvs4)
  36073. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36074. if (this.uvs5)
  36075. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36076. if (this.uvs6)
  36077. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36078. if (this.colors)
  36079. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36080. if (this.matricesIndices)
  36081. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36082. if (this.matricesWeights)
  36083. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36084. if (this.matricesIndicesExtra)
  36085. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36086. if (this.matricesWeightsExtra)
  36087. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36088. };
  36089. /**
  36090. * Serializes the VertexData
  36091. * @returns a serialized object
  36092. */
  36093. VertexData.prototype.serialize = function () {
  36094. var serializationObject = this.serialize();
  36095. if (this.positions) {
  36096. serializationObject.positions = this.positions;
  36097. }
  36098. if (this.normals) {
  36099. serializationObject.normals = this.normals;
  36100. }
  36101. if (this.tangents) {
  36102. serializationObject.tangents = this.tangents;
  36103. }
  36104. if (this.uvs) {
  36105. serializationObject.uvs = this.uvs;
  36106. }
  36107. if (this.uvs2) {
  36108. serializationObject.uvs2 = this.uvs2;
  36109. }
  36110. if (this.uvs3) {
  36111. serializationObject.uvs3 = this.uvs3;
  36112. }
  36113. if (this.uvs4) {
  36114. serializationObject.uvs4 = this.uvs4;
  36115. }
  36116. if (this.uvs5) {
  36117. serializationObject.uvs5 = this.uvs5;
  36118. }
  36119. if (this.uvs6) {
  36120. serializationObject.uvs6 = this.uvs6;
  36121. }
  36122. if (this.colors) {
  36123. serializationObject.colors = this.colors;
  36124. }
  36125. if (this.matricesIndices) {
  36126. serializationObject.matricesIndices = this.matricesIndices;
  36127. serializationObject.matricesIndices._isExpanded = true;
  36128. }
  36129. if (this.matricesWeights) {
  36130. serializationObject.matricesWeights = this.matricesWeights;
  36131. }
  36132. if (this.matricesIndicesExtra) {
  36133. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36134. serializationObject.matricesIndicesExtra._isExpanded = true;
  36135. }
  36136. if (this.matricesWeightsExtra) {
  36137. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36138. }
  36139. serializationObject.indices = this.indices;
  36140. return serializationObject;
  36141. };
  36142. // Statics
  36143. /**
  36144. * Extracts the vertexData from a mesh
  36145. * @param mesh the mesh from which to extract the VertexData
  36146. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36147. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36148. * @returns the object VertexData associated to the passed mesh
  36149. */
  36150. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36151. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36152. };
  36153. /**
  36154. * Extracts the vertexData from the geometry
  36155. * @param geometry the geometry from which to extract the VertexData
  36156. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36157. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36158. * @returns the object VertexData associated to the passed mesh
  36159. */
  36160. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36161. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36162. };
  36163. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36164. var result = new VertexData();
  36165. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36166. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36167. }
  36168. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36169. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36170. }
  36171. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36172. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36173. }
  36174. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36175. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36176. }
  36177. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36178. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36179. }
  36180. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36181. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36182. }
  36183. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36184. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36185. }
  36186. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36187. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36188. }
  36189. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36190. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36191. }
  36192. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36193. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36194. }
  36195. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36196. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36197. }
  36198. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36199. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36200. }
  36201. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36202. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36203. }
  36204. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36205. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36206. }
  36207. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36208. return result;
  36209. };
  36210. /**
  36211. * Creates the VertexData for a Ribbon
  36212. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36213. * * pathArray array of paths, each of which an array of successive Vector3
  36214. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36215. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36216. * * 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
  36217. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36218. * * 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)
  36219. * * 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)
  36220. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36221. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36222. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36223. * @returns the VertexData of the ribbon
  36224. */
  36225. VertexData.CreateRibbon = function (options) {
  36226. var pathArray = options.pathArray;
  36227. var closeArray = options.closeArray || false;
  36228. var closePath = options.closePath || false;
  36229. var invertUV = options.invertUV || false;
  36230. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36231. var offset = options.offset || defaultOffset;
  36232. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36233. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36234. var customUV = options.uvs;
  36235. var customColors = options.colors;
  36236. var positions = [];
  36237. var indices = [];
  36238. var normals = [];
  36239. var uvs = [];
  36240. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36241. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36242. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36243. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36244. var minlg; // minimal length among all paths from pathArray
  36245. var lg = []; // array of path lengths : nb of vertex per path
  36246. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36247. var p; // path iterator
  36248. var i; // point iterator
  36249. var j; // point iterator
  36250. // if single path in pathArray
  36251. if (pathArray.length < 2) {
  36252. var ar1 = [];
  36253. var ar2 = [];
  36254. for (i = 0; i < pathArray[0].length - offset; i++) {
  36255. ar1.push(pathArray[0][i]);
  36256. ar2.push(pathArray[0][i + offset]);
  36257. }
  36258. pathArray = [ar1, ar2];
  36259. }
  36260. // positions and horizontal distances (u)
  36261. var idc = 0;
  36262. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36263. var path;
  36264. var l;
  36265. minlg = pathArray[0].length;
  36266. var vectlg;
  36267. var dist;
  36268. for (p = 0; p < pathArray.length; p++) {
  36269. uTotalDistance[p] = 0;
  36270. us[p] = [0];
  36271. path = pathArray[p];
  36272. l = path.length;
  36273. minlg = (minlg < l) ? minlg : l;
  36274. j = 0;
  36275. while (j < l) {
  36276. positions.push(path[j].x, path[j].y, path[j].z);
  36277. if (j > 0) {
  36278. vectlg = path[j].subtract(path[j - 1]).length();
  36279. dist = vectlg + uTotalDistance[p];
  36280. us[p].push(dist);
  36281. uTotalDistance[p] = dist;
  36282. }
  36283. j++;
  36284. }
  36285. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36286. j--;
  36287. positions.push(path[0].x, path[0].y, path[0].z);
  36288. vectlg = path[j].subtract(path[0]).length();
  36289. dist = vectlg + uTotalDistance[p];
  36290. us[p].push(dist);
  36291. uTotalDistance[p] = dist;
  36292. }
  36293. lg[p] = l + closePathCorr;
  36294. idx[p] = idc;
  36295. idc += (l + closePathCorr);
  36296. }
  36297. // vertical distances (v)
  36298. var path1;
  36299. var path2;
  36300. var vertex1 = null;
  36301. var vertex2 = null;
  36302. for (i = 0; i < minlg + closePathCorr; i++) {
  36303. vTotalDistance[i] = 0;
  36304. vs[i] = [0];
  36305. for (p = 0; p < pathArray.length - 1; p++) {
  36306. path1 = pathArray[p];
  36307. path2 = pathArray[p + 1];
  36308. if (i === minlg) { // closePath
  36309. vertex1 = path1[0];
  36310. vertex2 = path2[0];
  36311. }
  36312. else {
  36313. vertex1 = path1[i];
  36314. vertex2 = path2[i];
  36315. }
  36316. vectlg = vertex2.subtract(vertex1).length();
  36317. dist = vectlg + vTotalDistance[i];
  36318. vs[i].push(dist);
  36319. vTotalDistance[i] = dist;
  36320. }
  36321. if (closeArray && vertex2 && vertex1) {
  36322. path1 = pathArray[p];
  36323. path2 = pathArray[0];
  36324. if (i === minlg) { // closePath
  36325. vertex2 = path2[0];
  36326. }
  36327. vectlg = vertex2.subtract(vertex1).length();
  36328. dist = vectlg + vTotalDistance[i];
  36329. vTotalDistance[i] = dist;
  36330. }
  36331. }
  36332. // uvs
  36333. var u;
  36334. var v;
  36335. if (customUV) {
  36336. for (p = 0; p < customUV.length; p++) {
  36337. uvs.push(customUV[p].x, customUV[p].y);
  36338. }
  36339. }
  36340. else {
  36341. for (p = 0; p < pathArray.length; p++) {
  36342. for (i = 0; i < minlg + closePathCorr; i++) {
  36343. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36344. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36345. if (invertUV) {
  36346. uvs.push(v, u);
  36347. }
  36348. else {
  36349. uvs.push(u, v);
  36350. }
  36351. }
  36352. }
  36353. }
  36354. // indices
  36355. p = 0; // path index
  36356. var pi = 0; // positions array index
  36357. var l1 = lg[p] - 1; // path1 length
  36358. var l2 = lg[p + 1] - 1; // path2 length
  36359. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36360. var shft = idx[1] - idx[0]; // shift
  36361. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36362. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36363. // 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
  36364. indices.push(pi, pi + shft, pi + 1);
  36365. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36366. pi += 1;
  36367. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36368. p++;
  36369. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36370. shft = idx[0] - idx[p];
  36371. l1 = lg[p] - 1;
  36372. l2 = lg[0] - 1;
  36373. }
  36374. else {
  36375. shft = idx[p + 1] - idx[p];
  36376. l1 = lg[p] - 1;
  36377. l2 = lg[p + 1] - 1;
  36378. }
  36379. pi = idx[p];
  36380. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36381. }
  36382. }
  36383. // normals
  36384. VertexData.ComputeNormals(positions, indices, normals);
  36385. if (closePath) { // update both the first and last vertex normals to their average value
  36386. var indexFirst = 0;
  36387. var indexLast = 0;
  36388. for (p = 0; p < pathArray.length; p++) {
  36389. indexFirst = idx[p] * 3;
  36390. if (p + 1 < pathArray.length) {
  36391. indexLast = (idx[p + 1] - 1) * 3;
  36392. }
  36393. else {
  36394. indexLast = normals.length - 3;
  36395. }
  36396. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36397. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36398. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36399. normals[indexLast] = normals[indexFirst];
  36400. normals[indexLast + 1] = normals[indexFirst + 1];
  36401. normals[indexLast + 2] = normals[indexFirst + 2];
  36402. }
  36403. }
  36404. // sides
  36405. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36406. // Colors
  36407. var colors = null;
  36408. if (customColors) {
  36409. colors = new Float32Array(customColors.length * 4);
  36410. for (var c = 0; c < customColors.length; c++) {
  36411. colors[c * 4] = customColors[c].r;
  36412. colors[c * 4 + 1] = customColors[c].g;
  36413. colors[c * 4 + 2] = customColors[c].b;
  36414. colors[c * 4 + 3] = customColors[c].a;
  36415. }
  36416. }
  36417. // Result
  36418. var vertexData = new VertexData();
  36419. var positions32 = new Float32Array(positions);
  36420. var normals32 = new Float32Array(normals);
  36421. var uvs32 = new Float32Array(uvs);
  36422. vertexData.indices = indices;
  36423. vertexData.positions = positions32;
  36424. vertexData.normals = normals32;
  36425. vertexData.uvs = uvs32;
  36426. if (colors) {
  36427. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36428. }
  36429. if (closePath) {
  36430. vertexData._idx = idx;
  36431. }
  36432. return vertexData;
  36433. };
  36434. /**
  36435. * Creates the VertexData for a box
  36436. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36437. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36438. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36439. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36440. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36441. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36442. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36443. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36444. * * 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)
  36445. * * 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)
  36446. * @returns the VertexData of the box
  36447. */
  36448. VertexData.CreateBox = function (options) {
  36449. var normalsSource = [
  36450. new BABYLON.Vector3(0, 0, 1),
  36451. new BABYLON.Vector3(0, 0, -1),
  36452. new BABYLON.Vector3(1, 0, 0),
  36453. new BABYLON.Vector3(-1, 0, 0),
  36454. new BABYLON.Vector3(0, 1, 0),
  36455. new BABYLON.Vector3(0, -1, 0)
  36456. ];
  36457. var indices = [];
  36458. var positions = [];
  36459. var normals = [];
  36460. var uvs = [];
  36461. var width = options.width || options.size || 1;
  36462. var height = options.height || options.size || 1;
  36463. var depth = options.depth || options.size || 1;
  36464. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36465. var faceUV = options.faceUV || new Array(6);
  36466. var faceColors = options.faceColors;
  36467. var colors = [];
  36468. // default face colors and UV if undefined
  36469. for (var f = 0; f < 6; f++) {
  36470. if (faceUV[f] === undefined) {
  36471. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36472. }
  36473. if (faceColors && faceColors[f] === undefined) {
  36474. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36475. }
  36476. }
  36477. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36478. // Create each face in turn.
  36479. for (var index = 0; index < normalsSource.length; index++) {
  36480. var normal = normalsSource[index];
  36481. // Get two vectors perpendicular to the face normal and to each other.
  36482. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36483. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36484. // Six indices (two triangles) per face.
  36485. var verticesLength = positions.length / 3;
  36486. indices.push(verticesLength);
  36487. indices.push(verticesLength + 1);
  36488. indices.push(verticesLength + 2);
  36489. indices.push(verticesLength);
  36490. indices.push(verticesLength + 2);
  36491. indices.push(verticesLength + 3);
  36492. // Four vertices per face.
  36493. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36494. positions.push(vertex.x, vertex.y, vertex.z);
  36495. normals.push(normal.x, normal.y, normal.z);
  36496. uvs.push(faceUV[index].z, faceUV[index].w);
  36497. if (faceColors) {
  36498. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36499. }
  36500. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36501. positions.push(vertex.x, vertex.y, vertex.z);
  36502. normals.push(normal.x, normal.y, normal.z);
  36503. uvs.push(faceUV[index].x, faceUV[index].w);
  36504. if (faceColors) {
  36505. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36506. }
  36507. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36508. positions.push(vertex.x, vertex.y, vertex.z);
  36509. normals.push(normal.x, normal.y, normal.z);
  36510. uvs.push(faceUV[index].x, faceUV[index].y);
  36511. if (faceColors) {
  36512. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36513. }
  36514. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36515. positions.push(vertex.x, vertex.y, vertex.z);
  36516. normals.push(normal.x, normal.y, normal.z);
  36517. uvs.push(faceUV[index].z, faceUV[index].y);
  36518. if (faceColors) {
  36519. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36520. }
  36521. }
  36522. // sides
  36523. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36524. // Result
  36525. var vertexData = new VertexData();
  36526. vertexData.indices = indices;
  36527. vertexData.positions = positions;
  36528. vertexData.normals = normals;
  36529. vertexData.uvs = uvs;
  36530. if (faceColors) {
  36531. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36532. vertexData.colors = totalColors;
  36533. }
  36534. return vertexData;
  36535. };
  36536. /**
  36537. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36538. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36539. * * segments sets the number of horizontal strips optional, default 32
  36540. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36541. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36542. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36543. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36544. * * 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
  36545. * * 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
  36546. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36547. * * 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)
  36548. * * 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)
  36549. * @returns the VertexData of the ellipsoid
  36550. */
  36551. VertexData.CreateSphere = function (options) {
  36552. var segments = options.segments || 32;
  36553. var diameterX = options.diameterX || options.diameter || 1;
  36554. var diameterY = options.diameterY || options.diameter || 1;
  36555. var diameterZ = options.diameterZ || options.diameter || 1;
  36556. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36557. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36558. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36559. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36560. var totalZRotationSteps = 2 + segments;
  36561. var totalYRotationSteps = 2 * totalZRotationSteps;
  36562. var indices = [];
  36563. var positions = [];
  36564. var normals = [];
  36565. var uvs = [];
  36566. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36567. var normalizedZ = zRotationStep / totalZRotationSteps;
  36568. var angleZ = normalizedZ * Math.PI * slice;
  36569. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36570. var normalizedY = yRotationStep / totalYRotationSteps;
  36571. var angleY = normalizedY * Math.PI * 2 * arc;
  36572. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36573. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36574. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36575. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36576. var vertex = complete.multiply(radius);
  36577. var normal = complete.divide(radius).normalize();
  36578. positions.push(vertex.x, vertex.y, vertex.z);
  36579. normals.push(normal.x, normal.y, normal.z);
  36580. uvs.push(normalizedY, normalizedZ);
  36581. }
  36582. if (zRotationStep > 0) {
  36583. var verticesCount = positions.length / 3;
  36584. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36585. indices.push((firstIndex));
  36586. indices.push((firstIndex + 1));
  36587. indices.push(firstIndex + totalYRotationSteps + 1);
  36588. indices.push((firstIndex + totalYRotationSteps + 1));
  36589. indices.push((firstIndex + 1));
  36590. indices.push((firstIndex + totalYRotationSteps + 2));
  36591. }
  36592. }
  36593. }
  36594. // Sides
  36595. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36596. // Result
  36597. var vertexData = new VertexData();
  36598. vertexData.indices = indices;
  36599. vertexData.positions = positions;
  36600. vertexData.normals = normals;
  36601. vertexData.uvs = uvs;
  36602. return vertexData;
  36603. };
  36604. /**
  36605. * Creates the VertexData for a cylinder, cone or prism
  36606. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36607. * * height sets the height (y direction) of the cylinder, optional, default 2
  36608. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36609. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36610. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36611. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36612. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36613. * * 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
  36614. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36615. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36616. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36617. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36618. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36619. * * 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)
  36620. * * 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)
  36621. * @returns the VertexData of the cylinder, cone or prism
  36622. */
  36623. VertexData.CreateCylinder = function (options) {
  36624. var height = options.height || 2;
  36625. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36626. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36627. var tessellation = options.tessellation || 24;
  36628. var subdivisions = options.subdivisions || 1;
  36629. var hasRings = options.hasRings ? true : false;
  36630. var enclose = options.enclose ? true : false;
  36631. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36632. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36633. var faceUV = options.faceUV || new Array(3);
  36634. var faceColors = options.faceColors;
  36635. // default face colors and UV if undefined
  36636. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36637. var ringNb = (hasRings) ? subdivisions : 1;
  36638. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36639. var f;
  36640. for (f = 0; f < surfaceNb; f++) {
  36641. if (faceColors && faceColors[f] === undefined) {
  36642. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36643. }
  36644. }
  36645. for (f = 0; f < surfaceNb; f++) {
  36646. if (faceUV && faceUV[f] === undefined) {
  36647. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36648. }
  36649. }
  36650. var indices = new Array();
  36651. var positions = new Array();
  36652. var normals = new Array();
  36653. var uvs = new Array();
  36654. var colors = new Array();
  36655. var angle_step = Math.PI * 2 * arc / tessellation;
  36656. var angle;
  36657. var h;
  36658. var radius;
  36659. var tan = (diameterBottom - diameterTop) / 2 / height;
  36660. var ringVertex = BABYLON.Vector3.Zero();
  36661. var ringNormal = BABYLON.Vector3.Zero();
  36662. var ringFirstVertex = BABYLON.Vector3.Zero();
  36663. var ringFirstNormal = BABYLON.Vector3.Zero();
  36664. var quadNormal = BABYLON.Vector3.Zero();
  36665. var Y = BABYLON.Axis.Y;
  36666. // positions, normals, uvs
  36667. var i;
  36668. var j;
  36669. var r;
  36670. var ringIdx = 1;
  36671. var s = 1; // surface index
  36672. var cs = 0;
  36673. var v = 0;
  36674. for (i = 0; i <= subdivisions; i++) {
  36675. h = i / subdivisions;
  36676. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36677. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36678. for (r = 0; r < ringIdx; r++) {
  36679. if (hasRings) {
  36680. s += r;
  36681. }
  36682. if (enclose) {
  36683. s += 2 * r;
  36684. }
  36685. for (j = 0; j <= tessellation; j++) {
  36686. angle = j * angle_step;
  36687. // position
  36688. ringVertex.x = Math.cos(-angle) * radius;
  36689. ringVertex.y = -height / 2 + h * height;
  36690. ringVertex.z = Math.sin(-angle) * radius;
  36691. // normal
  36692. if (diameterTop === 0 && i === subdivisions) {
  36693. // if no top cap, reuse former normals
  36694. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36695. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36696. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36697. }
  36698. else {
  36699. ringNormal.x = ringVertex.x;
  36700. ringNormal.z = ringVertex.z;
  36701. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36702. ringNormal.normalize();
  36703. }
  36704. // keep first ring vertex values for enclose
  36705. if (j === 0) {
  36706. ringFirstVertex.copyFrom(ringVertex);
  36707. ringFirstNormal.copyFrom(ringNormal);
  36708. }
  36709. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36710. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36711. if (hasRings) {
  36712. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36713. }
  36714. else {
  36715. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36716. }
  36717. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36718. if (faceColors) {
  36719. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36720. }
  36721. }
  36722. // if enclose, add four vertices and their dedicated normals
  36723. if (arc !== 1 && enclose) {
  36724. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36725. positions.push(0, ringVertex.y, 0);
  36726. positions.push(0, ringVertex.y, 0);
  36727. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36728. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36729. quadNormal.normalize();
  36730. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36731. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36732. quadNormal.normalize();
  36733. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36734. if (hasRings) {
  36735. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36736. }
  36737. else {
  36738. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36739. }
  36740. uvs.push(faceUV[s + 1].x, v);
  36741. uvs.push(faceUV[s + 1].z, v);
  36742. if (hasRings) {
  36743. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36744. }
  36745. else {
  36746. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36747. }
  36748. uvs.push(faceUV[s + 2].x, v);
  36749. uvs.push(faceUV[s + 2].z, v);
  36750. if (faceColors) {
  36751. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36752. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36753. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36754. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36755. }
  36756. }
  36757. if (cs !== s) {
  36758. cs = s;
  36759. }
  36760. }
  36761. }
  36762. // indices
  36763. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36764. var s;
  36765. i = 0;
  36766. for (s = 0; s < subdivisions; s++) {
  36767. var i0 = 0;
  36768. var i1 = 0;
  36769. var i2 = 0;
  36770. var i3 = 0;
  36771. for (j = 0; j < tessellation; j++) {
  36772. i0 = i * (e + 1) + j;
  36773. i1 = (i + 1) * (e + 1) + j;
  36774. i2 = i * (e + 1) + (j + 1);
  36775. i3 = (i + 1) * (e + 1) + (j + 1);
  36776. indices.push(i0, i1, i2);
  36777. indices.push(i3, i2, i1);
  36778. }
  36779. if (arc !== 1 && enclose) { // if enclose, add two quads
  36780. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36781. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36782. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36783. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36784. }
  36785. i = (hasRings) ? (i + 2) : (i + 1);
  36786. }
  36787. // Caps
  36788. var createCylinderCap = function (isTop) {
  36789. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36790. if (radius === 0) {
  36791. return;
  36792. }
  36793. // Cap positions, normals & uvs
  36794. var angle;
  36795. var circleVector;
  36796. var i;
  36797. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36798. var c = null;
  36799. if (faceColors) {
  36800. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36801. }
  36802. // cap center
  36803. var vbase = positions.length / 3;
  36804. var offset = isTop ? height / 2 : -height / 2;
  36805. var center = new BABYLON.Vector3(0, offset, 0);
  36806. positions.push(center.x, center.y, center.z);
  36807. normals.push(0, isTop ? 1 : -1, 0);
  36808. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36809. if (c) {
  36810. colors.push(c.r, c.g, c.b, c.a);
  36811. }
  36812. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  36813. for (i = 0; i <= tessellation; i++) {
  36814. angle = Math.PI * 2 * i * arc / tessellation;
  36815. var cos = Math.cos(-angle);
  36816. var sin = Math.sin(-angle);
  36817. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  36818. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  36819. positions.push(circleVector.x, circleVector.y, circleVector.z);
  36820. normals.push(0, isTop ? 1 : -1, 0);
  36821. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  36822. if (c) {
  36823. colors.push(c.r, c.g, c.b, c.a);
  36824. }
  36825. }
  36826. // Cap indices
  36827. for (i = 0; i < tessellation; i++) {
  36828. if (!isTop) {
  36829. indices.push(vbase);
  36830. indices.push(vbase + (i + 1));
  36831. indices.push(vbase + (i + 2));
  36832. }
  36833. else {
  36834. indices.push(vbase);
  36835. indices.push(vbase + (i + 2));
  36836. indices.push(vbase + (i + 1));
  36837. }
  36838. }
  36839. };
  36840. // add caps to geometry
  36841. createCylinderCap(false);
  36842. createCylinderCap(true);
  36843. // Sides
  36844. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36845. var vertexData = new VertexData();
  36846. vertexData.indices = indices;
  36847. vertexData.positions = positions;
  36848. vertexData.normals = normals;
  36849. vertexData.uvs = uvs;
  36850. if (faceColors) {
  36851. vertexData.colors = colors;
  36852. }
  36853. return vertexData;
  36854. };
  36855. /**
  36856. * Creates the VertexData for a torus
  36857. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36858. * * diameter the diameter of the torus, optional default 1
  36859. * * thickness the diameter of the tube forming the torus, optional default 0.5
  36860. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36861. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36862. * * 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)
  36863. * * 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)
  36864. * @returns the VertexData of the torus
  36865. */
  36866. VertexData.CreateTorus = function (options) {
  36867. var indices = [];
  36868. var positions = [];
  36869. var normals = [];
  36870. var uvs = [];
  36871. var diameter = options.diameter || 1;
  36872. var thickness = options.thickness || 0.5;
  36873. var tessellation = options.tessellation || 16;
  36874. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36875. var stride = tessellation + 1;
  36876. for (var i = 0; i <= tessellation; i++) {
  36877. var u = i / tessellation;
  36878. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  36879. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  36880. for (var j = 0; j <= tessellation; j++) {
  36881. var v = 1 - j / tessellation;
  36882. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  36883. var dx = Math.cos(innerAngle);
  36884. var dy = Math.sin(innerAngle);
  36885. // Create a vertex.
  36886. var normal = new BABYLON.Vector3(dx, dy, 0);
  36887. var position = normal.scale(thickness / 2);
  36888. var textureCoordinate = new BABYLON.Vector2(u, v);
  36889. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  36890. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  36891. positions.push(position.x, position.y, position.z);
  36892. normals.push(normal.x, normal.y, normal.z);
  36893. uvs.push(textureCoordinate.x, textureCoordinate.y);
  36894. // And create indices for two triangles.
  36895. var nextI = (i + 1) % stride;
  36896. var nextJ = (j + 1) % stride;
  36897. indices.push(i * stride + j);
  36898. indices.push(i * stride + nextJ);
  36899. indices.push(nextI * stride + j);
  36900. indices.push(i * stride + nextJ);
  36901. indices.push(nextI * stride + nextJ);
  36902. indices.push(nextI * stride + j);
  36903. }
  36904. }
  36905. // Sides
  36906. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36907. // Result
  36908. var vertexData = new VertexData();
  36909. vertexData.indices = indices;
  36910. vertexData.positions = positions;
  36911. vertexData.normals = normals;
  36912. vertexData.uvs = uvs;
  36913. return vertexData;
  36914. };
  36915. /**
  36916. * Creates the VertexData of the LineSystem
  36917. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  36918. * - lines an array of lines, each line being an array of successive Vector3
  36919. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  36920. * @returns the VertexData of the LineSystem
  36921. */
  36922. VertexData.CreateLineSystem = function (options) {
  36923. var indices = [];
  36924. var positions = [];
  36925. var lines = options.lines;
  36926. var colors = options.colors;
  36927. var vertexColors = [];
  36928. var idx = 0;
  36929. for (var l = 0; l < lines.length; l++) {
  36930. var points = lines[l];
  36931. for (var index = 0; index < points.length; index++) {
  36932. positions.push(points[index].x, points[index].y, points[index].z);
  36933. if (colors) {
  36934. var color = colors[l];
  36935. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  36936. }
  36937. if (index > 0) {
  36938. indices.push(idx - 1);
  36939. indices.push(idx);
  36940. }
  36941. idx++;
  36942. }
  36943. }
  36944. var vertexData = new VertexData();
  36945. vertexData.indices = indices;
  36946. vertexData.positions = positions;
  36947. if (colors) {
  36948. vertexData.colors = vertexColors;
  36949. }
  36950. return vertexData;
  36951. };
  36952. /**
  36953. * Create the VertexData for a DashedLines
  36954. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  36955. * - points an array successive Vector3
  36956. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  36957. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  36958. * - dashNb the intended total number of dashes, optional, default 200
  36959. * @returns the VertexData for the DashedLines
  36960. */
  36961. VertexData.CreateDashedLines = function (options) {
  36962. var dashSize = options.dashSize || 3;
  36963. var gapSize = options.gapSize || 1;
  36964. var dashNb = options.dashNb || 200;
  36965. var points = options.points;
  36966. var positions = new Array();
  36967. var indices = new Array();
  36968. var curvect = BABYLON.Vector3.Zero();
  36969. var lg = 0;
  36970. var nb = 0;
  36971. var shft = 0;
  36972. var dashshft = 0;
  36973. var curshft = 0;
  36974. var idx = 0;
  36975. var i = 0;
  36976. for (i = 0; i < points.length - 1; i++) {
  36977. points[i + 1].subtractToRef(points[i], curvect);
  36978. lg += curvect.length();
  36979. }
  36980. shft = lg / dashNb;
  36981. dashshft = dashSize * shft / (dashSize + gapSize);
  36982. for (i = 0; i < points.length - 1; i++) {
  36983. points[i + 1].subtractToRef(points[i], curvect);
  36984. nb = Math.floor(curvect.length() / shft);
  36985. curvect.normalize();
  36986. for (var j = 0; j < nb; j++) {
  36987. curshft = shft * j;
  36988. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  36989. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  36990. indices.push(idx, idx + 1);
  36991. idx += 2;
  36992. }
  36993. }
  36994. // Result
  36995. var vertexData = new VertexData();
  36996. vertexData.positions = positions;
  36997. vertexData.indices = indices;
  36998. return vertexData;
  36999. };
  37000. /**
  37001. * Creates the VertexData for a Ground
  37002. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37003. * - width the width (x direction) of the ground, optional, default 1
  37004. * - height the height (z direction) of the ground, optional, default 1
  37005. * - subdivisions the number of subdivisions per side, optional, default 1
  37006. * @returns the VertexData of the Ground
  37007. */
  37008. VertexData.CreateGround = function (options) {
  37009. var indices = [];
  37010. var positions = [];
  37011. var normals = [];
  37012. var uvs = [];
  37013. var row, col;
  37014. var width = options.width || 1;
  37015. var height = options.height || 1;
  37016. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37017. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37018. for (row = 0; row <= subdivisionsY; row++) {
  37019. for (col = 0; col <= subdivisionsX; col++) {
  37020. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37021. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37022. positions.push(position.x, position.y, position.z);
  37023. normals.push(normal.x, normal.y, normal.z);
  37024. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37025. }
  37026. }
  37027. for (row = 0; row < subdivisionsY; row++) {
  37028. for (col = 0; col < subdivisionsX; col++) {
  37029. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37030. indices.push(col + 1 + row * (subdivisionsX + 1));
  37031. indices.push(col + row * (subdivisionsX + 1));
  37032. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37033. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37034. indices.push(col + row * (subdivisionsX + 1));
  37035. }
  37036. }
  37037. // Result
  37038. var vertexData = new VertexData();
  37039. vertexData.indices = indices;
  37040. vertexData.positions = positions;
  37041. vertexData.normals = normals;
  37042. vertexData.uvs = uvs;
  37043. return vertexData;
  37044. };
  37045. /**
  37046. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37047. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37048. * * xmin the ground minimum X coordinate, optional, default -1
  37049. * * zmin the ground minimum Z coordinate, optional, default -1
  37050. * * xmax the ground maximum X coordinate, optional, default 1
  37051. * * zmax the ground maximum Z coordinate, optional, default 1
  37052. * * 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}
  37053. * * 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}
  37054. * @returns the VertexData of the TiledGround
  37055. */
  37056. VertexData.CreateTiledGround = function (options) {
  37057. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37058. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37059. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37060. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37061. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37062. var precision = options.precision || { w: 1, h: 1 };
  37063. var indices = new Array();
  37064. var positions = new Array();
  37065. var normals = new Array();
  37066. var uvs = new Array();
  37067. var row, col, tileRow, tileCol;
  37068. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37069. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37070. precision.w = (precision.w < 1) ? 1 : precision.w;
  37071. precision.h = (precision.h < 1) ? 1 : precision.h;
  37072. var tileSize = {
  37073. 'w': (xmax - xmin) / subdivisions.w,
  37074. 'h': (zmax - zmin) / subdivisions.h
  37075. };
  37076. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37077. // Indices
  37078. var base = positions.length / 3;
  37079. var rowLength = precision.w + 1;
  37080. for (row = 0; row < precision.h; row++) {
  37081. for (col = 0; col < precision.w; col++) {
  37082. var square = [
  37083. base + col + row * rowLength,
  37084. base + (col + 1) + row * rowLength,
  37085. base + (col + 1) + (row + 1) * rowLength,
  37086. base + col + (row + 1) * rowLength
  37087. ];
  37088. indices.push(square[1]);
  37089. indices.push(square[2]);
  37090. indices.push(square[3]);
  37091. indices.push(square[0]);
  37092. indices.push(square[1]);
  37093. indices.push(square[3]);
  37094. }
  37095. }
  37096. // Position, normals and uvs
  37097. var position = BABYLON.Vector3.Zero();
  37098. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37099. for (row = 0; row <= precision.h; row++) {
  37100. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37101. for (col = 0; col <= precision.w; col++) {
  37102. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37103. position.y = 0;
  37104. positions.push(position.x, position.y, position.z);
  37105. normals.push(normal.x, normal.y, normal.z);
  37106. uvs.push(col / precision.w, row / precision.h);
  37107. }
  37108. }
  37109. }
  37110. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37111. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37112. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37113. }
  37114. }
  37115. // Result
  37116. var vertexData = new VertexData();
  37117. vertexData.indices = indices;
  37118. vertexData.positions = positions;
  37119. vertexData.normals = normals;
  37120. vertexData.uvs = uvs;
  37121. return vertexData;
  37122. };
  37123. /**
  37124. * Creates the VertexData of the Ground designed from a heightmap
  37125. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37126. * * width the width (x direction) of the ground
  37127. * * height the height (z direction) of the ground
  37128. * * subdivisions the number of subdivisions per side
  37129. * * minHeight the minimum altitude on the ground, optional, default 0
  37130. * * maxHeight the maximum altitude on the ground, optional default 1
  37131. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37132. * * buffer the array holding the image color data
  37133. * * bufferWidth the width of image
  37134. * * bufferHeight the height of image
  37135. * @returns the VertexData of the Ground designed from a heightmap
  37136. */
  37137. VertexData.CreateGroundFromHeightMap = function (options) {
  37138. var indices = [];
  37139. var positions = [];
  37140. var normals = [];
  37141. var uvs = [];
  37142. var row, col;
  37143. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37144. // Vertices
  37145. for (row = 0; row <= options.subdivisions; row++) {
  37146. for (col = 0; col <= options.subdivisions; col++) {
  37147. 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));
  37148. // Compute height
  37149. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37150. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37151. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37152. var r = options.buffer[pos] / 255.0;
  37153. var g = options.buffer[pos + 1] / 255.0;
  37154. var b = options.buffer[pos + 2] / 255.0;
  37155. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37156. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37157. // Add vertex
  37158. positions.push(position.x, position.y, position.z);
  37159. normals.push(0, 0, 0);
  37160. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37161. }
  37162. }
  37163. // Indices
  37164. for (row = 0; row < options.subdivisions; row++) {
  37165. for (col = 0; col < options.subdivisions; col++) {
  37166. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37167. indices.push(col + 1 + row * (options.subdivisions + 1));
  37168. indices.push(col + row * (options.subdivisions + 1));
  37169. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37170. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37171. indices.push(col + row * (options.subdivisions + 1));
  37172. }
  37173. }
  37174. // Normals
  37175. VertexData.ComputeNormals(positions, indices, normals);
  37176. // Result
  37177. var vertexData = new VertexData();
  37178. vertexData.indices = indices;
  37179. vertexData.positions = positions;
  37180. vertexData.normals = normals;
  37181. vertexData.uvs = uvs;
  37182. return vertexData;
  37183. };
  37184. /**
  37185. * Creates the VertexData for a Plane
  37186. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37187. * * size sets the width and height of the plane to the value of size, optional default 1
  37188. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37189. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37190. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37191. * * 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)
  37192. * * 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)
  37193. * @returns the VertexData of the box
  37194. */
  37195. VertexData.CreatePlane = function (options) {
  37196. var indices = [];
  37197. var positions = [];
  37198. var normals = [];
  37199. var uvs = [];
  37200. var width = options.width || options.size || 1;
  37201. var height = options.height || options.size || 1;
  37202. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37203. // Vertices
  37204. var halfWidth = width / 2.0;
  37205. var halfHeight = height / 2.0;
  37206. positions.push(-halfWidth, -halfHeight, 0);
  37207. normals.push(0, 0, -1.0);
  37208. uvs.push(0.0, 0.0);
  37209. positions.push(halfWidth, -halfHeight, 0);
  37210. normals.push(0, 0, -1.0);
  37211. uvs.push(1.0, 0.0);
  37212. positions.push(halfWidth, halfHeight, 0);
  37213. normals.push(0, 0, -1.0);
  37214. uvs.push(1.0, 1.0);
  37215. positions.push(-halfWidth, halfHeight, 0);
  37216. normals.push(0, 0, -1.0);
  37217. uvs.push(0.0, 1.0);
  37218. // Indices
  37219. indices.push(0);
  37220. indices.push(1);
  37221. indices.push(2);
  37222. indices.push(0);
  37223. indices.push(2);
  37224. indices.push(3);
  37225. // Sides
  37226. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37227. // Result
  37228. var vertexData = new VertexData();
  37229. vertexData.indices = indices;
  37230. vertexData.positions = positions;
  37231. vertexData.normals = normals;
  37232. vertexData.uvs = uvs;
  37233. return vertexData;
  37234. };
  37235. /**
  37236. * Creates the VertexData of the Disc or regular Polygon
  37237. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37238. * * radius the radius of the disc, optional default 0.5
  37239. * * tessellation the number of polygon sides, optional, default 64
  37240. * * 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
  37241. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37242. * * 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)
  37243. * * 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)
  37244. * @returns the VertexData of the box
  37245. */
  37246. VertexData.CreateDisc = function (options) {
  37247. var positions = new Array();
  37248. var indices = new Array();
  37249. var normals = new Array();
  37250. var uvs = new Array();
  37251. var radius = options.radius || 0.5;
  37252. var tessellation = options.tessellation || 64;
  37253. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37254. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37255. // positions and uvs
  37256. positions.push(0, 0, 0); // disc center first
  37257. uvs.push(0.5, 0.5);
  37258. var theta = Math.PI * 2 * arc;
  37259. var step = theta / tessellation;
  37260. for (var a = 0; a < theta; a += step) {
  37261. var x = Math.cos(a);
  37262. var y = Math.sin(a);
  37263. var u = (x + 1) / 2;
  37264. var v = (1 - y) / 2;
  37265. positions.push(radius * x, radius * y, 0);
  37266. uvs.push(u, v);
  37267. }
  37268. if (arc === 1) {
  37269. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37270. uvs.push(uvs[2], uvs[3]);
  37271. }
  37272. //indices
  37273. var vertexNb = positions.length / 3;
  37274. for (var i = 1; i < vertexNb - 1; i++) {
  37275. indices.push(i + 1, 0, i);
  37276. }
  37277. // result
  37278. VertexData.ComputeNormals(positions, indices, normals);
  37279. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37280. var vertexData = new VertexData();
  37281. vertexData.indices = indices;
  37282. vertexData.positions = positions;
  37283. vertexData.normals = normals;
  37284. vertexData.uvs = uvs;
  37285. return vertexData;
  37286. };
  37287. /**
  37288. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37289. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37290. * @param polygon a mesh built from polygonTriangulation.build()
  37291. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37292. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37293. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37294. * @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)
  37295. * @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)
  37296. * @returns the VertexData of the Polygon
  37297. */
  37298. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37299. var faceUV = fUV || new Array(3);
  37300. var faceColors = fColors;
  37301. var colors = [];
  37302. // default face colors and UV if undefined
  37303. for (var f = 0; f < 3; f++) {
  37304. if (faceUV[f] === undefined) {
  37305. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37306. }
  37307. if (faceColors && faceColors[f] === undefined) {
  37308. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37309. }
  37310. }
  37311. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37312. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37313. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37314. var indices = polygon.getIndices();
  37315. // set face colours and textures
  37316. var idx = 0;
  37317. var face = 0;
  37318. for (var index = 0; index < normals.length; index += 3) {
  37319. //Edge Face no. 1
  37320. if (Math.abs(normals[index + 1]) < 0.001) {
  37321. face = 1;
  37322. }
  37323. //Top Face no. 0
  37324. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37325. face = 0;
  37326. }
  37327. //Bottom Face no. 2
  37328. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37329. face = 2;
  37330. }
  37331. idx = index / 3;
  37332. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37333. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37334. if (faceColors) {
  37335. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37336. }
  37337. }
  37338. // sides
  37339. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37340. // Result
  37341. var vertexData = new VertexData();
  37342. vertexData.indices = indices;
  37343. vertexData.positions = positions;
  37344. vertexData.normals = normals;
  37345. vertexData.uvs = uvs;
  37346. if (faceColors) {
  37347. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37348. vertexData.colors = totalColors;
  37349. }
  37350. return vertexData;
  37351. };
  37352. /**
  37353. * Creates the VertexData of the IcoSphere
  37354. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37355. * * radius the radius of the IcoSphere, optional default 1
  37356. * * radiusX allows stretching in the x direction, optional, default radius
  37357. * * radiusY allows stretching in the y direction, optional, default radius
  37358. * * radiusZ allows stretching in the z direction, optional, default radius
  37359. * * flat when true creates a flat shaded mesh, optional, default true
  37360. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37361. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37362. * * 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)
  37363. * * 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)
  37364. * @returns the VertexData of the IcoSphere
  37365. */
  37366. VertexData.CreateIcoSphere = function (options) {
  37367. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37368. var radius = options.radius || 1;
  37369. var flat = (options.flat === undefined) ? true : options.flat;
  37370. var subdivisions = options.subdivisions || 4;
  37371. var radiusX = options.radiusX || radius;
  37372. var radiusY = options.radiusY || radius;
  37373. var radiusZ = options.radiusZ || radius;
  37374. var t = (1 + Math.sqrt(5)) / 2;
  37375. // 12 vertex x,y,z
  37376. var ico_vertices = [
  37377. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37378. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37379. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37380. ];
  37381. // index of 3 vertex makes a face of icopshere
  37382. var ico_indices = [
  37383. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37384. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37385. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37386. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37387. ];
  37388. // vertex for uv have aliased position, not for UV
  37389. var vertices_unalias_id = [
  37390. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37391. // vertex alias
  37392. 0,
  37393. 2,
  37394. 3,
  37395. 3,
  37396. 3,
  37397. 4,
  37398. 7,
  37399. 8,
  37400. 9,
  37401. 9,
  37402. 10,
  37403. 11 // 23: B + 12
  37404. ];
  37405. // uv as integer step (not pixels !)
  37406. var ico_vertexuv = [
  37407. 5, 1, 3, 1, 6, 4, 0, 0,
  37408. 5, 3, 4, 2, 2, 2, 4, 0,
  37409. 2, 0, 1, 1, 6, 0, 6, 2,
  37410. // vertex alias (for same vertex on different faces)
  37411. 0, 4,
  37412. 3, 3,
  37413. 4, 4,
  37414. 3, 1,
  37415. 4, 2,
  37416. 4, 4,
  37417. 0, 2,
  37418. 1, 1,
  37419. 2, 2,
  37420. 3, 3,
  37421. 1, 3,
  37422. 2, 4 // 23: B + 12
  37423. ];
  37424. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37425. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37426. // First island of uv mapping
  37427. // v = 4h 3+ 2
  37428. // v = 3h 9+ 4
  37429. // v = 2h 9+ 5 B
  37430. // v = 1h 9 1 0
  37431. // v = 0h 3 8 7 A
  37432. // u = 0 1 2 3 4 5 6 *a
  37433. // Second island of uv mapping
  37434. // v = 4h 0+ B+ 4+
  37435. // v = 3h A+ 2+
  37436. // v = 2h 7+ 6 3+
  37437. // v = 1h 8+ 3+
  37438. // v = 0h
  37439. // u = 0 1 2 3 4 5 6 *a
  37440. // Face layout on texture UV mapping
  37441. // ============
  37442. // \ 4 /\ 16 / ======
  37443. // \ / \ / /\ 11 /
  37444. // \/ 7 \/ / \ /
  37445. // ======= / 10 \/
  37446. // /\ 17 /\ =======
  37447. // / \ / \ \ 15 /\
  37448. // / 8 \/ 12 \ \ / \
  37449. // ============ \/ 6 \
  37450. // \ 18 /\ ============
  37451. // \ / \ \ 5 /\ 0 /
  37452. // \/ 13 \ \ / \ /
  37453. // ======= \/ 1 \/
  37454. // =============
  37455. // /\ 19 /\ 2 /\
  37456. // / \ / \ / \
  37457. // / 14 \/ 9 \/ 3 \
  37458. // ===================
  37459. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37460. var ustep = 138 / 1024;
  37461. var vstep = 239 / 1024;
  37462. var uoffset = 60 / 1024;
  37463. var voffset = 26 / 1024;
  37464. // Second island should have margin, not to touch the first island
  37465. // avoid any borderline artefact in pixel rounding
  37466. var island_u_offset = -40 / 1024;
  37467. var island_v_offset = +20 / 1024;
  37468. // face is either island 0 or 1 :
  37469. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37470. var island = [
  37471. 0, 0, 0, 0, 1,
  37472. 0, 0, 1, 1, 0,
  37473. 0, 0, 1, 1, 0,
  37474. 0, 1, 1, 1, 0 // 15 - 19
  37475. ];
  37476. var indices = new Array();
  37477. var positions = new Array();
  37478. var normals = new Array();
  37479. var uvs = new Array();
  37480. var current_indice = 0;
  37481. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37482. var face_vertex_pos = new Array(3);
  37483. var face_vertex_uv = new Array(3);
  37484. var v012;
  37485. for (v012 = 0; v012 < 3; v012++) {
  37486. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37487. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37488. }
  37489. // create all with normals
  37490. for (var face = 0; face < 20; face++) {
  37491. // 3 vertex per face
  37492. for (v012 = 0; v012 < 3; v012++) {
  37493. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37494. var v_id = ico_indices[3 * face + v012];
  37495. // vertex have 3D position (x,y,z)
  37496. 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]);
  37497. // Normalize to get normal, then scale to radius
  37498. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37499. // uv Coordinates from vertex ID
  37500. 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);
  37501. }
  37502. // Subdivide the face (interpolate pos, norm, uv)
  37503. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37504. // - norm is linear interpolation of vertex corner normal
  37505. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37506. // - uv is linear interpolation
  37507. //
  37508. // Topology is as below for sub-divide by 2
  37509. // vertex shown as v0,v1,v2
  37510. // interp index is i1 to progress in range [v0,v1[
  37511. // interp index is i2 to progress in range [v0,v2[
  37512. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37513. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37514. //
  37515. //
  37516. // i2 v2
  37517. // ^ ^
  37518. // / / \
  37519. // / / \
  37520. // / / \
  37521. // / / (0,1) \
  37522. // / #---------\
  37523. // / / \ (0,0)'/ \
  37524. // / / \ / \
  37525. // / / \ / \
  37526. // / / (0,0) \ / (1,0) \
  37527. // / #---------#---------\
  37528. // v0 v1
  37529. //
  37530. // --------------------> i1
  37531. //
  37532. // interp of (i1,i2):
  37533. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37534. // along i1 : lerp(x0,x1, i1/(S-i2))
  37535. //
  37536. // centroid of triangle is needed to get help normal computation
  37537. // (c1,c2) are used for centroid location
  37538. var interp_vertex = function (i1, i2, c1, c2) {
  37539. // vertex is interpolated from
  37540. // - face_vertex_pos[0..2]
  37541. // - face_vertex_uv[0..2]
  37542. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37543. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37544. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37545. pos_interp.normalize();
  37546. var vertex_normal;
  37547. if (flat) {
  37548. // in flat mode, recalculate normal as face centroid normal
  37549. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37550. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37551. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37552. }
  37553. else {
  37554. // in smooth mode, recalculate normal from each single vertex position
  37555. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37556. }
  37557. // Vertex normal need correction due to X,Y,Z radius scaling
  37558. vertex_normal.x /= radiusX;
  37559. vertex_normal.y /= radiusY;
  37560. vertex_normal.z /= radiusZ;
  37561. vertex_normal.normalize();
  37562. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37563. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37564. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37565. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37566. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37567. uvs.push(uv_interp.x, uv_interp.y);
  37568. // push each vertex has member of a face
  37569. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37570. indices.push(current_indice);
  37571. current_indice++;
  37572. };
  37573. for (var i2 = 0; i2 < subdivisions; i2++) {
  37574. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37575. // face : (i1,i2) for /\ :
  37576. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37577. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37578. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37579. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37580. if (i1 + i2 + 1 < subdivisions) {
  37581. // face : (i1,i2)' for \/ :
  37582. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37583. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37584. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37585. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37586. }
  37587. }
  37588. }
  37589. }
  37590. // Sides
  37591. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37592. // Result
  37593. var vertexData = new VertexData();
  37594. vertexData.indices = indices;
  37595. vertexData.positions = positions;
  37596. vertexData.normals = normals;
  37597. vertexData.uvs = uvs;
  37598. return vertexData;
  37599. };
  37600. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37601. /**
  37602. * Creates the VertexData for a Polyhedron
  37603. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37604. * * type provided types are:
  37605. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37606. * * 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)
  37607. * * size the size of the IcoSphere, optional default 1
  37608. * * sizeX allows stretching in the x direction, optional, default size
  37609. * * sizeY allows stretching in the y direction, optional, default size
  37610. * * sizeZ allows stretching in the z direction, optional, default size
  37611. * * 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
  37612. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37613. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37614. * * flat when true creates a flat shaded mesh, optional, default true
  37615. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37616. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37617. * * 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)
  37618. * * 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)
  37619. * @returns the VertexData of the Polyhedron
  37620. */
  37621. VertexData.CreatePolyhedron = function (options) {
  37622. // provided polyhedron types :
  37623. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37624. // 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)
  37625. var polyhedra = [];
  37626. 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]] };
  37627. 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]] };
  37628. polyhedra[2] = {
  37629. 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]],
  37630. 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]]
  37631. };
  37632. polyhedra[3] = {
  37633. 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]],
  37634. 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]]
  37635. };
  37636. polyhedra[4] = {
  37637. 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]],
  37638. 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]]
  37639. };
  37640. 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]] };
  37641. 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]] };
  37642. 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]] };
  37643. 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]] };
  37644. 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]] };
  37645. 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]] };
  37646. 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]] };
  37647. 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]] };
  37648. 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]] };
  37649. polyhedra[14] = {
  37650. 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]],
  37651. 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]]
  37652. };
  37653. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37654. var size = options.size;
  37655. var sizeX = options.sizeX || size || 1;
  37656. var sizeY = options.sizeY || size || 1;
  37657. var sizeZ = options.sizeZ || size || 1;
  37658. var data = options.custom || polyhedra[type];
  37659. var nbfaces = data.face.length;
  37660. var faceUV = options.faceUV || new Array(nbfaces);
  37661. var faceColors = options.faceColors;
  37662. var flat = (options.flat === undefined) ? true : options.flat;
  37663. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37664. var positions = new Array();
  37665. var indices = new Array();
  37666. var normals = new Array();
  37667. var uvs = new Array();
  37668. var colors = new Array();
  37669. var index = 0;
  37670. var faceIdx = 0; // face cursor in the array "indexes"
  37671. var indexes = new Array();
  37672. var i = 0;
  37673. var f = 0;
  37674. var u, v, ang, x, y, tmp;
  37675. // default face colors and UV if undefined
  37676. if (flat) {
  37677. for (f = 0; f < nbfaces; f++) {
  37678. if (faceColors && faceColors[f] === undefined) {
  37679. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37680. }
  37681. if (faceUV && faceUV[f] === undefined) {
  37682. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37683. }
  37684. }
  37685. }
  37686. if (!flat) {
  37687. for (i = 0; i < data.vertex.length; i++) {
  37688. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37689. uvs.push(0, 0);
  37690. }
  37691. for (f = 0; f < nbfaces; f++) {
  37692. for (i = 0; i < data.face[f].length - 2; i++) {
  37693. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37694. }
  37695. }
  37696. }
  37697. else {
  37698. for (f = 0; f < nbfaces; f++) {
  37699. var fl = data.face[f].length; // number of vertices of the current face
  37700. ang = 2 * Math.PI / fl;
  37701. x = 0.5 * Math.tan(ang / 2);
  37702. y = 0.5;
  37703. // positions, uvs, colors
  37704. for (i = 0; i < fl; i++) {
  37705. // positions
  37706. 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);
  37707. indexes.push(index);
  37708. index++;
  37709. // uvs
  37710. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37711. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37712. uvs.push(u, v);
  37713. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37714. y = x * Math.sin(ang) + y * Math.cos(ang);
  37715. x = tmp;
  37716. // colors
  37717. if (faceColors) {
  37718. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37719. }
  37720. }
  37721. // indices from indexes
  37722. for (i = 0; i < fl - 2; i++) {
  37723. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37724. }
  37725. faceIdx += fl;
  37726. }
  37727. }
  37728. VertexData.ComputeNormals(positions, indices, normals);
  37729. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37730. var vertexData = new VertexData();
  37731. vertexData.positions = positions;
  37732. vertexData.indices = indices;
  37733. vertexData.normals = normals;
  37734. vertexData.uvs = uvs;
  37735. if (faceColors && flat) {
  37736. vertexData.colors = colors;
  37737. }
  37738. return vertexData;
  37739. };
  37740. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37741. /**
  37742. * Creates the VertexData for a TorusKnot
  37743. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37744. * * radius the radius of the torus knot, optional, default 2
  37745. * * tube the thickness of the tube, optional, default 0.5
  37746. * * radialSegments the number of sides on each tube segments, optional, default 32
  37747. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37748. * * p the number of windings around the z axis, optional, default 2
  37749. * * q the number of windings around the x axis, optional, default 3
  37750. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37751. * * 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)
  37752. * * 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)
  37753. * @returns the VertexData of the Torus Knot
  37754. */
  37755. VertexData.CreateTorusKnot = function (options) {
  37756. var indices = new Array();
  37757. var positions = new Array();
  37758. var normals = new Array();
  37759. var uvs = new Array();
  37760. var radius = options.radius || 2;
  37761. var tube = options.tube || 0.5;
  37762. var radialSegments = options.radialSegments || 32;
  37763. var tubularSegments = options.tubularSegments || 32;
  37764. var p = options.p || 2;
  37765. var q = options.q || 3;
  37766. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37767. // Helper
  37768. var getPos = function (angle) {
  37769. var cu = Math.cos(angle);
  37770. var su = Math.sin(angle);
  37771. var quOverP = q / p * angle;
  37772. var cs = Math.cos(quOverP);
  37773. var tx = radius * (2 + cs) * 0.5 * cu;
  37774. var ty = radius * (2 + cs) * su * 0.5;
  37775. var tz = radius * Math.sin(quOverP) * 0.5;
  37776. return new BABYLON.Vector3(tx, ty, tz);
  37777. };
  37778. // Vertices
  37779. var i;
  37780. var j;
  37781. for (i = 0; i <= radialSegments; i++) {
  37782. var modI = i % radialSegments;
  37783. var u = modI / radialSegments * 2 * p * Math.PI;
  37784. var p1 = getPos(u);
  37785. var p2 = getPos(u + 0.01);
  37786. var tang = p2.subtract(p1);
  37787. var n = p2.add(p1);
  37788. var bitan = BABYLON.Vector3.Cross(tang, n);
  37789. n = BABYLON.Vector3.Cross(bitan, tang);
  37790. bitan.normalize();
  37791. n.normalize();
  37792. for (j = 0; j < tubularSegments; j++) {
  37793. var modJ = j % tubularSegments;
  37794. var v = modJ / tubularSegments * 2 * Math.PI;
  37795. var cx = -tube * Math.cos(v);
  37796. var cy = tube * Math.sin(v);
  37797. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37798. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37799. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37800. uvs.push(i / radialSegments);
  37801. uvs.push(j / tubularSegments);
  37802. }
  37803. }
  37804. for (i = 0; i < radialSegments; i++) {
  37805. for (j = 0; j < tubularSegments; j++) {
  37806. var jNext = (j + 1) % tubularSegments;
  37807. var a = i * tubularSegments + j;
  37808. var b = (i + 1) * tubularSegments + j;
  37809. var c = (i + 1) * tubularSegments + jNext;
  37810. var d = i * tubularSegments + jNext;
  37811. indices.push(d);
  37812. indices.push(b);
  37813. indices.push(a);
  37814. indices.push(d);
  37815. indices.push(c);
  37816. indices.push(b);
  37817. }
  37818. }
  37819. // Normals
  37820. VertexData.ComputeNormals(positions, indices, normals);
  37821. // Sides
  37822. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37823. // Result
  37824. var vertexData = new VertexData();
  37825. vertexData.indices = indices;
  37826. vertexData.positions = positions;
  37827. vertexData.normals = normals;
  37828. vertexData.uvs = uvs;
  37829. return vertexData;
  37830. };
  37831. // Tools
  37832. /**
  37833. * Compute normals for given positions and indices
  37834. * @param positions an array of vertex positions, [...., x, y, z, ......]
  37835. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  37836. * @param normals an array of vertex normals, [...., x, y, z, ......]
  37837. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  37838. * * facetNormals : optional array of facet normals (vector3)
  37839. * * facetPositions : optional array of facet positions (vector3)
  37840. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  37841. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  37842. * * bInfo : optional bounding info, required for facetPartitioning computation
  37843. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  37844. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  37845. * * useRightHandedSystem: optional boolean to for right handed system computation
  37846. * * depthSort : optional boolean to enable the facet depth sort computation
  37847. * * distanceTo : optional Vector3 to compute the facet depth from this location
  37848. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  37849. */
  37850. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  37851. // temporary scalar variables
  37852. var index = 0; // facet index
  37853. var p1p2x = 0.0; // p1p2 vector x coordinate
  37854. var p1p2y = 0.0; // p1p2 vector y coordinate
  37855. var p1p2z = 0.0; // p1p2 vector z coordinate
  37856. var p3p2x = 0.0; // p3p2 vector x coordinate
  37857. var p3p2y = 0.0; // p3p2 vector y coordinate
  37858. var p3p2z = 0.0; // p3p2 vector z coordinate
  37859. var faceNormalx = 0.0; // facet normal x coordinate
  37860. var faceNormaly = 0.0; // facet normal y coordinate
  37861. var faceNormalz = 0.0; // facet normal z coordinate
  37862. var length = 0.0; // facet normal length before normalization
  37863. var v1x = 0; // vector1 x index in the positions array
  37864. var v1y = 0; // vector1 y index in the positions array
  37865. var v1z = 0; // vector1 z index in the positions array
  37866. var v2x = 0; // vector2 x index in the positions array
  37867. var v2y = 0; // vector2 y index in the positions array
  37868. var v2z = 0; // vector2 z index in the positions array
  37869. var v3x = 0; // vector3 x index in the positions array
  37870. var v3y = 0; // vector3 y index in the positions array
  37871. var v3z = 0; // vector3 z index in the positions array
  37872. var computeFacetNormals = false;
  37873. var computeFacetPositions = false;
  37874. var computeFacetPartitioning = false;
  37875. var computeDepthSort = false;
  37876. var faceNormalSign = 1;
  37877. var ratio = 0;
  37878. var distanceTo = null;
  37879. if (options) {
  37880. computeFacetNormals = (options.facetNormals) ? true : false;
  37881. computeFacetPositions = (options.facetPositions) ? true : false;
  37882. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  37883. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  37884. ratio = options.ratio || 0;
  37885. computeDepthSort = (options.depthSort) ? true : false;
  37886. distanceTo = (options.distanceTo);
  37887. if (computeDepthSort) {
  37888. if (distanceTo === undefined) {
  37889. distanceTo = BABYLON.Vector3.Zero();
  37890. }
  37891. var depthSortedFacets = options.depthSortedFacets;
  37892. }
  37893. }
  37894. // facetPartitioning reinit if needed
  37895. var xSubRatio = 0;
  37896. var ySubRatio = 0;
  37897. var zSubRatio = 0;
  37898. var subSq = 0;
  37899. if (computeFacetPartitioning && options && options.bbSize) {
  37900. var ox = 0; // X partitioning index for facet position
  37901. var oy = 0; // Y partinioning index for facet position
  37902. var oz = 0; // Z partinioning index for facet position
  37903. var b1x = 0; // X partitioning index for facet v1 vertex
  37904. var b1y = 0; // Y partitioning index for facet v1 vertex
  37905. var b1z = 0; // z partitioning index for facet v1 vertex
  37906. var b2x = 0; // X partitioning index for facet v2 vertex
  37907. var b2y = 0; // Y partitioning index for facet v2 vertex
  37908. var b2z = 0; // Z partitioning index for facet v2 vertex
  37909. var b3x = 0; // X partitioning index for facet v3 vertex
  37910. var b3y = 0; // Y partitioning index for facet v3 vertex
  37911. var b3z = 0; // Z partitioning index for facet v3 vertex
  37912. var block_idx_o = 0; // facet barycenter block index
  37913. var block_idx_v1 = 0; // v1 vertex block index
  37914. var block_idx_v2 = 0; // v2 vertex block index
  37915. var block_idx_v3 = 0; // v3 vertex block index
  37916. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  37917. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  37918. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  37919. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  37920. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  37921. subSq = options.subDiv.max * options.subDiv.max;
  37922. options.facetPartitioning.length = 0;
  37923. }
  37924. // reset the normals
  37925. for (index = 0; index < positions.length; index++) {
  37926. normals[index] = 0.0;
  37927. }
  37928. // Loop : 1 indice triplet = 1 facet
  37929. var nbFaces = (indices.length / 3) | 0;
  37930. for (index = 0; index < nbFaces; index++) {
  37931. // get the indexes of the coordinates of each vertex of the facet
  37932. v1x = indices[index * 3] * 3;
  37933. v1y = v1x + 1;
  37934. v1z = v1x + 2;
  37935. v2x = indices[index * 3 + 1] * 3;
  37936. v2y = v2x + 1;
  37937. v2z = v2x + 2;
  37938. v3x = indices[index * 3 + 2] * 3;
  37939. v3y = v3x + 1;
  37940. v3z = v3x + 2;
  37941. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  37942. p1p2y = positions[v1y] - positions[v2y];
  37943. p1p2z = positions[v1z] - positions[v2z];
  37944. p3p2x = positions[v3x] - positions[v2x];
  37945. p3p2y = positions[v3y] - positions[v2y];
  37946. p3p2z = positions[v3z] - positions[v2z];
  37947. // compute the face normal with the cross product
  37948. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  37949. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  37950. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  37951. // normalize this normal and store it in the array facetData
  37952. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  37953. length = (length === 0) ? 1.0 : length;
  37954. faceNormalx /= length;
  37955. faceNormaly /= length;
  37956. faceNormalz /= length;
  37957. if (computeFacetNormals && options) {
  37958. options.facetNormals[index].x = faceNormalx;
  37959. options.facetNormals[index].y = faceNormaly;
  37960. options.facetNormals[index].z = faceNormalz;
  37961. }
  37962. if (computeFacetPositions && options) {
  37963. // compute and the facet barycenter coordinates in the array facetPositions
  37964. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  37965. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  37966. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  37967. }
  37968. if (computeFacetPartitioning && options) {
  37969. // store the facet indexes in arrays in the main facetPartitioning array :
  37970. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  37971. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  37972. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  37973. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  37974. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37975. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37976. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37977. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37978. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37979. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37980. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  37981. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  37982. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  37983. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  37984. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  37985. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  37986. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  37987. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  37988. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  37989. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  37990. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  37991. // push each facet index in each block containing the vertex
  37992. options.facetPartitioning[block_idx_v1].push(index);
  37993. if (block_idx_v2 != block_idx_v1) {
  37994. options.facetPartitioning[block_idx_v2].push(index);
  37995. }
  37996. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  37997. options.facetPartitioning[block_idx_v3].push(index);
  37998. }
  37999. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38000. options.facetPartitioning[block_idx_o].push(index);
  38001. }
  38002. }
  38003. if (computeDepthSort && options && options.facetPositions) {
  38004. var dsf = depthSortedFacets[index];
  38005. dsf.ind = index * 3;
  38006. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38007. }
  38008. // compute the normals anyway
  38009. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38010. normals[v1y] += faceNormaly;
  38011. normals[v1z] += faceNormalz;
  38012. normals[v2x] += faceNormalx;
  38013. normals[v2y] += faceNormaly;
  38014. normals[v2z] += faceNormalz;
  38015. normals[v3x] += faceNormalx;
  38016. normals[v3y] += faceNormaly;
  38017. normals[v3z] += faceNormalz;
  38018. }
  38019. // last normalization of each normal
  38020. for (index = 0; index < normals.length / 3; index++) {
  38021. faceNormalx = normals[index * 3];
  38022. faceNormaly = normals[index * 3 + 1];
  38023. faceNormalz = normals[index * 3 + 2];
  38024. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38025. length = (length === 0) ? 1.0 : length;
  38026. faceNormalx /= length;
  38027. faceNormaly /= length;
  38028. faceNormalz /= length;
  38029. normals[index * 3] = faceNormalx;
  38030. normals[index * 3 + 1] = faceNormaly;
  38031. normals[index * 3 + 2] = faceNormalz;
  38032. }
  38033. };
  38034. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38035. var li = indices.length;
  38036. var ln = normals.length;
  38037. var i;
  38038. var n;
  38039. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38040. switch (sideOrientation) {
  38041. case BABYLON.Mesh.FRONTSIDE:
  38042. // nothing changed
  38043. break;
  38044. case BABYLON.Mesh.BACKSIDE:
  38045. var tmp;
  38046. // indices
  38047. for (i = 0; i < li; i += 3) {
  38048. tmp = indices[i];
  38049. indices[i] = indices[i + 2];
  38050. indices[i + 2] = tmp;
  38051. }
  38052. // normals
  38053. for (n = 0; n < ln; n++) {
  38054. normals[n] = -normals[n];
  38055. }
  38056. break;
  38057. case BABYLON.Mesh.DOUBLESIDE:
  38058. // positions
  38059. var lp = positions.length;
  38060. var l = lp / 3;
  38061. for (var p = 0; p < lp; p++) {
  38062. positions[lp + p] = positions[p];
  38063. }
  38064. // indices
  38065. for (i = 0; i < li; i += 3) {
  38066. indices[i + li] = indices[i + 2] + l;
  38067. indices[i + 1 + li] = indices[i + 1] + l;
  38068. indices[i + 2 + li] = indices[i] + l;
  38069. }
  38070. // normals
  38071. for (n = 0; n < ln; n++) {
  38072. normals[ln + n] = -normals[n];
  38073. }
  38074. // uvs
  38075. var lu = uvs.length;
  38076. var u = 0;
  38077. for (u = 0; u < lu; u++) {
  38078. uvs[u + lu] = uvs[u];
  38079. }
  38080. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38081. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38082. u = 0;
  38083. for (i = 0; i < lu / 2; i++) {
  38084. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38085. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38086. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38087. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38088. u += 2;
  38089. }
  38090. break;
  38091. }
  38092. };
  38093. /**
  38094. * Applies VertexData created from the imported parameters to the geometry
  38095. * @param parsedVertexData the parsed data from an imported file
  38096. * @param geometry the geometry to apply the VertexData to
  38097. */
  38098. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38099. var vertexData = new VertexData();
  38100. // positions
  38101. var positions = parsedVertexData.positions;
  38102. if (positions) {
  38103. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38104. }
  38105. // normals
  38106. var normals = parsedVertexData.normals;
  38107. if (normals) {
  38108. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38109. }
  38110. // tangents
  38111. var tangents = parsedVertexData.tangents;
  38112. if (tangents) {
  38113. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38114. }
  38115. // uvs
  38116. var uvs = parsedVertexData.uvs;
  38117. if (uvs) {
  38118. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38119. }
  38120. // uv2s
  38121. var uv2s = parsedVertexData.uv2s;
  38122. if (uv2s) {
  38123. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38124. }
  38125. // uv3s
  38126. var uv3s = parsedVertexData.uv3s;
  38127. if (uv3s) {
  38128. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38129. }
  38130. // uv4s
  38131. var uv4s = parsedVertexData.uv4s;
  38132. if (uv4s) {
  38133. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38134. }
  38135. // uv5s
  38136. var uv5s = parsedVertexData.uv5s;
  38137. if (uv5s) {
  38138. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38139. }
  38140. // uv6s
  38141. var uv6s = parsedVertexData.uv6s;
  38142. if (uv6s) {
  38143. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38144. }
  38145. // colors
  38146. var colors = parsedVertexData.colors;
  38147. if (colors) {
  38148. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38149. }
  38150. // matricesIndices
  38151. var matricesIndices = parsedVertexData.matricesIndices;
  38152. if (matricesIndices) {
  38153. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38154. }
  38155. // matricesWeights
  38156. var matricesWeights = parsedVertexData.matricesWeights;
  38157. if (matricesWeights) {
  38158. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38159. }
  38160. // indices
  38161. var indices = parsedVertexData.indices;
  38162. if (indices) {
  38163. vertexData.indices = indices;
  38164. }
  38165. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38166. };
  38167. return VertexData;
  38168. }());
  38169. BABYLON.VertexData = VertexData;
  38170. })(BABYLON || (BABYLON = {}));
  38171. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38172. var BABYLON;
  38173. (function (BABYLON) {
  38174. /**
  38175. * Class used to store geometry data (vertex buffers + index buffer)
  38176. */
  38177. var Geometry = /** @class */ (function () {
  38178. /**
  38179. * Creates a new geometry
  38180. * @param id defines the unique ID
  38181. * @param scene defines the hosting scene
  38182. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38183. * @param updatable defines if geometry must be updatable (false by default)
  38184. * @param mesh defines the mesh that will be associated with the geometry
  38185. */
  38186. function Geometry(id, scene, vertexData, updatable, mesh) {
  38187. if (updatable === void 0) { updatable = false; }
  38188. if (mesh === void 0) { mesh = null; }
  38189. /**
  38190. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38191. */
  38192. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38193. this._totalVertices = 0;
  38194. this._isDisposed = false;
  38195. this._indexBufferIsUpdatable = false;
  38196. this.id = id;
  38197. this._engine = scene.getEngine();
  38198. this._meshes = [];
  38199. this._scene = scene;
  38200. //Init vertex buffer cache
  38201. this._vertexBuffers = {};
  38202. this._indices = [];
  38203. this._updatable = updatable;
  38204. // vertexData
  38205. if (vertexData) {
  38206. this.setAllVerticesData(vertexData, updatable);
  38207. }
  38208. else {
  38209. this._totalVertices = 0;
  38210. this._indices = [];
  38211. }
  38212. if (this._engine.getCaps().vertexArrayObject) {
  38213. this._vertexArrayObjects = {};
  38214. }
  38215. // applyToMesh
  38216. if (mesh) {
  38217. if (mesh.getClassName() === "LinesMesh") {
  38218. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38219. this._updateExtend();
  38220. }
  38221. this.applyToMesh(mesh);
  38222. mesh.computeWorldMatrix(true);
  38223. }
  38224. }
  38225. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38226. /**
  38227. * 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
  38228. */
  38229. get: function () {
  38230. return this._boundingBias;
  38231. },
  38232. /**
  38233. * 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
  38234. */
  38235. set: function (value) {
  38236. if (this._boundingBias && this._boundingBias.equals(value)) {
  38237. return;
  38238. }
  38239. this._boundingBias = value.clone();
  38240. this._updateBoundingInfo(true, null);
  38241. },
  38242. enumerable: true,
  38243. configurable: true
  38244. });
  38245. /**
  38246. * Static function used to attach a new empty geometry to a mesh
  38247. * @param mesh defines the mesh to attach the geometry to
  38248. * @returns the new {BABYLON.Geometry}
  38249. */
  38250. Geometry.CreateGeometryForMesh = function (mesh) {
  38251. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38252. geometry.applyToMesh(mesh);
  38253. return geometry;
  38254. };
  38255. Object.defineProperty(Geometry.prototype, "extend", {
  38256. /**
  38257. * Gets the current extend of the geometry
  38258. */
  38259. get: function () {
  38260. return this._extend;
  38261. },
  38262. enumerable: true,
  38263. configurable: true
  38264. });
  38265. /**
  38266. * Gets the hosting scene
  38267. * @returns the hosting {BABYLON.Scene}
  38268. */
  38269. Geometry.prototype.getScene = function () {
  38270. return this._scene;
  38271. };
  38272. /**
  38273. * Gets the hosting engine
  38274. * @returns the hosting {BABYLON.Engine}
  38275. */
  38276. Geometry.prototype.getEngine = function () {
  38277. return this._engine;
  38278. };
  38279. /**
  38280. * Defines if the geometry is ready to use
  38281. * @returns true if the geometry is ready to be used
  38282. */
  38283. Geometry.prototype.isReady = function () {
  38284. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38285. };
  38286. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38287. /**
  38288. * Gets a value indicating that the geometry should not be serialized
  38289. */
  38290. get: function () {
  38291. for (var index = 0; index < this._meshes.length; index++) {
  38292. if (!this._meshes[index].doNotSerialize) {
  38293. return false;
  38294. }
  38295. }
  38296. return true;
  38297. },
  38298. enumerable: true,
  38299. configurable: true
  38300. });
  38301. /** @ignore */
  38302. Geometry.prototype._rebuild = function () {
  38303. if (this._vertexArrayObjects) {
  38304. this._vertexArrayObjects = {};
  38305. }
  38306. // Index buffer
  38307. if (this._meshes.length !== 0 && this._indices) {
  38308. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38309. }
  38310. // Vertex buffers
  38311. for (var key in this._vertexBuffers) {
  38312. var vertexBuffer = this._vertexBuffers[key];
  38313. vertexBuffer._rebuild();
  38314. }
  38315. };
  38316. /**
  38317. * Affects all gemetry data in one call
  38318. * @param vertexData defines the geometry data
  38319. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38320. */
  38321. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38322. vertexData.applyToGeometry(this, updatable);
  38323. this.notifyUpdate();
  38324. };
  38325. /**
  38326. * Set specific vertex data
  38327. * @param kind defines the data kind (Position, normal, etc...)
  38328. * @param data defines the vertex data to use
  38329. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38330. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38331. */
  38332. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38333. if (updatable === void 0) { updatable = false; }
  38334. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38335. this.setVerticesBuffer(buffer);
  38336. };
  38337. /**
  38338. * Removes a specific vertex data
  38339. * @param kind defines the data kind (Position, normal, etc...)
  38340. */
  38341. Geometry.prototype.removeVerticesData = function (kind) {
  38342. if (this._vertexBuffers[kind]) {
  38343. this._vertexBuffers[kind].dispose();
  38344. delete this._vertexBuffers[kind];
  38345. }
  38346. };
  38347. /**
  38348. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38349. * @param buffer defines the vertex buffer to use
  38350. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38351. */
  38352. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38353. if (totalVertices === void 0) { totalVertices = null; }
  38354. var kind = buffer.getKind();
  38355. if (this._vertexBuffers[kind]) {
  38356. this._vertexBuffers[kind].dispose();
  38357. }
  38358. this._vertexBuffers[kind] = buffer;
  38359. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38360. var data = buffer.getData();
  38361. if (totalVertices != null) {
  38362. this._totalVertices = totalVertices;
  38363. }
  38364. else {
  38365. if (data != null) {
  38366. this._totalVertices = data.length / (buffer.byteStride / 4);
  38367. }
  38368. }
  38369. this._updateExtend(data);
  38370. this._resetPointsArrayCache();
  38371. var meshes = this._meshes;
  38372. var numOfMeshes = meshes.length;
  38373. for (var index = 0; index < numOfMeshes; index++) {
  38374. var mesh = meshes[index];
  38375. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38376. mesh._createGlobalSubMesh(false);
  38377. mesh.computeWorldMatrix(true);
  38378. }
  38379. }
  38380. this.notifyUpdate(kind);
  38381. if (this._vertexArrayObjects) {
  38382. this._disposeVertexArrayObjects();
  38383. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38384. }
  38385. };
  38386. /**
  38387. * Update a specific vertex buffer
  38388. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38389. * It will do nothing if the buffer is not updatable
  38390. * @param kind defines the data kind (Position, normal, etc...)
  38391. * @param data defines the data to use
  38392. * @param offset defines the offset in the target buffer where to store the data
  38393. * @param useBytes set to true if the offset is in bytes
  38394. */
  38395. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38396. if (useBytes === void 0) { useBytes = false; }
  38397. var vertexBuffer = this.getVertexBuffer(kind);
  38398. if (!vertexBuffer) {
  38399. return;
  38400. }
  38401. vertexBuffer.updateDirectly(data, offset, useBytes);
  38402. this.notifyUpdate(kind);
  38403. };
  38404. /**
  38405. * Update a specific vertex buffer
  38406. * This function will create a new buffer if the current one is not updatable
  38407. * @param kind defines the data kind (Position, normal, etc...)
  38408. * @param data defines the data to use
  38409. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38410. */
  38411. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38412. if (updateExtends === void 0) { updateExtends = false; }
  38413. var vertexBuffer = this.getVertexBuffer(kind);
  38414. if (!vertexBuffer) {
  38415. return;
  38416. }
  38417. vertexBuffer.update(data);
  38418. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38419. this._updateBoundingInfo(updateExtends, data);
  38420. }
  38421. this.notifyUpdate(kind);
  38422. };
  38423. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38424. if (updateExtends) {
  38425. this._updateExtend(data);
  38426. }
  38427. var meshes = this._meshes;
  38428. var numOfMeshes = meshes.length;
  38429. this._resetPointsArrayCache();
  38430. for (var index = 0; index < numOfMeshes; index++) {
  38431. var mesh = meshes[index];
  38432. if (updateExtends) {
  38433. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38434. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38435. var subMesh = mesh.subMeshes[subIndex];
  38436. subMesh.refreshBoundingInfo();
  38437. }
  38438. }
  38439. }
  38440. };
  38441. /** @ignore */
  38442. Geometry.prototype._bind = function (effect, indexToBind) {
  38443. if (!effect) {
  38444. return;
  38445. }
  38446. if (indexToBind === undefined) {
  38447. indexToBind = this._indexBuffer;
  38448. }
  38449. var vbs = this.getVertexBuffers();
  38450. if (!vbs) {
  38451. return;
  38452. }
  38453. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38454. this._engine.bindBuffers(vbs, indexToBind, effect);
  38455. return;
  38456. }
  38457. // Using VAO
  38458. if (!this._vertexArrayObjects[effect.key]) {
  38459. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38460. }
  38461. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38462. };
  38463. /**
  38464. * Gets total number of vertices
  38465. * @returns the total number of vertices
  38466. */
  38467. Geometry.prototype.getTotalVertices = function () {
  38468. if (!this.isReady()) {
  38469. return 0;
  38470. }
  38471. return this._totalVertices;
  38472. };
  38473. /**
  38474. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38475. * @param kind defines the data kind (Position, normal, etc...)
  38476. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38477. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38478. * @returns a float array containing vertex data
  38479. */
  38480. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38481. var vertexBuffer = this.getVertexBuffer(kind);
  38482. if (!vertexBuffer) {
  38483. return null;
  38484. }
  38485. var data = vertexBuffer.getData();
  38486. if (!data) {
  38487. return null;
  38488. }
  38489. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38490. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38491. var count = this._totalVertices * defaultStride;
  38492. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38493. var copy_1 = new Array(count);
  38494. vertexBuffer.forEach(count, function (value, index) {
  38495. copy_1[index] = value;
  38496. });
  38497. return copy_1;
  38498. }
  38499. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38500. if (data instanceof Array) {
  38501. var offset = vertexBuffer.byteOffset / 4;
  38502. return BABYLON.Tools.Slice(data, offset, offset + count);
  38503. }
  38504. else if (data instanceof ArrayBuffer) {
  38505. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38506. }
  38507. else {
  38508. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38509. }
  38510. }
  38511. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38512. return BABYLON.Tools.Slice(data);
  38513. }
  38514. return data;
  38515. };
  38516. /**
  38517. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38518. * @param kind defines the data kind (Position, normal, etc...)
  38519. * @returns true if the vertex buffer with the specified kind is updatable
  38520. */
  38521. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38522. var vb = this._vertexBuffers[kind];
  38523. if (!vb) {
  38524. return false;
  38525. }
  38526. return vb.isUpdatable();
  38527. };
  38528. /**
  38529. * Gets a specific vertex buffer
  38530. * @param kind defines the data kind (Position, normal, etc...)
  38531. * @returns a {BABYLON.VertexBuffer}
  38532. */
  38533. Geometry.prototype.getVertexBuffer = function (kind) {
  38534. if (!this.isReady()) {
  38535. return null;
  38536. }
  38537. return this._vertexBuffers[kind];
  38538. };
  38539. /**
  38540. * Returns all vertex buffers
  38541. * @return an object holding all vertex buffers indexed by kind
  38542. */
  38543. Geometry.prototype.getVertexBuffers = function () {
  38544. if (!this.isReady()) {
  38545. return null;
  38546. }
  38547. return this._vertexBuffers;
  38548. };
  38549. /**
  38550. * Gets a boolean indicating if specific vertex buffer is present
  38551. * @param kind defines the data kind (Position, normal, etc...)
  38552. * @returns true if data is present
  38553. */
  38554. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38555. if (!this._vertexBuffers) {
  38556. if (this._delayInfo) {
  38557. return this._delayInfo.indexOf(kind) !== -1;
  38558. }
  38559. return false;
  38560. }
  38561. return this._vertexBuffers[kind] !== undefined;
  38562. };
  38563. /**
  38564. * Gets a list of all attached data kinds (Position, normal, etc...)
  38565. * @returns a list of string containing all kinds
  38566. */
  38567. Geometry.prototype.getVerticesDataKinds = function () {
  38568. var result = [];
  38569. var kind;
  38570. if (!this._vertexBuffers && this._delayInfo) {
  38571. for (kind in this._delayInfo) {
  38572. result.push(kind);
  38573. }
  38574. }
  38575. else {
  38576. for (kind in this._vertexBuffers) {
  38577. result.push(kind);
  38578. }
  38579. }
  38580. return result;
  38581. };
  38582. /**
  38583. * Update index buffer
  38584. * @param indices defines the indices to store in the index buffer
  38585. * @param offset defines the offset in the target buffer where to store the data
  38586. */
  38587. Geometry.prototype.updateIndices = function (indices, offset) {
  38588. if (!this._indexBuffer) {
  38589. return;
  38590. }
  38591. if (!this._indexBufferIsUpdatable) {
  38592. this.setIndices(indices, null, true);
  38593. }
  38594. else {
  38595. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38596. }
  38597. };
  38598. /**
  38599. * Creates a new index buffer
  38600. * @param indices defines the indices to store in the index buffer
  38601. * @param totalVertices defines the total number of vertices (could be null)
  38602. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38603. */
  38604. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38605. if (totalVertices === void 0) { totalVertices = null; }
  38606. if (updatable === void 0) { updatable = false; }
  38607. if (this._indexBuffer) {
  38608. this._engine._releaseBuffer(this._indexBuffer);
  38609. }
  38610. this._disposeVertexArrayObjects();
  38611. this._indices = indices;
  38612. this._indexBufferIsUpdatable = updatable;
  38613. if (this._meshes.length !== 0 && this._indices) {
  38614. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38615. }
  38616. if (totalVertices != undefined) { // including null and undefined
  38617. this._totalVertices = totalVertices;
  38618. }
  38619. var meshes = this._meshes;
  38620. var numOfMeshes = meshes.length;
  38621. for (var index = 0; index < numOfMeshes; index++) {
  38622. meshes[index]._createGlobalSubMesh(true);
  38623. }
  38624. this.notifyUpdate();
  38625. };
  38626. /**
  38627. * Return the total number of indices
  38628. * @returns the total number of indices
  38629. */
  38630. Geometry.prototype.getTotalIndices = function () {
  38631. if (!this.isReady()) {
  38632. return 0;
  38633. }
  38634. return this._indices.length;
  38635. };
  38636. /**
  38637. * Gets the index buffer array
  38638. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38639. * @returns the index buffer array
  38640. */
  38641. Geometry.prototype.getIndices = function (copyWhenShared) {
  38642. if (!this.isReady()) {
  38643. return null;
  38644. }
  38645. var orig = this._indices;
  38646. if (!copyWhenShared || this._meshes.length === 1) {
  38647. return orig;
  38648. }
  38649. else {
  38650. var len = orig.length;
  38651. var copy = [];
  38652. for (var i = 0; i < len; i++) {
  38653. copy.push(orig[i]);
  38654. }
  38655. return copy;
  38656. }
  38657. };
  38658. /**
  38659. * Gets the index buffer
  38660. * @return the index buffer
  38661. */
  38662. Geometry.prototype.getIndexBuffer = function () {
  38663. if (!this.isReady()) {
  38664. return null;
  38665. }
  38666. return this._indexBuffer;
  38667. };
  38668. /** @ignore */
  38669. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38670. if (effect === void 0) { effect = null; }
  38671. if (!effect || !this._vertexArrayObjects) {
  38672. return;
  38673. }
  38674. if (this._vertexArrayObjects[effect.key]) {
  38675. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38676. delete this._vertexArrayObjects[effect.key];
  38677. }
  38678. };
  38679. /**
  38680. * Release the associated resources for a specific mesh
  38681. * @param mesh defines the source mesh
  38682. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38683. */
  38684. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38685. var meshes = this._meshes;
  38686. var index = meshes.indexOf(mesh);
  38687. if (index === -1) {
  38688. return;
  38689. }
  38690. meshes.splice(index, 1);
  38691. mesh._geometry = null;
  38692. if (meshes.length === 0 && shouldDispose) {
  38693. this.dispose();
  38694. }
  38695. };
  38696. /**
  38697. * Apply current geometry to a given mesh
  38698. * @param mesh defines the mesh to apply geometry to
  38699. */
  38700. Geometry.prototype.applyToMesh = function (mesh) {
  38701. if (mesh._geometry === this) {
  38702. return;
  38703. }
  38704. var previousGeometry = mesh._geometry;
  38705. if (previousGeometry) {
  38706. previousGeometry.releaseForMesh(mesh);
  38707. }
  38708. var meshes = this._meshes;
  38709. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38710. mesh._geometry = this;
  38711. this._scene.pushGeometry(this);
  38712. meshes.push(mesh);
  38713. if (this.isReady()) {
  38714. this._applyToMesh(mesh);
  38715. }
  38716. else {
  38717. mesh._boundingInfo = this._boundingInfo;
  38718. }
  38719. };
  38720. Geometry.prototype._updateExtend = function (data) {
  38721. if (data === void 0) { data = null; }
  38722. if (!data) {
  38723. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38724. }
  38725. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38726. };
  38727. Geometry.prototype._applyToMesh = function (mesh) {
  38728. var numOfMeshes = this._meshes.length;
  38729. // vertexBuffers
  38730. for (var kind in this._vertexBuffers) {
  38731. if (numOfMeshes === 1) {
  38732. this._vertexBuffers[kind].create();
  38733. }
  38734. var buffer = this._vertexBuffers[kind].getBuffer();
  38735. if (buffer)
  38736. buffer.references = numOfMeshes;
  38737. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38738. if (!this._extend) {
  38739. this._updateExtend();
  38740. }
  38741. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38742. mesh._createGlobalSubMesh(false);
  38743. //bounding info was just created again, world matrix should be applied again.
  38744. mesh._updateBoundingInfo();
  38745. }
  38746. }
  38747. // indexBuffer
  38748. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38749. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38750. }
  38751. if (this._indexBuffer) {
  38752. this._indexBuffer.references = numOfMeshes;
  38753. }
  38754. };
  38755. Geometry.prototype.notifyUpdate = function (kind) {
  38756. if (this.onGeometryUpdated) {
  38757. this.onGeometryUpdated(this, kind);
  38758. }
  38759. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38760. var mesh = _a[_i];
  38761. mesh._markSubMeshesAsAttributesDirty();
  38762. }
  38763. };
  38764. /**
  38765. * Load the geometry if it was flagged as delay loaded
  38766. * @param scene defines the hosting scene
  38767. * @param onLoaded defines a callback called when the geometry is loaded
  38768. */
  38769. Geometry.prototype.load = function (scene, onLoaded) {
  38770. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38771. return;
  38772. }
  38773. if (this.isReady()) {
  38774. if (onLoaded) {
  38775. onLoaded();
  38776. }
  38777. return;
  38778. }
  38779. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38780. this._queueLoad(scene, onLoaded);
  38781. };
  38782. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38783. var _this = this;
  38784. if (!this.delayLoadingFile) {
  38785. return;
  38786. }
  38787. scene._addPendingData(this);
  38788. scene._loadFile(this.delayLoadingFile, function (data) {
  38789. if (!_this._delayLoadingFunction) {
  38790. return;
  38791. }
  38792. _this._delayLoadingFunction(JSON.parse(data), _this);
  38793. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38794. _this._delayInfo = [];
  38795. scene._removePendingData(_this);
  38796. var meshes = _this._meshes;
  38797. var numOfMeshes = meshes.length;
  38798. for (var index = 0; index < numOfMeshes; index++) {
  38799. _this._applyToMesh(meshes[index]);
  38800. }
  38801. if (onLoaded) {
  38802. onLoaded();
  38803. }
  38804. }, undefined, true);
  38805. };
  38806. /**
  38807. * Invert the geometry to move from a right handed system to a left handed one.
  38808. */
  38809. Geometry.prototype.toLeftHanded = function () {
  38810. // Flip faces
  38811. var tIndices = this.getIndices(false);
  38812. if (tIndices != null && tIndices.length > 0) {
  38813. for (var i = 0; i < tIndices.length; i += 3) {
  38814. var tTemp = tIndices[i + 0];
  38815. tIndices[i + 0] = tIndices[i + 2];
  38816. tIndices[i + 2] = tTemp;
  38817. }
  38818. this.setIndices(tIndices);
  38819. }
  38820. // Negate position.z
  38821. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  38822. if (tPositions != null && tPositions.length > 0) {
  38823. for (var i = 0; i < tPositions.length; i += 3) {
  38824. tPositions[i + 2] = -tPositions[i + 2];
  38825. }
  38826. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  38827. }
  38828. // Negate normal.z
  38829. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  38830. if (tNormals != null && tNormals.length > 0) {
  38831. for (var i = 0; i < tNormals.length; i += 3) {
  38832. tNormals[i + 2] = -tNormals[i + 2];
  38833. }
  38834. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  38835. }
  38836. };
  38837. // Cache
  38838. /** @ignore */
  38839. Geometry.prototype._resetPointsArrayCache = function () {
  38840. this._positions = null;
  38841. };
  38842. /** @ignore */
  38843. Geometry.prototype._generatePointsArray = function () {
  38844. if (this._positions)
  38845. return true;
  38846. this._positions = [];
  38847. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38848. if (!data) {
  38849. return false;
  38850. }
  38851. for (var index = 0; index < data.length; index += 3) {
  38852. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  38853. }
  38854. return true;
  38855. };
  38856. /**
  38857. * Gets a value indicating if the geometry is disposed
  38858. * @returns true if the geometry was disposed
  38859. */
  38860. Geometry.prototype.isDisposed = function () {
  38861. return this._isDisposed;
  38862. };
  38863. Geometry.prototype._disposeVertexArrayObjects = function () {
  38864. if (this._vertexArrayObjects) {
  38865. for (var kind in this._vertexArrayObjects) {
  38866. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  38867. }
  38868. this._vertexArrayObjects = {};
  38869. }
  38870. };
  38871. /**
  38872. * Free all associated resources
  38873. */
  38874. Geometry.prototype.dispose = function () {
  38875. var meshes = this._meshes;
  38876. var numOfMeshes = meshes.length;
  38877. var index;
  38878. for (index = 0; index < numOfMeshes; index++) {
  38879. this.releaseForMesh(meshes[index]);
  38880. }
  38881. this._meshes = [];
  38882. this._disposeVertexArrayObjects();
  38883. for (var kind in this._vertexBuffers) {
  38884. this._vertexBuffers[kind].dispose();
  38885. }
  38886. this._vertexBuffers = {};
  38887. this._totalVertices = 0;
  38888. if (this._indexBuffer) {
  38889. this._engine._releaseBuffer(this._indexBuffer);
  38890. }
  38891. this._indexBuffer = null;
  38892. this._indices = [];
  38893. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38894. this.delayLoadingFile = null;
  38895. this._delayLoadingFunction = null;
  38896. this._delayInfo = [];
  38897. this._boundingInfo = null;
  38898. this._scene.removeGeometry(this);
  38899. this._isDisposed = true;
  38900. };
  38901. /**
  38902. * Clone the current geometry into a new geometry
  38903. * @param id defines the unique ID of the new geometry
  38904. * @returns a new geometry object
  38905. */
  38906. Geometry.prototype.copy = function (id) {
  38907. var vertexData = new BABYLON.VertexData();
  38908. vertexData.indices = [];
  38909. var indices = this.getIndices();
  38910. if (indices) {
  38911. for (var index = 0; index < indices.length; index++) {
  38912. vertexData.indices.push(indices[index]);
  38913. }
  38914. }
  38915. var updatable = false;
  38916. var stopChecking = false;
  38917. var kind;
  38918. for (kind in this._vertexBuffers) {
  38919. // using slice() to make a copy of the array and not just reference it
  38920. var data = this.getVerticesData(kind);
  38921. if (data instanceof Float32Array) {
  38922. vertexData.set(new Float32Array(data), kind);
  38923. }
  38924. else {
  38925. vertexData.set(data.slice(0), kind);
  38926. }
  38927. if (!stopChecking) {
  38928. var vb = this.getVertexBuffer(kind);
  38929. if (vb) {
  38930. updatable = vb.isUpdatable();
  38931. stopChecking = !updatable;
  38932. }
  38933. }
  38934. }
  38935. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  38936. geometry.delayLoadState = this.delayLoadState;
  38937. geometry.delayLoadingFile = this.delayLoadingFile;
  38938. geometry._delayLoadingFunction = this._delayLoadingFunction;
  38939. for (kind in this._delayInfo) {
  38940. geometry._delayInfo = geometry._delayInfo || [];
  38941. geometry._delayInfo.push(kind);
  38942. }
  38943. // Bounding info
  38944. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38945. return geometry;
  38946. };
  38947. /**
  38948. * Serialize the current geometry info (and not the vertices data) into a JSON object
  38949. * @return a JSON representation of the current geometry data (without the vertices data)
  38950. */
  38951. Geometry.prototype.serialize = function () {
  38952. var serializationObject = {};
  38953. serializationObject.id = this.id;
  38954. serializationObject.updatable = this._updatable;
  38955. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  38956. serializationObject.tags = BABYLON.Tags.GetTags(this);
  38957. }
  38958. return serializationObject;
  38959. };
  38960. Geometry.prototype.toNumberArray = function (origin) {
  38961. if (Array.isArray(origin)) {
  38962. return origin;
  38963. }
  38964. else {
  38965. return Array.prototype.slice.call(origin);
  38966. }
  38967. };
  38968. /**
  38969. * Serialize all vertices data into a JSON oject
  38970. * @returns a JSON representation of the current geometry data
  38971. */
  38972. Geometry.prototype.serializeVerticeData = function () {
  38973. var serializationObject = this.serialize();
  38974. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38975. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  38976. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  38977. serializationObject.positions._updatable = true;
  38978. }
  38979. }
  38980. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38981. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  38982. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  38983. serializationObject.normals._updatable = true;
  38984. }
  38985. }
  38986. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38987. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  38988. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  38989. serializationObject.tangets._updatable = true;
  38990. }
  38991. }
  38992. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38993. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  38994. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  38995. serializationObject.uvs._updatable = true;
  38996. }
  38997. }
  38998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38999. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39000. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39001. serializationObject.uv2s._updatable = true;
  39002. }
  39003. }
  39004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39005. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39006. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39007. serializationObject.uv3s._updatable = true;
  39008. }
  39009. }
  39010. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39011. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39012. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39013. serializationObject.uv4s._updatable = true;
  39014. }
  39015. }
  39016. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39017. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39018. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39019. serializationObject.uv5s._updatable = true;
  39020. }
  39021. }
  39022. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39023. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39024. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39025. serializationObject.uv6s._updatable = true;
  39026. }
  39027. }
  39028. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39029. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39030. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39031. serializationObject.colors._updatable = true;
  39032. }
  39033. }
  39034. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39035. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39036. serializationObject.matricesIndices._isExpanded = true;
  39037. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39038. serializationObject.matricesIndices._updatable = true;
  39039. }
  39040. }
  39041. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39042. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39043. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39044. serializationObject.matricesWeights._updatable = true;
  39045. }
  39046. }
  39047. serializationObject.indices = this.toNumberArray(this.getIndices());
  39048. return serializationObject;
  39049. };
  39050. // Statics
  39051. /**
  39052. * Extracts a clone of a mesh geometry
  39053. * @param mesh defines the source mesh
  39054. * @param id defines the unique ID of the new geometry object
  39055. * @returns the new geometry object
  39056. */
  39057. Geometry.ExtractFromMesh = function (mesh, id) {
  39058. var geometry = mesh._geometry;
  39059. if (!geometry) {
  39060. return null;
  39061. }
  39062. return geometry.copy(id);
  39063. };
  39064. /**
  39065. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39066. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39067. * Be aware Math.random() could cause collisions, but:
  39068. * "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"
  39069. * @returns a string containing a new GUID
  39070. */
  39071. Geometry.RandomId = function () {
  39072. return BABYLON.Tools.RandomId();
  39073. };
  39074. /** @ignore */
  39075. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39076. var scene = mesh.getScene();
  39077. // Geometry
  39078. var geometryId = parsedGeometry.geometryId;
  39079. if (geometryId) {
  39080. var geometry = scene.getGeometryByID(geometryId);
  39081. if (geometry) {
  39082. geometry.applyToMesh(mesh);
  39083. }
  39084. }
  39085. else if (parsedGeometry instanceof ArrayBuffer) {
  39086. var binaryInfo = mesh._binaryInfo;
  39087. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39088. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39089. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39090. }
  39091. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39092. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39093. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39094. }
  39095. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39096. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39097. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39098. }
  39099. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39100. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39101. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39102. }
  39103. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39104. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39105. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39106. }
  39107. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39108. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39109. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39110. }
  39111. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39112. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39113. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39114. }
  39115. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39116. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39117. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39118. }
  39119. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39120. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39121. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39122. }
  39123. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39124. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39125. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39126. }
  39127. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39128. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39129. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39130. }
  39131. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39132. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39133. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39134. }
  39135. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39136. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39137. mesh.setIndices(indicesData, null);
  39138. }
  39139. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39140. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39141. mesh.subMeshes = [];
  39142. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39143. var materialIndex = subMeshesData[(i * 5) + 0];
  39144. var verticesStart = subMeshesData[(i * 5) + 1];
  39145. var verticesCount = subMeshesData[(i * 5) + 2];
  39146. var indexStart = subMeshesData[(i * 5) + 3];
  39147. var indexCount = subMeshesData[(i * 5) + 4];
  39148. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39149. }
  39150. }
  39151. }
  39152. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39153. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39154. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39155. if (parsedGeometry.tangents) {
  39156. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39157. }
  39158. if (parsedGeometry.uvs) {
  39159. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39160. }
  39161. if (parsedGeometry.uvs2) {
  39162. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39163. }
  39164. if (parsedGeometry.uvs3) {
  39165. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39166. }
  39167. if (parsedGeometry.uvs4) {
  39168. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39169. }
  39170. if (parsedGeometry.uvs5) {
  39171. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39172. }
  39173. if (parsedGeometry.uvs6) {
  39174. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39175. }
  39176. if (parsedGeometry.colors) {
  39177. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39178. }
  39179. if (parsedGeometry.matricesIndices) {
  39180. if (!parsedGeometry.matricesIndices._isExpanded) {
  39181. var floatIndices = [];
  39182. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39183. var matricesIndex = parsedGeometry.matricesIndices[i];
  39184. floatIndices.push(matricesIndex & 0x000000FF);
  39185. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39186. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39187. floatIndices.push(matricesIndex >> 24);
  39188. }
  39189. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39190. }
  39191. else {
  39192. delete parsedGeometry.matricesIndices._isExpanded;
  39193. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39194. }
  39195. }
  39196. if (parsedGeometry.matricesIndicesExtra) {
  39197. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39198. var floatIndices = [];
  39199. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39200. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39201. floatIndices.push(matricesIndex & 0x000000FF);
  39202. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39203. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39204. floatIndices.push(matricesIndex >> 24);
  39205. }
  39206. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39207. }
  39208. else {
  39209. delete parsedGeometry.matricesIndices._isExpanded;
  39210. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39211. }
  39212. }
  39213. if (parsedGeometry.matricesWeights) {
  39214. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39215. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39216. }
  39217. if (parsedGeometry.matricesWeightsExtra) {
  39218. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39219. }
  39220. mesh.setIndices(parsedGeometry.indices, null);
  39221. }
  39222. // SubMeshes
  39223. if (parsedGeometry.subMeshes) {
  39224. mesh.subMeshes = [];
  39225. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39226. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39227. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39228. }
  39229. }
  39230. // Flat shading
  39231. if (mesh._shouldGenerateFlatShading) {
  39232. mesh.convertToFlatShadedMesh();
  39233. delete mesh._shouldGenerateFlatShading;
  39234. }
  39235. // Update
  39236. mesh.computeWorldMatrix(true);
  39237. // Octree
  39238. var sceneOctree = scene.selectionOctree;
  39239. if (sceneOctree !== undefined && sceneOctree !== null) {
  39240. sceneOctree.addMesh(mesh);
  39241. }
  39242. };
  39243. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39244. var epsilon = 1e-3;
  39245. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39246. return;
  39247. }
  39248. var noInfluenceBoneIndex = 0.0;
  39249. if (parsedGeometry.skeletonId > -1) {
  39250. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39251. if (!skeleton) {
  39252. return;
  39253. }
  39254. noInfluenceBoneIndex = skeleton.bones.length;
  39255. }
  39256. else {
  39257. return;
  39258. }
  39259. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39260. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39261. var matricesWeights = parsedGeometry.matricesWeights;
  39262. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39263. var influencers = parsedGeometry.numBoneInfluencer;
  39264. var size = matricesWeights.length;
  39265. for (var i = 0; i < size; i += 4) {
  39266. var weight = 0.0;
  39267. var firstZeroWeight = -1;
  39268. for (var j = 0; j < 4; j++) {
  39269. var w = matricesWeights[i + j];
  39270. weight += w;
  39271. if (w < epsilon && firstZeroWeight < 0) {
  39272. firstZeroWeight = j;
  39273. }
  39274. }
  39275. if (matricesWeightsExtra) {
  39276. for (var j = 0; j < 4; j++) {
  39277. var w = matricesWeightsExtra[i + j];
  39278. weight += w;
  39279. if (w < epsilon && firstZeroWeight < 0) {
  39280. firstZeroWeight = j + 4;
  39281. }
  39282. }
  39283. }
  39284. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39285. firstZeroWeight = influencers - 1;
  39286. }
  39287. if (weight > epsilon) {
  39288. var mweight = 1.0 / weight;
  39289. for (var j = 0; j < 4; j++) {
  39290. matricesWeights[i + j] *= mweight;
  39291. }
  39292. if (matricesWeightsExtra) {
  39293. for (var j = 0; j < 4; j++) {
  39294. matricesWeightsExtra[i + j] *= mweight;
  39295. }
  39296. }
  39297. }
  39298. else {
  39299. if (firstZeroWeight >= 4) {
  39300. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39301. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39302. }
  39303. else {
  39304. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39305. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39306. }
  39307. }
  39308. }
  39309. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39310. if (parsedGeometry.matricesWeightsExtra) {
  39311. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39312. }
  39313. };
  39314. /**
  39315. * Create a new geometry from persisted data (Using .babylon file format)
  39316. * @param parsedVertexData defines the persisted data
  39317. * @param scene defines the hosting scene
  39318. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39319. * @returns the new geometry object
  39320. */
  39321. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39322. if (scene.getGeometryByID(parsedVertexData.id)) {
  39323. return null; // null since geometry could be something else than a box...
  39324. }
  39325. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39326. if (BABYLON.Tags) {
  39327. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39328. }
  39329. if (parsedVertexData.delayLoadingFile) {
  39330. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39331. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39332. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39333. geometry._delayInfo = [];
  39334. if (parsedVertexData.hasUVs) {
  39335. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39336. }
  39337. if (parsedVertexData.hasUVs2) {
  39338. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39339. }
  39340. if (parsedVertexData.hasUVs3) {
  39341. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39342. }
  39343. if (parsedVertexData.hasUVs4) {
  39344. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39345. }
  39346. if (parsedVertexData.hasUVs5) {
  39347. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39348. }
  39349. if (parsedVertexData.hasUVs6) {
  39350. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39351. }
  39352. if (parsedVertexData.hasColors) {
  39353. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39354. }
  39355. if (parsedVertexData.hasMatricesIndices) {
  39356. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39357. }
  39358. if (parsedVertexData.hasMatricesWeights) {
  39359. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39360. }
  39361. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39362. }
  39363. else {
  39364. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39365. }
  39366. scene.pushGeometry(geometry, true);
  39367. return geometry;
  39368. };
  39369. return Geometry;
  39370. }());
  39371. BABYLON.Geometry = Geometry;
  39372. // Primitives
  39373. /// Abstract class
  39374. /**
  39375. * Abstract class used to provide common services for all typed geometries
  39376. */
  39377. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39378. __extends(_PrimitiveGeometry, _super);
  39379. /**
  39380. * Creates a new typed geometry
  39381. * @param id defines the unique ID of the geometry
  39382. * @param scene defines the hosting scene
  39383. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39384. * @param mesh defines the hosting mesh (can be null)
  39385. */
  39386. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39387. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39388. if (mesh === void 0) { mesh = null; }
  39389. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39390. _this._canBeRegenerated = _canBeRegenerated;
  39391. _this._beingRegenerated = true;
  39392. _this.regenerate();
  39393. _this._beingRegenerated = false;
  39394. return _this;
  39395. }
  39396. /**
  39397. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39398. * @returns true if the geometry can be regenerated
  39399. */
  39400. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39401. return this._canBeRegenerated;
  39402. };
  39403. /**
  39404. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39405. */
  39406. _PrimitiveGeometry.prototype.regenerate = function () {
  39407. if (!this._canBeRegenerated) {
  39408. return;
  39409. }
  39410. this._beingRegenerated = true;
  39411. this.setAllVerticesData(this._regenerateVertexData(), false);
  39412. this._beingRegenerated = false;
  39413. };
  39414. /**
  39415. * Clone the geometry
  39416. * @param id defines the unique ID of the new geometry
  39417. * @returns the new geometry
  39418. */
  39419. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39420. return _super.prototype.copy.call(this, id);
  39421. };
  39422. // overrides
  39423. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39424. if (!this._beingRegenerated) {
  39425. return;
  39426. }
  39427. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39428. };
  39429. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39430. if (!this._beingRegenerated) {
  39431. return;
  39432. }
  39433. _super.prototype.setVerticesData.call(this, kind, data, false);
  39434. };
  39435. // to override
  39436. /** @ignore */
  39437. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39438. throw new Error("Abstract method");
  39439. };
  39440. _PrimitiveGeometry.prototype.copy = function (id) {
  39441. throw new Error("Must be overriden in sub-classes.");
  39442. };
  39443. _PrimitiveGeometry.prototype.serialize = function () {
  39444. var serializationObject = _super.prototype.serialize.call(this);
  39445. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39446. return serializationObject;
  39447. };
  39448. return _PrimitiveGeometry;
  39449. }(Geometry));
  39450. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39451. /**
  39452. * Creates a ribbon geometry
  39453. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39454. */
  39455. var RibbonGeometry = /** @class */ (function (_super) {
  39456. __extends(RibbonGeometry, _super);
  39457. /**
  39458. * Creates a ribbon geometry
  39459. * @param id defines the unique ID of the geometry
  39460. * @param scene defines the hosting scene
  39461. * @param pathArray defines the array of paths to use
  39462. * @param closeArray defines if the last path and the first path must be joined
  39463. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39464. * @param offset defines the offset between points
  39465. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39466. * @param mesh defines the hosting mesh (can be null)
  39467. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39468. */
  39469. function RibbonGeometry(id, scene,
  39470. /**
  39471. * Defines the array of paths to use
  39472. */
  39473. pathArray,
  39474. /**
  39475. * Defines if the last and first points of each path in your pathArray must be joined
  39476. */
  39477. closeArray,
  39478. /**
  39479. * Defines if the last and first points of each path in your pathArray must be joined
  39480. */
  39481. closePath,
  39482. /**
  39483. * Defines the offset between points
  39484. */
  39485. offset, canBeRegenerated, mesh,
  39486. /**
  39487. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39488. */
  39489. side) {
  39490. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39491. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39492. _this.pathArray = pathArray;
  39493. _this.closeArray = closeArray;
  39494. _this.closePath = closePath;
  39495. _this.offset = offset;
  39496. _this.side = side;
  39497. return _this;
  39498. }
  39499. /** @ignore */
  39500. RibbonGeometry.prototype._regenerateVertexData = function () {
  39501. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39502. };
  39503. RibbonGeometry.prototype.copy = function (id) {
  39504. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39505. };
  39506. return RibbonGeometry;
  39507. }(_PrimitiveGeometry));
  39508. BABYLON.RibbonGeometry = RibbonGeometry;
  39509. /**
  39510. * Creates a box geometry
  39511. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39512. */
  39513. var BoxGeometry = /** @class */ (function (_super) {
  39514. __extends(BoxGeometry, _super);
  39515. /**
  39516. * Creates a box geometry
  39517. * @param id defines the unique ID of the geometry
  39518. * @param scene defines the hosting scene
  39519. * @param size defines the zise of the box (width, height and depth are the same)
  39520. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39521. * @param mesh defines the hosting mesh (can be null)
  39522. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39523. */
  39524. function BoxGeometry(id, scene,
  39525. /**
  39526. * Defines the zise of the box (width, height and depth are the same)
  39527. */
  39528. size, canBeRegenerated, mesh,
  39529. /**
  39530. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39531. */
  39532. side) {
  39533. if (mesh === void 0) { mesh = null; }
  39534. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39535. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39536. _this.size = size;
  39537. _this.side = side;
  39538. return _this;
  39539. }
  39540. BoxGeometry.prototype._regenerateVertexData = function () {
  39541. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39542. };
  39543. BoxGeometry.prototype.copy = function (id) {
  39544. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39545. };
  39546. BoxGeometry.prototype.serialize = function () {
  39547. var serializationObject = _super.prototype.serialize.call(this);
  39548. serializationObject.size = this.size;
  39549. return serializationObject;
  39550. };
  39551. BoxGeometry.Parse = function (parsedBox, scene) {
  39552. if (scene.getGeometryByID(parsedBox.id)) {
  39553. return null; // null since geometry could be something else than a box...
  39554. }
  39555. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39556. if (BABYLON.Tags) {
  39557. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39558. }
  39559. scene.pushGeometry(box, true);
  39560. return box;
  39561. };
  39562. return BoxGeometry;
  39563. }(_PrimitiveGeometry));
  39564. BABYLON.BoxGeometry = BoxGeometry;
  39565. /**
  39566. * Creates a sphere geometry
  39567. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39568. */
  39569. var SphereGeometry = /** @class */ (function (_super) {
  39570. __extends(SphereGeometry, _super);
  39571. /**
  39572. * Create a new sphere geometry
  39573. * @param id defines the unique ID of the geometry
  39574. * @param scene defines the hosting scene
  39575. * @param segments defines the number of segments to use to create the sphere
  39576. * @param diameter defines the diameter of the sphere
  39577. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39578. * @param mesh defines the hosting mesh (can be null)
  39579. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39580. */
  39581. function SphereGeometry(id, scene,
  39582. /**
  39583. * Defines the number of segments to use to create the sphere
  39584. */
  39585. segments,
  39586. /**
  39587. * Defines the diameter of the sphere
  39588. */
  39589. diameter, canBeRegenerated, mesh,
  39590. /**
  39591. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39592. */
  39593. side) {
  39594. if (mesh === void 0) { mesh = null; }
  39595. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39596. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39597. _this.segments = segments;
  39598. _this.diameter = diameter;
  39599. _this.side = side;
  39600. return _this;
  39601. }
  39602. SphereGeometry.prototype._regenerateVertexData = function () {
  39603. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39604. };
  39605. SphereGeometry.prototype.copy = function (id) {
  39606. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39607. };
  39608. SphereGeometry.prototype.serialize = function () {
  39609. var serializationObject = _super.prototype.serialize.call(this);
  39610. serializationObject.segments = this.segments;
  39611. serializationObject.diameter = this.diameter;
  39612. return serializationObject;
  39613. };
  39614. SphereGeometry.Parse = function (parsedSphere, scene) {
  39615. if (scene.getGeometryByID(parsedSphere.id)) {
  39616. return null; // null since geometry could be something else than a sphere...
  39617. }
  39618. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39619. if (BABYLON.Tags) {
  39620. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39621. }
  39622. scene.pushGeometry(sphere, true);
  39623. return sphere;
  39624. };
  39625. return SphereGeometry;
  39626. }(_PrimitiveGeometry));
  39627. BABYLON.SphereGeometry = SphereGeometry;
  39628. /**
  39629. * Creates a disc geometry
  39630. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39631. */
  39632. var DiscGeometry = /** @class */ (function (_super) {
  39633. __extends(DiscGeometry, _super);
  39634. /**
  39635. * Creates a new disc geometry
  39636. * @param id defines the unique ID of the geometry
  39637. * @param scene defines the hosting scene
  39638. * @param radius defines the radius of the disc
  39639. * @param tessellation defines the tesselation factor to apply to the disc
  39640. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39641. * @param mesh defines the hosting mesh (can be null)
  39642. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39643. */
  39644. function DiscGeometry(id, scene,
  39645. /**
  39646. * Defines the radius of the disc
  39647. */
  39648. radius,
  39649. /**
  39650. * Defines the tesselation factor to apply to the disc
  39651. */
  39652. tessellation, canBeRegenerated, mesh,
  39653. /**
  39654. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39655. */
  39656. side) {
  39657. if (mesh === void 0) { mesh = null; }
  39658. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39659. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39660. _this.radius = radius;
  39661. _this.tessellation = tessellation;
  39662. _this.side = side;
  39663. return _this;
  39664. }
  39665. DiscGeometry.prototype._regenerateVertexData = function () {
  39666. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39667. };
  39668. DiscGeometry.prototype.copy = function (id) {
  39669. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39670. };
  39671. return DiscGeometry;
  39672. }(_PrimitiveGeometry));
  39673. BABYLON.DiscGeometry = DiscGeometry;
  39674. /**
  39675. * Creates a new cylinder geometry
  39676. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39677. */
  39678. var CylinderGeometry = /** @class */ (function (_super) {
  39679. __extends(CylinderGeometry, _super);
  39680. /**
  39681. * Creates a new cylinder geometry
  39682. * @param id defines the unique ID of the geometry
  39683. * @param scene defines the hosting scene
  39684. * @param height defines the height of the cylinder
  39685. * @param diameterTop defines the diameter of the cylinder's top cap
  39686. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39687. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39688. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39689. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39690. * @param mesh defines the hosting mesh (can be null)
  39691. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39692. */
  39693. function CylinderGeometry(id, scene,
  39694. /**
  39695. * Defines the height of the cylinder
  39696. */
  39697. height,
  39698. /**
  39699. * Defines the diameter of the cylinder's top cap
  39700. */
  39701. diameterTop,
  39702. /**
  39703. * Defines the diameter of the cylinder's bottom cap
  39704. */
  39705. diameterBottom,
  39706. /**
  39707. * Defines the tessellation factor to apply to the cylinder
  39708. */
  39709. tessellation,
  39710. /**
  39711. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39712. */
  39713. subdivisions, canBeRegenerated, mesh,
  39714. /**
  39715. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39716. */
  39717. side) {
  39718. if (subdivisions === void 0) { subdivisions = 1; }
  39719. if (mesh === void 0) { mesh = null; }
  39720. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39721. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39722. _this.height = height;
  39723. _this.diameterTop = diameterTop;
  39724. _this.diameterBottom = diameterBottom;
  39725. _this.tessellation = tessellation;
  39726. _this.subdivisions = subdivisions;
  39727. _this.side = side;
  39728. return _this;
  39729. }
  39730. CylinderGeometry.prototype._regenerateVertexData = function () {
  39731. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39732. };
  39733. CylinderGeometry.prototype.copy = function (id) {
  39734. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39735. };
  39736. CylinderGeometry.prototype.serialize = function () {
  39737. var serializationObject = _super.prototype.serialize.call(this);
  39738. serializationObject.height = this.height;
  39739. serializationObject.diameterTop = this.diameterTop;
  39740. serializationObject.diameterBottom = this.diameterBottom;
  39741. serializationObject.tessellation = this.tessellation;
  39742. return serializationObject;
  39743. };
  39744. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39745. if (scene.getGeometryByID(parsedCylinder.id)) {
  39746. return null; // null since geometry could be something else than a cylinder...
  39747. }
  39748. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39749. if (BABYLON.Tags) {
  39750. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39751. }
  39752. scene.pushGeometry(cylinder, true);
  39753. return cylinder;
  39754. };
  39755. return CylinderGeometry;
  39756. }(_PrimitiveGeometry));
  39757. BABYLON.CylinderGeometry = CylinderGeometry;
  39758. /**
  39759. * Creates a new torus geometry
  39760. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39761. */
  39762. var TorusGeometry = /** @class */ (function (_super) {
  39763. __extends(TorusGeometry, _super);
  39764. /**
  39765. * Creates a new torus geometry
  39766. * @param id defines the unique ID of the geometry
  39767. * @param scene defines the hosting scene
  39768. * @param diameter defines the diameter of the torus
  39769. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39770. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39771. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39772. * @param mesh defines the hosting mesh (can be null)
  39773. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39774. */
  39775. function TorusGeometry(id, scene,
  39776. /**
  39777. * Defines the diameter of the torus
  39778. */
  39779. diameter,
  39780. /**
  39781. * Defines the thickness of the torus (ie. internal diameter)
  39782. */
  39783. thickness,
  39784. /**
  39785. * Defines the tesselation factor to apply to the torus
  39786. */
  39787. tessellation, canBeRegenerated, mesh,
  39788. /**
  39789. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39790. */
  39791. side) {
  39792. if (mesh === void 0) { mesh = null; }
  39793. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39794. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39795. _this.diameter = diameter;
  39796. _this.thickness = thickness;
  39797. _this.tessellation = tessellation;
  39798. _this.side = side;
  39799. return _this;
  39800. }
  39801. TorusGeometry.prototype._regenerateVertexData = function () {
  39802. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39803. };
  39804. TorusGeometry.prototype.copy = function (id) {
  39805. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39806. };
  39807. TorusGeometry.prototype.serialize = function () {
  39808. var serializationObject = _super.prototype.serialize.call(this);
  39809. serializationObject.diameter = this.diameter;
  39810. serializationObject.thickness = this.thickness;
  39811. serializationObject.tessellation = this.tessellation;
  39812. return serializationObject;
  39813. };
  39814. TorusGeometry.Parse = function (parsedTorus, scene) {
  39815. if (scene.getGeometryByID(parsedTorus.id)) {
  39816. return null; // null since geometry could be something else than a torus...
  39817. }
  39818. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  39819. if (BABYLON.Tags) {
  39820. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  39821. }
  39822. scene.pushGeometry(torus, true);
  39823. return torus;
  39824. };
  39825. return TorusGeometry;
  39826. }(_PrimitiveGeometry));
  39827. BABYLON.TorusGeometry = TorusGeometry;
  39828. /**
  39829. * Creates a new ground geometry
  39830. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  39831. */
  39832. var GroundGeometry = /** @class */ (function (_super) {
  39833. __extends(GroundGeometry, _super);
  39834. /**
  39835. * Creates a new ground geometry
  39836. * @param id defines the unique ID of the geometry
  39837. * @param scene defines the hosting scene
  39838. * @param width defines the width of the ground
  39839. * @param height defines the height of the ground
  39840. * @param subdivisions defines the subdivisions to apply to the ground
  39841. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39842. * @param mesh defines the hosting mesh (can be null)
  39843. */
  39844. function GroundGeometry(id, scene,
  39845. /**
  39846. * Defines the width of the ground
  39847. */
  39848. width,
  39849. /**
  39850. * Defines the height of the ground
  39851. */
  39852. height,
  39853. /**
  39854. * Defines the subdivisions to apply to the ground
  39855. */
  39856. subdivisions, canBeRegenerated, mesh) {
  39857. if (mesh === void 0) { mesh = null; }
  39858. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39859. _this.width = width;
  39860. _this.height = height;
  39861. _this.subdivisions = subdivisions;
  39862. return _this;
  39863. }
  39864. GroundGeometry.prototype._regenerateVertexData = function () {
  39865. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  39866. };
  39867. GroundGeometry.prototype.copy = function (id) {
  39868. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  39869. };
  39870. GroundGeometry.prototype.serialize = function () {
  39871. var serializationObject = _super.prototype.serialize.call(this);
  39872. serializationObject.width = this.width;
  39873. serializationObject.height = this.height;
  39874. serializationObject.subdivisions = this.subdivisions;
  39875. return serializationObject;
  39876. };
  39877. GroundGeometry.Parse = function (parsedGround, scene) {
  39878. if (scene.getGeometryByID(parsedGround.id)) {
  39879. return null; // null since geometry could be something else than a ground...
  39880. }
  39881. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  39882. if (BABYLON.Tags) {
  39883. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  39884. }
  39885. scene.pushGeometry(ground, true);
  39886. return ground;
  39887. };
  39888. return GroundGeometry;
  39889. }(_PrimitiveGeometry));
  39890. BABYLON.GroundGeometry = GroundGeometry;
  39891. /**
  39892. * Creates a tiled ground geometry
  39893. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  39894. */
  39895. var TiledGroundGeometry = /** @class */ (function (_super) {
  39896. __extends(TiledGroundGeometry, _super);
  39897. /**
  39898. * Creates a tiled ground geometry
  39899. * @param id defines the unique ID of the geometry
  39900. * @param scene defines the hosting scene
  39901. * @param xmin defines the minimum value on X axis
  39902. * @param zmin defines the minimum value on Z axis
  39903. * @param xmax defines the maximum value on X axis
  39904. * @param zmax defines the maximum value on Z axis
  39905. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  39906. * @param precision defines the precision to use when computing the tiles
  39907. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39908. * @param mesh defines the hosting mesh (can be null)
  39909. */
  39910. function TiledGroundGeometry(id, scene,
  39911. /**
  39912. * Defines the minimum value on X axis
  39913. */
  39914. xmin,
  39915. /**
  39916. * Defines the minimum value on Z axis
  39917. */
  39918. zmin,
  39919. /**
  39920. * Defines the maximum value on X axis
  39921. */
  39922. xmax,
  39923. /**
  39924. * Defines the maximum value on Z axis
  39925. */
  39926. zmax,
  39927. /**
  39928. * Defines the subdivisions to apply to the ground
  39929. */
  39930. subdivisions,
  39931. /**
  39932. * Defines the precision to use when computing the tiles
  39933. */
  39934. precision, canBeRegenerated, mesh) {
  39935. if (mesh === void 0) { mesh = null; }
  39936. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39937. _this.xmin = xmin;
  39938. _this.zmin = zmin;
  39939. _this.xmax = xmax;
  39940. _this.zmax = zmax;
  39941. _this.subdivisions = subdivisions;
  39942. _this.precision = precision;
  39943. return _this;
  39944. }
  39945. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  39946. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  39947. };
  39948. TiledGroundGeometry.prototype.copy = function (id) {
  39949. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  39950. };
  39951. return TiledGroundGeometry;
  39952. }(_PrimitiveGeometry));
  39953. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  39954. /**
  39955. * Creates a plane geometry
  39956. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  39957. */
  39958. var PlaneGeometry = /** @class */ (function (_super) {
  39959. __extends(PlaneGeometry, _super);
  39960. /**
  39961. * Creates a plane geometry
  39962. * @param id defines the unique ID of the geometry
  39963. * @param scene defines the hosting scene
  39964. * @param size defines the size of the plane (width === height)
  39965. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39966. * @param mesh defines the hosting mesh (can be null)
  39967. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39968. */
  39969. function PlaneGeometry(id, scene,
  39970. /**
  39971. * Defines the size of the plane (width === height)
  39972. */
  39973. size, canBeRegenerated, mesh,
  39974. /**
  39975. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39976. */
  39977. side) {
  39978. if (mesh === void 0) { mesh = null; }
  39979. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39980. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39981. _this.size = size;
  39982. _this.side = side;
  39983. return _this;
  39984. }
  39985. PlaneGeometry.prototype._regenerateVertexData = function () {
  39986. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  39987. };
  39988. PlaneGeometry.prototype.copy = function (id) {
  39989. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  39990. };
  39991. PlaneGeometry.prototype.serialize = function () {
  39992. var serializationObject = _super.prototype.serialize.call(this);
  39993. serializationObject.size = this.size;
  39994. return serializationObject;
  39995. };
  39996. PlaneGeometry.Parse = function (parsedPlane, scene) {
  39997. if (scene.getGeometryByID(parsedPlane.id)) {
  39998. return null; // null since geometry could be something else than a ground...
  39999. }
  40000. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40001. if (BABYLON.Tags) {
  40002. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40003. }
  40004. scene.pushGeometry(plane, true);
  40005. return plane;
  40006. };
  40007. return PlaneGeometry;
  40008. }(_PrimitiveGeometry));
  40009. BABYLON.PlaneGeometry = PlaneGeometry;
  40010. /**
  40011. * Creates a torus knot geometry
  40012. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40013. */
  40014. var TorusKnotGeometry = /** @class */ (function (_super) {
  40015. __extends(TorusKnotGeometry, _super);
  40016. /**
  40017. * Creates a torus knot geometry
  40018. * @param id defines the unique ID of the geometry
  40019. * @param scene defines the hosting scene
  40020. * @param radius defines the radius of the torus knot
  40021. * @param tube defines the thickness of the torus knot tube
  40022. * @param radialSegments defines the number of radial segments
  40023. * @param tubularSegments defines the number of tubular segments
  40024. * @param p defines the first number of windings
  40025. * @param q defines the second number of windings
  40026. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40027. * @param mesh defines the hosting mesh (can be null)
  40028. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40029. */
  40030. function TorusKnotGeometry(id, scene,
  40031. /**
  40032. * Defines the radius of the torus knot
  40033. */
  40034. radius,
  40035. /**
  40036. * Defines the thickness of the torus knot tube
  40037. */
  40038. tube,
  40039. /**
  40040. * Defines the number of radial segments
  40041. */
  40042. radialSegments,
  40043. /**
  40044. * Defines the number of tubular segments
  40045. */
  40046. tubularSegments,
  40047. /**
  40048. * Defines the first number of windings
  40049. */
  40050. p,
  40051. /**
  40052. * Defines the second number of windings
  40053. */
  40054. q, canBeRegenerated, mesh,
  40055. /**
  40056. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40057. */
  40058. side) {
  40059. if (mesh === void 0) { mesh = null; }
  40060. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40061. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40062. _this.radius = radius;
  40063. _this.tube = tube;
  40064. _this.radialSegments = radialSegments;
  40065. _this.tubularSegments = tubularSegments;
  40066. _this.p = p;
  40067. _this.q = q;
  40068. _this.side = side;
  40069. return _this;
  40070. }
  40071. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40072. 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 });
  40073. };
  40074. TorusKnotGeometry.prototype.copy = function (id) {
  40075. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40076. };
  40077. TorusKnotGeometry.prototype.serialize = function () {
  40078. var serializationObject = _super.prototype.serialize.call(this);
  40079. serializationObject.radius = this.radius;
  40080. serializationObject.tube = this.tube;
  40081. serializationObject.radialSegments = this.radialSegments;
  40082. serializationObject.tubularSegments = this.tubularSegments;
  40083. serializationObject.p = this.p;
  40084. serializationObject.q = this.q;
  40085. return serializationObject;
  40086. };
  40087. ;
  40088. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40089. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40090. return null; // null since geometry could be something else than a ground...
  40091. }
  40092. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40093. if (BABYLON.Tags) {
  40094. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40095. }
  40096. scene.pushGeometry(torusKnot, true);
  40097. return torusKnot;
  40098. };
  40099. return TorusKnotGeometry;
  40100. }(_PrimitiveGeometry));
  40101. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40102. //}
  40103. })(BABYLON || (BABYLON = {}));
  40104. //# sourceMappingURL=babylon.geometry.js.map
  40105. var BABYLON;
  40106. (function (BABYLON) {
  40107. /**
  40108. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40109. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40110. */
  40111. var PostProcessManager = /** @class */ (function () {
  40112. /**
  40113. * Creates a new instance PostProcess
  40114. * @param scene The scene that the post process is associated with.
  40115. */
  40116. function PostProcessManager(scene) {
  40117. this._vertexBuffers = {};
  40118. this._scene = scene;
  40119. }
  40120. PostProcessManager.prototype._prepareBuffers = function () {
  40121. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40122. return;
  40123. }
  40124. // VBO
  40125. var vertices = [];
  40126. vertices.push(1, 1);
  40127. vertices.push(-1, 1);
  40128. vertices.push(-1, -1);
  40129. vertices.push(1, -1);
  40130. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40131. this._buildIndexBuffer();
  40132. };
  40133. PostProcessManager.prototype._buildIndexBuffer = function () {
  40134. // Indices
  40135. var indices = [];
  40136. indices.push(0);
  40137. indices.push(1);
  40138. indices.push(2);
  40139. indices.push(0);
  40140. indices.push(2);
  40141. indices.push(3);
  40142. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40143. };
  40144. /**
  40145. * Rebuilds the vertex buffers of the manager.
  40146. */
  40147. PostProcessManager.prototype._rebuild = function () {
  40148. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40149. if (!vb) {
  40150. return;
  40151. }
  40152. vb._rebuild();
  40153. this._buildIndexBuffer();
  40154. };
  40155. // Methods
  40156. /**
  40157. * Prepares a frame to be run through a post process.
  40158. * @param sourceTexture The input texture to the post procesess. (default: null)
  40159. * @param postProcesses An array of post processes to be run. (default: null)
  40160. * @returns True if the post processes were able to be run.
  40161. */
  40162. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40163. if (sourceTexture === void 0) { sourceTexture = null; }
  40164. if (postProcesses === void 0) { postProcesses = null; }
  40165. var camera = this._scene.activeCamera;
  40166. if (!camera) {
  40167. return false;
  40168. }
  40169. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40170. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40171. return false;
  40172. }
  40173. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40174. return true;
  40175. };
  40176. /**
  40177. * Manually render a set of post processes to a texture.
  40178. * @param postProcesses An array of post processes to be run.
  40179. * @param targetTexture The target texture to render to.
  40180. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40181. */
  40182. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40183. if (targetTexture === void 0) { targetTexture = null; }
  40184. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40185. var engine = this._scene.getEngine();
  40186. for (var index = 0; index < postProcesses.length; index++) {
  40187. if (index < postProcesses.length - 1) {
  40188. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40189. }
  40190. else {
  40191. if (targetTexture) {
  40192. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40193. }
  40194. else {
  40195. engine.restoreDefaultFramebuffer();
  40196. }
  40197. }
  40198. var pp = postProcesses[index];
  40199. var effect = pp.apply();
  40200. if (effect) {
  40201. pp.onBeforeRenderObservable.notifyObservers(effect);
  40202. // VBOs
  40203. this._prepareBuffers();
  40204. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40205. // Draw order
  40206. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40207. pp.onAfterRenderObservable.notifyObservers(effect);
  40208. }
  40209. }
  40210. // Restore depth buffer
  40211. engine.setDepthBuffer(true);
  40212. engine.setDepthWrite(true);
  40213. };
  40214. /**
  40215. * Finalize the result of the output of the postprocesses.
  40216. * @param doNotPresent If true the result will not be displayed to the screen.
  40217. * @param targetTexture The target texture to render to.
  40218. * @param faceIndex The index of the face to bind the target texture to.
  40219. * @param postProcesses The array of post processes to render.
  40220. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40221. */
  40222. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40223. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40224. var camera = this._scene.activeCamera;
  40225. if (!camera) {
  40226. return;
  40227. }
  40228. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40229. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40230. return;
  40231. }
  40232. var engine = this._scene.getEngine();
  40233. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40234. var pp = postProcesses[index];
  40235. if (index < len - 1) {
  40236. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40237. }
  40238. else {
  40239. if (targetTexture) {
  40240. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40241. pp._outputTexture = targetTexture;
  40242. }
  40243. else {
  40244. engine.restoreDefaultFramebuffer();
  40245. pp._outputTexture = null;
  40246. }
  40247. }
  40248. if (doNotPresent) {
  40249. break;
  40250. }
  40251. var effect = pp.apply();
  40252. if (effect) {
  40253. pp.onBeforeRenderObservable.notifyObservers(effect);
  40254. // VBOs
  40255. this._prepareBuffers();
  40256. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40257. // Draw order
  40258. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40259. pp.onAfterRenderObservable.notifyObservers(effect);
  40260. }
  40261. }
  40262. // Restore states
  40263. engine.setDepthBuffer(true);
  40264. engine.setDepthWrite(true);
  40265. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40266. };
  40267. /**
  40268. * Disposes of the post process manager.
  40269. */
  40270. PostProcessManager.prototype.dispose = function () {
  40271. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40272. if (buffer) {
  40273. buffer.dispose();
  40274. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40275. }
  40276. if (this._indexBuffer) {
  40277. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40278. this._indexBuffer = null;
  40279. }
  40280. };
  40281. return PostProcessManager;
  40282. }());
  40283. BABYLON.PostProcessManager = PostProcessManager;
  40284. })(BABYLON || (BABYLON = {}));
  40285. //# sourceMappingURL=babylon.postProcessManager.js.map
  40286. var BABYLON;
  40287. (function (BABYLON) {
  40288. /**
  40289. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40290. */
  40291. var PerformanceMonitor = /** @class */ (function () {
  40292. /**
  40293. * constructor
  40294. * @param frameSampleSize The number of samples required to saturate the sliding window
  40295. */
  40296. function PerformanceMonitor(frameSampleSize) {
  40297. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40298. this._enabled = true;
  40299. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40300. }
  40301. /**
  40302. * Samples current frame
  40303. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40304. */
  40305. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40306. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40307. if (!this._enabled)
  40308. return;
  40309. if (this._lastFrameTimeMs != null) {
  40310. var dt = timeMs - this._lastFrameTimeMs;
  40311. this._rollingFrameTime.add(dt);
  40312. }
  40313. this._lastFrameTimeMs = timeMs;
  40314. };
  40315. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40316. /**
  40317. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40318. * @return Average frame time in milliseconds
  40319. */
  40320. get: function () {
  40321. return this._rollingFrameTime.average;
  40322. },
  40323. enumerable: true,
  40324. configurable: true
  40325. });
  40326. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40327. /**
  40328. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40329. * @return Frame time variance in milliseconds squared
  40330. */
  40331. get: function () {
  40332. return this._rollingFrameTime.variance;
  40333. },
  40334. enumerable: true,
  40335. configurable: true
  40336. });
  40337. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40338. /**
  40339. * Returns the frame time of the most recent frame
  40340. * @return Frame time in milliseconds
  40341. */
  40342. get: function () {
  40343. return this._rollingFrameTime.history(0);
  40344. },
  40345. enumerable: true,
  40346. configurable: true
  40347. });
  40348. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40349. /**
  40350. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40351. * @return Framerate in frames per second
  40352. */
  40353. get: function () {
  40354. return 1000.0 / this._rollingFrameTime.average;
  40355. },
  40356. enumerable: true,
  40357. configurable: true
  40358. });
  40359. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40360. /**
  40361. * Returns the average framerate in frames per second using the most recent frame time
  40362. * @return Framerate in frames per second
  40363. */
  40364. get: function () {
  40365. var history = this._rollingFrameTime.history(0);
  40366. if (history === 0) {
  40367. return 0;
  40368. }
  40369. return 1000.0 / history;
  40370. },
  40371. enumerable: true,
  40372. configurable: true
  40373. });
  40374. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40375. /**
  40376. * Returns true if enough samples have been taken to completely fill the sliding window
  40377. * @return true if saturated
  40378. */
  40379. get: function () {
  40380. return this._rollingFrameTime.isSaturated();
  40381. },
  40382. enumerable: true,
  40383. configurable: true
  40384. });
  40385. /**
  40386. * Enables contributions to the sliding window sample set
  40387. */
  40388. PerformanceMonitor.prototype.enable = function () {
  40389. this._enabled = true;
  40390. };
  40391. /**
  40392. * Disables contributions to the sliding window sample set
  40393. * Samples will not be interpolated over the disabled period
  40394. */
  40395. PerformanceMonitor.prototype.disable = function () {
  40396. this._enabled = false;
  40397. //clear last sample to avoid interpolating over the disabled period when next enabled
  40398. this._lastFrameTimeMs = null;
  40399. };
  40400. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40401. /**
  40402. * Returns true if sampling is enabled
  40403. * @return true if enabled
  40404. */
  40405. get: function () {
  40406. return this._enabled;
  40407. },
  40408. enumerable: true,
  40409. configurable: true
  40410. });
  40411. /**
  40412. * Resets performance monitor
  40413. */
  40414. PerformanceMonitor.prototype.reset = function () {
  40415. //clear last sample to avoid interpolating over the disabled period when next enabled
  40416. this._lastFrameTimeMs = null;
  40417. //wipe record
  40418. this._rollingFrameTime.reset();
  40419. };
  40420. return PerformanceMonitor;
  40421. }());
  40422. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40423. /**
  40424. * RollingAverage
  40425. *
  40426. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40427. */
  40428. var RollingAverage = /** @class */ (function () {
  40429. /**
  40430. * constructor
  40431. * @param length The number of samples required to saturate the sliding window
  40432. */
  40433. function RollingAverage(length) {
  40434. this._samples = new Array(length);
  40435. this.reset();
  40436. }
  40437. /**
  40438. * Adds a sample to the sample set
  40439. * @param v The sample value
  40440. */
  40441. RollingAverage.prototype.add = function (v) {
  40442. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40443. var delta;
  40444. //we need to check if we've already wrapped round
  40445. if (this.isSaturated()) {
  40446. //remove bottom of stack from mean
  40447. var bottomValue = this._samples[this._pos];
  40448. delta = bottomValue - this.average;
  40449. this.average -= delta / (this._sampleCount - 1);
  40450. this._m2 -= delta * (bottomValue - this.average);
  40451. }
  40452. else {
  40453. this._sampleCount++;
  40454. }
  40455. //add new value to mean
  40456. delta = v - this.average;
  40457. this.average += delta / (this._sampleCount);
  40458. this._m2 += delta * (v - this.average);
  40459. //set the new variance
  40460. this.variance = this._m2 / (this._sampleCount - 1);
  40461. this._samples[this._pos] = v;
  40462. this._pos++;
  40463. this._pos %= this._samples.length; //positive wrap around
  40464. };
  40465. /**
  40466. * Returns previously added values or null if outside of history or outside the sliding window domain
  40467. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40468. * @return Value previously recorded with add() or null if outside of range
  40469. */
  40470. RollingAverage.prototype.history = function (i) {
  40471. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40472. return 0;
  40473. }
  40474. var i0 = this._wrapPosition(this._pos - 1.0);
  40475. return this._samples[this._wrapPosition(i0 - i)];
  40476. };
  40477. /**
  40478. * Returns true if enough samples have been taken to completely fill the sliding window
  40479. * @return true if sample-set saturated
  40480. */
  40481. RollingAverage.prototype.isSaturated = function () {
  40482. return this._sampleCount >= this._samples.length;
  40483. };
  40484. /**
  40485. * Resets the rolling average (equivalent to 0 samples taken so far)
  40486. */
  40487. RollingAverage.prototype.reset = function () {
  40488. this.average = 0;
  40489. this.variance = 0;
  40490. this._sampleCount = 0;
  40491. this._pos = 0;
  40492. this._m2 = 0;
  40493. };
  40494. /**
  40495. * Wraps a value around the sample range boundaries
  40496. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40497. * @return Wrapped position in sample range
  40498. */
  40499. RollingAverage.prototype._wrapPosition = function (i) {
  40500. var max = this._samples.length;
  40501. return ((i % max) + max) % max;
  40502. };
  40503. return RollingAverage;
  40504. }());
  40505. BABYLON.RollingAverage = RollingAverage;
  40506. })(BABYLON || (BABYLON = {}));
  40507. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40508. var BABYLON;
  40509. (function (BABYLON) {
  40510. /**
  40511. * This groups together the common properties used for image processing either in direct forward pass
  40512. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40513. * or not.
  40514. */
  40515. var ImageProcessingConfiguration = /** @class */ (function () {
  40516. function ImageProcessingConfiguration() {
  40517. /**
  40518. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40519. */
  40520. this.colorCurves = new BABYLON.ColorCurves();
  40521. this._colorCurvesEnabled = false;
  40522. this._colorGradingEnabled = false;
  40523. this._colorGradingWithGreenDepth = true;
  40524. this._colorGradingBGR = true;
  40525. this._exposure = 1.0;
  40526. this._toneMappingEnabled = false;
  40527. this._contrast = 1.0;
  40528. /**
  40529. * Vignette stretch size.
  40530. */
  40531. this.vignetteStretch = 0;
  40532. /**
  40533. * Vignette centre X Offset.
  40534. */
  40535. this.vignetteCentreX = 0;
  40536. /**
  40537. * Vignette centre Y Offset.
  40538. */
  40539. this.vignetteCentreY = 0;
  40540. /**
  40541. * Vignette weight or intensity of the vignette effect.
  40542. */
  40543. this.vignetteWeight = 1.5;
  40544. /**
  40545. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40546. * if vignetteEnabled is set to true.
  40547. */
  40548. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40549. /**
  40550. * Camera field of view used by the Vignette effect.
  40551. */
  40552. this.vignetteCameraFov = 0.5;
  40553. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40554. this._vignetteEnabled = false;
  40555. this._applyByPostProcess = false;
  40556. this._isEnabled = true;
  40557. /**
  40558. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40559. */
  40560. this.onUpdateParameters = new BABYLON.Observable();
  40561. }
  40562. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40563. /**
  40564. * Gets wether the color curves effect is enabled.
  40565. */
  40566. get: function () {
  40567. return this._colorCurvesEnabled;
  40568. },
  40569. /**
  40570. * Sets wether the color curves effect is enabled.
  40571. */
  40572. set: function (value) {
  40573. if (this._colorCurvesEnabled === value) {
  40574. return;
  40575. }
  40576. this._colorCurvesEnabled = value;
  40577. this._updateParameters();
  40578. },
  40579. enumerable: true,
  40580. configurable: true
  40581. });
  40582. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40583. /**
  40584. * Gets wether the color grading effect is enabled.
  40585. */
  40586. get: function () {
  40587. return this._colorGradingEnabled;
  40588. },
  40589. /**
  40590. * Sets wether the color grading effect is enabled.
  40591. */
  40592. set: function (value) {
  40593. if (this._colorGradingEnabled === value) {
  40594. return;
  40595. }
  40596. this._colorGradingEnabled = value;
  40597. this._updateParameters();
  40598. },
  40599. enumerable: true,
  40600. configurable: true
  40601. });
  40602. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40603. /**
  40604. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40605. */
  40606. get: function () {
  40607. return this._colorGradingWithGreenDepth;
  40608. },
  40609. /**
  40610. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40611. */
  40612. set: function (value) {
  40613. if (this._colorGradingWithGreenDepth === value) {
  40614. return;
  40615. }
  40616. this._colorGradingWithGreenDepth = value;
  40617. this._updateParameters();
  40618. },
  40619. enumerable: true,
  40620. configurable: true
  40621. });
  40622. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40623. /**
  40624. * Gets wether the color grading texture contains BGR values.
  40625. */
  40626. get: function () {
  40627. return this._colorGradingBGR;
  40628. },
  40629. /**
  40630. * Sets wether the color grading texture contains BGR values.
  40631. */
  40632. set: function (value) {
  40633. if (this._colorGradingBGR === value) {
  40634. return;
  40635. }
  40636. this._colorGradingBGR = value;
  40637. this._updateParameters();
  40638. },
  40639. enumerable: true,
  40640. configurable: true
  40641. });
  40642. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40643. /**
  40644. * Gets the Exposure used in the effect.
  40645. */
  40646. get: function () {
  40647. return this._exposure;
  40648. },
  40649. /**
  40650. * Sets the Exposure used in the effect.
  40651. */
  40652. set: function (value) {
  40653. if (this._exposure === value) {
  40654. return;
  40655. }
  40656. this._exposure = value;
  40657. this._updateParameters();
  40658. },
  40659. enumerable: true,
  40660. configurable: true
  40661. });
  40662. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40663. /**
  40664. * Gets wether the tone mapping effect is enabled.
  40665. */
  40666. get: function () {
  40667. return this._toneMappingEnabled;
  40668. },
  40669. /**
  40670. * Sets wether the tone mapping effect is enabled.
  40671. */
  40672. set: function (value) {
  40673. if (this._toneMappingEnabled === value) {
  40674. return;
  40675. }
  40676. this._toneMappingEnabled = value;
  40677. this._updateParameters();
  40678. },
  40679. enumerable: true,
  40680. configurable: true
  40681. });
  40682. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40683. /**
  40684. * Gets the contrast used in the effect.
  40685. */
  40686. get: function () {
  40687. return this._contrast;
  40688. },
  40689. /**
  40690. * Sets the contrast used in the effect.
  40691. */
  40692. set: function (value) {
  40693. if (this._contrast === value) {
  40694. return;
  40695. }
  40696. this._contrast = value;
  40697. this._updateParameters();
  40698. },
  40699. enumerable: true,
  40700. configurable: true
  40701. });
  40702. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40703. /**
  40704. * Gets the vignette blend mode allowing different kind of effect.
  40705. */
  40706. get: function () {
  40707. return this._vignetteBlendMode;
  40708. },
  40709. /**
  40710. * Sets the vignette blend mode allowing different kind of effect.
  40711. */
  40712. set: function (value) {
  40713. if (this._vignetteBlendMode === value) {
  40714. return;
  40715. }
  40716. this._vignetteBlendMode = value;
  40717. this._updateParameters();
  40718. },
  40719. enumerable: true,
  40720. configurable: true
  40721. });
  40722. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40723. /**
  40724. * Gets wether the vignette effect is enabled.
  40725. */
  40726. get: function () {
  40727. return this._vignetteEnabled;
  40728. },
  40729. /**
  40730. * Sets wether the vignette effect is enabled.
  40731. */
  40732. set: function (value) {
  40733. if (this._vignetteEnabled === value) {
  40734. return;
  40735. }
  40736. this._vignetteEnabled = value;
  40737. this._updateParameters();
  40738. },
  40739. enumerable: true,
  40740. configurable: true
  40741. });
  40742. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40743. /**
  40744. * Gets wether the image processing is applied through a post process or not.
  40745. */
  40746. get: function () {
  40747. return this._applyByPostProcess;
  40748. },
  40749. /**
  40750. * Sets wether the image processing is applied through a post process or not.
  40751. */
  40752. set: function (value) {
  40753. if (this._applyByPostProcess === value) {
  40754. return;
  40755. }
  40756. this._applyByPostProcess = value;
  40757. this._updateParameters();
  40758. },
  40759. enumerable: true,
  40760. configurable: true
  40761. });
  40762. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40763. /**
  40764. * Gets wether the image processing is enabled or not.
  40765. */
  40766. get: function () {
  40767. return this._isEnabled;
  40768. },
  40769. /**
  40770. * Sets wether the image processing is enabled or not.
  40771. */
  40772. set: function (value) {
  40773. if (this._isEnabled === value) {
  40774. return;
  40775. }
  40776. this._isEnabled = value;
  40777. this._updateParameters();
  40778. },
  40779. enumerable: true,
  40780. configurable: true
  40781. });
  40782. /**
  40783. * Method called each time the image processing information changes requires to recompile the effect.
  40784. */
  40785. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40786. this.onUpdateParameters.notifyObservers(this);
  40787. };
  40788. ImageProcessingConfiguration.prototype.getClassName = function () {
  40789. return "ImageProcessingConfiguration";
  40790. };
  40791. /**
  40792. * Prepare the list of uniforms associated with the Image Processing effects.
  40793. * @param uniformsList The list of uniforms used in the effect
  40794. * @param defines the list of defines currently in use
  40795. */
  40796. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40797. if (defines.EXPOSURE) {
  40798. uniforms.push("exposureLinear");
  40799. }
  40800. if (defines.CONTRAST) {
  40801. uniforms.push("contrast");
  40802. }
  40803. if (defines.COLORGRADING) {
  40804. uniforms.push("colorTransformSettings");
  40805. }
  40806. if (defines.VIGNETTE) {
  40807. uniforms.push("vInverseScreenSize");
  40808. uniforms.push("vignetteSettings1");
  40809. uniforms.push("vignetteSettings2");
  40810. }
  40811. if (defines.COLORCURVES) {
  40812. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  40813. }
  40814. };
  40815. /**
  40816. * Prepare the list of samplers associated with the Image Processing effects.
  40817. * @param uniformsList The list of uniforms used in the effect
  40818. * @param defines the list of defines currently in use
  40819. */
  40820. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  40821. if (defines.COLORGRADING) {
  40822. samplersList.push("txColorTransform");
  40823. }
  40824. };
  40825. /**
  40826. * Prepare the list of defines associated to the shader.
  40827. * @param defines the list of defines to complete
  40828. */
  40829. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  40830. if (forPostProcess === void 0) { forPostProcess = false; }
  40831. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  40832. defines.VIGNETTE = false;
  40833. defines.TONEMAPPING = false;
  40834. defines.CONTRAST = false;
  40835. defines.EXPOSURE = false;
  40836. defines.COLORCURVES = false;
  40837. defines.COLORGRADING = false;
  40838. defines.COLORGRADING3D = false;
  40839. defines.IMAGEPROCESSING = false;
  40840. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  40841. return;
  40842. }
  40843. defines.VIGNETTE = this.vignetteEnabled;
  40844. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  40845. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  40846. defines.TONEMAPPING = this.toneMappingEnabled;
  40847. defines.CONTRAST = (this.contrast !== 1.0);
  40848. defines.EXPOSURE = (this.exposure !== 1.0);
  40849. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  40850. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  40851. if (defines.COLORGRADING) {
  40852. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  40853. }
  40854. else {
  40855. defines.COLORGRADING3D = false;
  40856. }
  40857. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  40858. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  40859. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  40860. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  40861. };
  40862. /**
  40863. * Returns true if all the image processing information are ready.
  40864. */
  40865. ImageProcessingConfiguration.prototype.isReady = function () {
  40866. // Color Grading texure can not be none blocking.
  40867. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  40868. };
  40869. /**
  40870. * Binds the image processing to the shader.
  40871. * @param effect The effect to bind to
  40872. */
  40873. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  40874. if (aspectRatio === void 0) { aspectRatio = 1; }
  40875. // Color Curves
  40876. if (this._colorCurvesEnabled && this.colorCurves) {
  40877. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  40878. }
  40879. // Vignette
  40880. if (this._vignetteEnabled) {
  40881. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  40882. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  40883. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  40884. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  40885. var vignetteScaleX = vignetteScaleY * aspectRatio;
  40886. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  40887. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  40888. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  40889. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  40890. var vignettePower = -2.0 * this.vignetteWeight;
  40891. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  40892. }
  40893. // Exposure
  40894. effect.setFloat("exposureLinear", this.exposure);
  40895. // Contrast
  40896. effect.setFloat("contrast", this.contrast);
  40897. // Color transform settings
  40898. if (this.colorGradingTexture) {
  40899. effect.setTexture("txColorTransform", this.colorGradingTexture);
  40900. var textureSize = this.colorGradingTexture.getSize().height;
  40901. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  40902. 0.5 / textureSize, // textureOffset
  40903. textureSize, // textureSize
  40904. this.colorGradingTexture.level // weight
  40905. );
  40906. }
  40907. };
  40908. /**
  40909. * Clones the current image processing instance.
  40910. * @return The cloned image processing
  40911. */
  40912. ImageProcessingConfiguration.prototype.clone = function () {
  40913. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  40914. };
  40915. /**
  40916. * Serializes the current image processing instance to a json representation.
  40917. * @return a JSON representation
  40918. */
  40919. ImageProcessingConfiguration.prototype.serialize = function () {
  40920. return BABYLON.SerializationHelper.Serialize(this);
  40921. };
  40922. /**
  40923. * Parses the image processing from a json representation.
  40924. * @param source the JSON source to parse
  40925. * @return The parsed image processing
  40926. */
  40927. ImageProcessingConfiguration.Parse = function (source) {
  40928. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  40929. };
  40930. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  40931. /**
  40932. * Used to apply the vignette as a mix with the pixel color.
  40933. */
  40934. get: function () {
  40935. return this._VIGNETTEMODE_MULTIPLY;
  40936. },
  40937. enumerable: true,
  40938. configurable: true
  40939. });
  40940. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  40941. /**
  40942. * Used to apply the vignette as a replacement of the pixel color.
  40943. */
  40944. get: function () {
  40945. return this._VIGNETTEMODE_OPAQUE;
  40946. },
  40947. enumerable: true,
  40948. configurable: true
  40949. });
  40950. // Static constants associated to the image processing.
  40951. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  40952. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  40953. __decorate([
  40954. BABYLON.serializeAsColorCurves()
  40955. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  40956. __decorate([
  40957. BABYLON.serialize()
  40958. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  40959. __decorate([
  40960. BABYLON.serializeAsTexture()
  40961. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  40962. __decorate([
  40963. BABYLON.serialize()
  40964. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  40965. __decorate([
  40966. BABYLON.serialize()
  40967. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  40968. __decorate([
  40969. BABYLON.serialize()
  40970. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  40971. __decorate([
  40972. BABYLON.serialize()
  40973. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  40974. __decorate([
  40975. BABYLON.serialize()
  40976. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  40977. __decorate([
  40978. BABYLON.serialize()
  40979. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  40980. __decorate([
  40981. BABYLON.serialize()
  40982. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  40983. __decorate([
  40984. BABYLON.serialize()
  40985. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  40986. __decorate([
  40987. BABYLON.serialize()
  40988. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  40989. __decorate([
  40990. BABYLON.serialize()
  40991. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  40992. __decorate([
  40993. BABYLON.serializeAsColor4()
  40994. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  40995. __decorate([
  40996. BABYLON.serialize()
  40997. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  40998. __decorate([
  40999. BABYLON.serialize()
  41000. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41001. __decorate([
  41002. BABYLON.serialize()
  41003. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41004. __decorate([
  41005. BABYLON.serialize()
  41006. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41007. __decorate([
  41008. BABYLON.serialize()
  41009. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41010. return ImageProcessingConfiguration;
  41011. }());
  41012. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41013. })(BABYLON || (BABYLON = {}));
  41014. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41015. var BABYLON;
  41016. (function (BABYLON) {
  41017. /**
  41018. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41019. * It can help converting any input color in a desired output one. This can then be used to create effects
  41020. * from sepia, black and white to sixties or futuristic rendering...
  41021. *
  41022. * The only supported format is currently 3dl.
  41023. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41024. */
  41025. var ColorGradingTexture = /** @class */ (function (_super) {
  41026. __extends(ColorGradingTexture, _super);
  41027. /**
  41028. * Instantiates a ColorGradingTexture from the following parameters.
  41029. *
  41030. * @param url The location of the color gradind data (currently only supporting 3dl)
  41031. * @param scene The scene the texture will be used in
  41032. */
  41033. function ColorGradingTexture(url, scene) {
  41034. var _this = _super.call(this, scene) || this;
  41035. if (!url) {
  41036. return _this;
  41037. }
  41038. _this._engine = scene.getEngine();
  41039. _this._textureMatrix = BABYLON.Matrix.Identity();
  41040. _this.name = url;
  41041. _this.url = url;
  41042. _this.hasAlpha = false;
  41043. _this.isCube = false;
  41044. _this.is3D = _this._engine.webGLVersion > 1;
  41045. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41046. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41047. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41048. _this.anisotropicFilteringLevel = 1;
  41049. _this._texture = _this._getFromCache(url, true);
  41050. if (!_this._texture) {
  41051. if (!scene.useDelayedTextureLoading) {
  41052. _this.loadTexture();
  41053. }
  41054. else {
  41055. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41056. }
  41057. }
  41058. return _this;
  41059. }
  41060. /**
  41061. * Returns the texture matrix used in most of the material.
  41062. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41063. */
  41064. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41065. return this._textureMatrix;
  41066. };
  41067. /**
  41068. * Occurs when the file being loaded is a .3dl LUT file.
  41069. */
  41070. ColorGradingTexture.prototype.load3dlTexture = function () {
  41071. var engine = this._engine;
  41072. var texture;
  41073. if (engine.webGLVersion === 1) {
  41074. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41075. }
  41076. else {
  41077. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41078. }
  41079. this._texture = texture;
  41080. var callback = function (text) {
  41081. if (typeof text !== "string") {
  41082. return;
  41083. }
  41084. var data = null;
  41085. var tempData = null;
  41086. var line;
  41087. var lines = text.split('\n');
  41088. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41089. var maxColor = 0;
  41090. for (var i = 0; i < lines.length; i++) {
  41091. line = lines[i];
  41092. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41093. continue;
  41094. if (line.indexOf('#') === 0)
  41095. continue;
  41096. var words = line.split(" ");
  41097. if (size === 0) {
  41098. // Number of space + one
  41099. size = words.length;
  41100. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41101. tempData = new Float32Array(size * size * size * 4);
  41102. continue;
  41103. }
  41104. if (size != 0) {
  41105. var r = Math.max(parseInt(words[0]), 0);
  41106. var g = Math.max(parseInt(words[1]), 0);
  41107. var b = Math.max(parseInt(words[2]), 0);
  41108. maxColor = Math.max(r, maxColor);
  41109. maxColor = Math.max(g, maxColor);
  41110. maxColor = Math.max(b, maxColor);
  41111. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41112. if (tempData) {
  41113. tempData[pixelStorageIndex + 0] = r;
  41114. tempData[pixelStorageIndex + 1] = g;
  41115. tempData[pixelStorageIndex + 2] = b;
  41116. }
  41117. pixelIndexSlice++;
  41118. if (pixelIndexSlice % size == 0) {
  41119. pixelIndexH++;
  41120. pixelIndexSlice = 0;
  41121. if (pixelIndexH % size == 0) {
  41122. pixelIndexW++;
  41123. pixelIndexH = 0;
  41124. }
  41125. }
  41126. }
  41127. }
  41128. if (tempData && data) {
  41129. for (var i = 0; i < tempData.length; i++) {
  41130. if (i > 0 && (i + 1) % 4 === 0) {
  41131. data[i] = 255;
  41132. }
  41133. else {
  41134. var value = tempData[i];
  41135. data[i] = (value / maxColor * 255);
  41136. }
  41137. }
  41138. }
  41139. if (texture.is3D) {
  41140. texture.updateSize(size, size, size);
  41141. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41142. }
  41143. else {
  41144. texture.updateSize(size * size, size);
  41145. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41146. }
  41147. };
  41148. var scene = this.getScene();
  41149. if (scene) {
  41150. scene._loadFile(this.url, callback);
  41151. }
  41152. else {
  41153. this._engine._loadFile(this.url, callback);
  41154. }
  41155. return this._texture;
  41156. };
  41157. /**
  41158. * Starts the loading process of the texture.
  41159. */
  41160. ColorGradingTexture.prototype.loadTexture = function () {
  41161. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41162. this.load3dlTexture();
  41163. }
  41164. };
  41165. /**
  41166. * Clones the color gradind texture.
  41167. */
  41168. ColorGradingTexture.prototype.clone = function () {
  41169. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41170. // Base texture
  41171. newTexture.level = this.level;
  41172. return newTexture;
  41173. };
  41174. /**
  41175. * Called during delayed load for textures.
  41176. */
  41177. ColorGradingTexture.prototype.delayLoad = function () {
  41178. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41179. return;
  41180. }
  41181. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41182. this._texture = this._getFromCache(this.url, true);
  41183. if (!this._texture) {
  41184. this.loadTexture();
  41185. }
  41186. };
  41187. /**
  41188. * Parses a color grading texture serialized by Babylon.
  41189. * @param parsedTexture The texture information being parsedTexture
  41190. * @param scene The scene to load the texture in
  41191. * @param rootUrl The root url of the data assets to load
  41192. * @return A color gradind texture
  41193. */
  41194. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41195. var texture = null;
  41196. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41197. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41198. texture.name = parsedTexture.name;
  41199. texture.level = parsedTexture.level;
  41200. }
  41201. return texture;
  41202. };
  41203. /**
  41204. * Serializes the LUT texture to json format.
  41205. */
  41206. ColorGradingTexture.prototype.serialize = function () {
  41207. if (!this.name) {
  41208. return null;
  41209. }
  41210. var serializationObject = {};
  41211. serializationObject.name = this.name;
  41212. serializationObject.level = this.level;
  41213. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41214. return serializationObject;
  41215. };
  41216. /**
  41217. * Empty line regex stored for GC.
  41218. */
  41219. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41220. return ColorGradingTexture;
  41221. }(BABYLON.BaseTexture));
  41222. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41223. })(BABYLON || (BABYLON = {}));
  41224. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41225. var BABYLON;
  41226. (function (BABYLON) {
  41227. /**
  41228. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41229. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41230. * 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;
  41231. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41232. */
  41233. var ColorCurves = /** @class */ (function () {
  41234. function ColorCurves() {
  41235. this._dirty = true;
  41236. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41237. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41238. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41239. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41240. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41241. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41242. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41243. this._globalHue = 30;
  41244. this._globalDensity = 0;
  41245. this._globalSaturation = 0;
  41246. this._globalExposure = 0;
  41247. this._highlightsHue = 30;
  41248. this._highlightsDensity = 0;
  41249. this._highlightsSaturation = 0;
  41250. this._highlightsExposure = 0;
  41251. this._midtonesHue = 30;
  41252. this._midtonesDensity = 0;
  41253. this._midtonesSaturation = 0;
  41254. this._midtonesExposure = 0;
  41255. this._shadowsHue = 30;
  41256. this._shadowsDensity = 0;
  41257. this._shadowsSaturation = 0;
  41258. this._shadowsExposure = 0;
  41259. }
  41260. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41261. /**
  41262. * Gets the global Hue value.
  41263. * 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).
  41264. */
  41265. get: function () {
  41266. return this._globalHue;
  41267. },
  41268. /**
  41269. * Sets the global Hue value.
  41270. * 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).
  41271. */
  41272. set: function (value) {
  41273. this._globalHue = value;
  41274. this._dirty = true;
  41275. },
  41276. enumerable: true,
  41277. configurable: true
  41278. });
  41279. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41280. /**
  41281. * Gets the global Density value.
  41282. * 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.
  41283. * Values less than zero provide a filter of opposite hue.
  41284. */
  41285. get: function () {
  41286. return this._globalDensity;
  41287. },
  41288. /**
  41289. * Sets the global Density value.
  41290. * 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.
  41291. * Values less than zero provide a filter of opposite hue.
  41292. */
  41293. set: function (value) {
  41294. this._globalDensity = value;
  41295. this._dirty = true;
  41296. },
  41297. enumerable: true,
  41298. configurable: true
  41299. });
  41300. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41301. /**
  41302. * Gets the global Saturation value.
  41303. * 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.
  41304. */
  41305. get: function () {
  41306. return this._globalSaturation;
  41307. },
  41308. /**
  41309. * Sets the global Saturation value.
  41310. * 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.
  41311. */
  41312. set: function (value) {
  41313. this._globalSaturation = value;
  41314. this._dirty = true;
  41315. },
  41316. enumerable: true,
  41317. configurable: true
  41318. });
  41319. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41320. /**
  41321. * Gets the highlights Hue value.
  41322. * 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).
  41323. */
  41324. get: function () {
  41325. return this._highlightsHue;
  41326. },
  41327. /**
  41328. * Sets the highlights Hue value.
  41329. * 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).
  41330. */
  41331. set: function (value) {
  41332. this._highlightsHue = value;
  41333. this._dirty = true;
  41334. },
  41335. enumerable: true,
  41336. configurable: true
  41337. });
  41338. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41339. /**
  41340. * Gets the highlights Density value.
  41341. * 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.
  41342. * Values less than zero provide a filter of opposite hue.
  41343. */
  41344. get: function () {
  41345. return this._highlightsDensity;
  41346. },
  41347. /**
  41348. * Sets the highlights Density value.
  41349. * 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.
  41350. * Values less than zero provide a filter of opposite hue.
  41351. */
  41352. set: function (value) {
  41353. this._highlightsDensity = value;
  41354. this._dirty = true;
  41355. },
  41356. enumerable: true,
  41357. configurable: true
  41358. });
  41359. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41360. /**
  41361. * Gets the highlights Saturation value.
  41362. * 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.
  41363. */
  41364. get: function () {
  41365. return this._highlightsSaturation;
  41366. },
  41367. /**
  41368. * Sets the highlights Saturation value.
  41369. * 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.
  41370. */
  41371. set: function (value) {
  41372. this._highlightsSaturation = value;
  41373. this._dirty = true;
  41374. },
  41375. enumerable: true,
  41376. configurable: true
  41377. });
  41378. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41379. /**
  41380. * Gets the highlights Exposure value.
  41381. * 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.
  41382. */
  41383. get: function () {
  41384. return this._highlightsExposure;
  41385. },
  41386. /**
  41387. * Sets the highlights Exposure value.
  41388. * 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.
  41389. */
  41390. set: function (value) {
  41391. this._highlightsExposure = value;
  41392. this._dirty = true;
  41393. },
  41394. enumerable: true,
  41395. configurable: true
  41396. });
  41397. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41398. /**
  41399. * Gets the midtones Hue value.
  41400. * 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).
  41401. */
  41402. get: function () {
  41403. return this._midtonesHue;
  41404. },
  41405. /**
  41406. * Sets the midtones Hue value.
  41407. * 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).
  41408. */
  41409. set: function (value) {
  41410. this._midtonesHue = value;
  41411. this._dirty = true;
  41412. },
  41413. enumerable: true,
  41414. configurable: true
  41415. });
  41416. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41417. /**
  41418. * Gets the midtones Density value.
  41419. * 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.
  41420. * Values less than zero provide a filter of opposite hue.
  41421. */
  41422. get: function () {
  41423. return this._midtonesDensity;
  41424. },
  41425. /**
  41426. * Sets the midtones Density value.
  41427. * 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.
  41428. * Values less than zero provide a filter of opposite hue.
  41429. */
  41430. set: function (value) {
  41431. this._midtonesDensity = value;
  41432. this._dirty = true;
  41433. },
  41434. enumerable: true,
  41435. configurable: true
  41436. });
  41437. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41438. /**
  41439. * Gets the midtones Saturation value.
  41440. * 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.
  41441. */
  41442. get: function () {
  41443. return this._midtonesSaturation;
  41444. },
  41445. /**
  41446. * Sets the midtones Saturation value.
  41447. * 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.
  41448. */
  41449. set: function (value) {
  41450. this._midtonesSaturation = value;
  41451. this._dirty = true;
  41452. },
  41453. enumerable: true,
  41454. configurable: true
  41455. });
  41456. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41457. /**
  41458. * Gets the midtones Exposure value.
  41459. * 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.
  41460. */
  41461. get: function () {
  41462. return this._midtonesExposure;
  41463. },
  41464. /**
  41465. * Sets the midtones Exposure value.
  41466. * 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.
  41467. */
  41468. set: function (value) {
  41469. this._midtonesExposure = value;
  41470. this._dirty = true;
  41471. },
  41472. enumerable: true,
  41473. configurable: true
  41474. });
  41475. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41476. /**
  41477. * Gets the shadows Hue value.
  41478. * 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).
  41479. */
  41480. get: function () {
  41481. return this._shadowsHue;
  41482. },
  41483. /**
  41484. * Sets the shadows Hue value.
  41485. * 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).
  41486. */
  41487. set: function (value) {
  41488. this._shadowsHue = value;
  41489. this._dirty = true;
  41490. },
  41491. enumerable: true,
  41492. configurable: true
  41493. });
  41494. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41495. /**
  41496. * Gets the shadows Density value.
  41497. * 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.
  41498. * Values less than zero provide a filter of opposite hue.
  41499. */
  41500. get: function () {
  41501. return this._shadowsDensity;
  41502. },
  41503. /**
  41504. * Sets the shadows Density value.
  41505. * 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.
  41506. * Values less than zero provide a filter of opposite hue.
  41507. */
  41508. set: function (value) {
  41509. this._shadowsDensity = value;
  41510. this._dirty = true;
  41511. },
  41512. enumerable: true,
  41513. configurable: true
  41514. });
  41515. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41516. /**
  41517. * Gets the shadows Saturation value.
  41518. * 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.
  41519. */
  41520. get: function () {
  41521. return this._shadowsSaturation;
  41522. },
  41523. /**
  41524. * Sets the shadows Saturation value.
  41525. * 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.
  41526. */
  41527. set: function (value) {
  41528. this._shadowsSaturation = value;
  41529. this._dirty = true;
  41530. },
  41531. enumerable: true,
  41532. configurable: true
  41533. });
  41534. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41535. /**
  41536. * Gets the shadows Exposure value.
  41537. * 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.
  41538. */
  41539. get: function () {
  41540. return this._shadowsExposure;
  41541. },
  41542. /**
  41543. * Sets the shadows Exposure value.
  41544. * 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.
  41545. */
  41546. set: function (value) {
  41547. this._shadowsExposure = value;
  41548. this._dirty = true;
  41549. },
  41550. enumerable: true,
  41551. configurable: true
  41552. });
  41553. ColorCurves.prototype.getClassName = function () {
  41554. return "ColorCurves";
  41555. };
  41556. /**
  41557. * Binds the color curves to the shader.
  41558. * @param colorCurves The color curve to bind
  41559. * @param effect The effect to bind to
  41560. */
  41561. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41562. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41563. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41564. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41565. if (colorCurves._dirty) {
  41566. colorCurves._dirty = false;
  41567. // Fill in global info.
  41568. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41569. // Compute highlights info.
  41570. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41571. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41572. // Compute midtones info.
  41573. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41574. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41575. // Compute shadows info.
  41576. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41577. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41578. // Compute deltas (neutral is midtones).
  41579. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41580. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41581. }
  41582. if (effect) {
  41583. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41584. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41585. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41586. }
  41587. };
  41588. /**
  41589. * Prepare the list of uniforms associated with the ColorCurves effects.
  41590. * @param uniformsList The list of uniforms used in the effect
  41591. */
  41592. ColorCurves.PrepareUniforms = function (uniformsList) {
  41593. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41594. };
  41595. /**
  41596. * Returns color grading data based on a hue, density, saturation and exposure value.
  41597. * @param filterHue The hue of the color filter.
  41598. * @param filterDensity The density of the color filter.
  41599. * @param saturation The saturation.
  41600. * @param exposure The exposure.
  41601. * @param result The result data container.
  41602. */
  41603. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41604. if (hue == null) {
  41605. return;
  41606. }
  41607. hue = ColorCurves.clamp(hue, 0, 360);
  41608. density = ColorCurves.clamp(density, -100, 100);
  41609. saturation = ColorCurves.clamp(saturation, -100, 100);
  41610. exposure = ColorCurves.clamp(exposure, -100, 100);
  41611. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41612. // so that the maximum filter density is only 50% control. This provides fine control
  41613. // for small values and reasonable range.
  41614. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41615. density *= 0.5;
  41616. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41617. if (density < 0) {
  41618. density *= -1;
  41619. hue = (hue + 180) % 360;
  41620. }
  41621. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41622. result.scaleToRef(2, result);
  41623. result.a = 1 + 0.01 * saturation;
  41624. };
  41625. /**
  41626. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41627. * @param value The input slider value in range [-100,100].
  41628. * @returns Adjusted value.
  41629. */
  41630. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41631. value /= 100;
  41632. var x = Math.abs(value);
  41633. x = Math.pow(x, 2);
  41634. if (value < 0) {
  41635. x *= -1;
  41636. }
  41637. x *= 100;
  41638. return x;
  41639. };
  41640. /**
  41641. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41642. * @param hue The hue (H) input.
  41643. * @param saturation The saturation (S) input.
  41644. * @param brightness The brightness (B) input.
  41645. * @result An RGBA color represented as Vector4.
  41646. */
  41647. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41648. var h = ColorCurves.clamp(hue, 0, 360);
  41649. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41650. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41651. if (s === 0) {
  41652. result.r = v;
  41653. result.g = v;
  41654. result.b = v;
  41655. }
  41656. else {
  41657. // sector 0 to 5
  41658. h /= 60;
  41659. var i = Math.floor(h);
  41660. // fractional part of h
  41661. var f = h - i;
  41662. var p = v * (1 - s);
  41663. var q = v * (1 - s * f);
  41664. var t = v * (1 - s * (1 - f));
  41665. switch (i) {
  41666. case 0:
  41667. result.r = v;
  41668. result.g = t;
  41669. result.b = p;
  41670. break;
  41671. case 1:
  41672. result.r = q;
  41673. result.g = v;
  41674. result.b = p;
  41675. break;
  41676. case 2:
  41677. result.r = p;
  41678. result.g = v;
  41679. result.b = t;
  41680. break;
  41681. case 3:
  41682. result.r = p;
  41683. result.g = q;
  41684. result.b = v;
  41685. break;
  41686. case 4:
  41687. result.r = t;
  41688. result.g = p;
  41689. result.b = v;
  41690. break;
  41691. default: // case 5:
  41692. result.r = v;
  41693. result.g = p;
  41694. result.b = q;
  41695. break;
  41696. }
  41697. }
  41698. result.a = 1;
  41699. };
  41700. /**
  41701. * Returns a value clamped between min and max
  41702. * @param value The value to clamp
  41703. * @param min The minimum of value
  41704. * @param max The maximum of value
  41705. * @returns The clamped value.
  41706. */
  41707. ColorCurves.clamp = function (value, min, max) {
  41708. return Math.min(Math.max(value, min), max);
  41709. };
  41710. /**
  41711. * Clones the current color curve instance.
  41712. * @return The cloned curves
  41713. */
  41714. ColorCurves.prototype.clone = function () {
  41715. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41716. };
  41717. /**
  41718. * Serializes the current color curve instance to a json representation.
  41719. * @return a JSON representation
  41720. */
  41721. ColorCurves.prototype.serialize = function () {
  41722. return BABYLON.SerializationHelper.Serialize(this);
  41723. };
  41724. /**
  41725. * Parses the color curve from a json representation.
  41726. * @param source the JSON source to parse
  41727. * @return The parsed curves
  41728. */
  41729. ColorCurves.Parse = function (source) {
  41730. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41731. };
  41732. __decorate([
  41733. BABYLON.serialize()
  41734. ], ColorCurves.prototype, "_globalHue", void 0);
  41735. __decorate([
  41736. BABYLON.serialize()
  41737. ], ColorCurves.prototype, "_globalDensity", void 0);
  41738. __decorate([
  41739. BABYLON.serialize()
  41740. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41741. __decorate([
  41742. BABYLON.serialize()
  41743. ], ColorCurves.prototype, "_globalExposure", void 0);
  41744. __decorate([
  41745. BABYLON.serialize()
  41746. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41747. __decorate([
  41748. BABYLON.serialize()
  41749. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41750. __decorate([
  41751. BABYLON.serialize()
  41752. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41753. __decorate([
  41754. BABYLON.serialize()
  41755. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41756. __decorate([
  41757. BABYLON.serialize()
  41758. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41759. __decorate([
  41760. BABYLON.serialize()
  41761. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41762. __decorate([
  41763. BABYLON.serialize()
  41764. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41765. __decorate([
  41766. BABYLON.serialize()
  41767. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41768. return ColorCurves;
  41769. }());
  41770. BABYLON.ColorCurves = ColorCurves;
  41771. })(BABYLON || (BABYLON = {}));
  41772. //# sourceMappingURL=babylon.colorCurves.js.map
  41773. //# sourceMappingURL=babylon.behavior.js.map
  41774. var BABYLON;
  41775. (function (BABYLON) {
  41776. /**
  41777. * "Static Class" containing the most commonly used helper while dealing with material for
  41778. * rendering purpose.
  41779. *
  41780. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41781. *
  41782. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41783. */
  41784. var MaterialHelper = /** @class */ (function () {
  41785. function MaterialHelper() {
  41786. }
  41787. /**
  41788. * Bind the current view position to an effect.
  41789. * @param effect The effect to be bound
  41790. * @param scene The scene the eyes position is used from
  41791. */
  41792. MaterialHelper.BindEyePosition = function (effect, scene) {
  41793. if (scene._forcedViewPosition) {
  41794. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41795. return;
  41796. }
  41797. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41798. };
  41799. /**
  41800. * Helps preparing the defines values about the UVs in used in the effect.
  41801. * UVs are shared as much as we can accross chanels in the shaders.
  41802. * @param texture The texture we are preparing the UVs for
  41803. * @param defines The defines to update
  41804. * @param key The chanel key "diffuse", "specular"... used in the shader
  41805. */
  41806. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41807. defines._needUVs = true;
  41808. defines[key] = true;
  41809. if (texture.getTextureMatrix().isIdentity(true)) {
  41810. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41811. if (texture.coordinatesIndex === 0) {
  41812. defines["MAINUV1"] = true;
  41813. }
  41814. else {
  41815. defines["MAINUV2"] = true;
  41816. }
  41817. }
  41818. else {
  41819. defines[key + "DIRECTUV"] = 0;
  41820. }
  41821. };
  41822. /**
  41823. * Binds a texture matrix value to its corrsponding uniform
  41824. * @param texture The texture to bind the matrix for
  41825. * @param uniformBuffer The uniform buffer receivin the data
  41826. * @param key The chanel key "diffuse", "specular"... used in the shader
  41827. */
  41828. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41829. var matrix = texture.getTextureMatrix();
  41830. if (!matrix.isIdentity(true)) {
  41831. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41832. }
  41833. };
  41834. /**
  41835. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41836. * @param mesh defines the current mesh
  41837. * @param scene defines the current scene
  41838. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41839. * @param pointsCloud defines if point cloud rendering has to be turned on
  41840. * @param fogEnabled defines if fog has to be turned on
  41841. * @param alphaTest defines if alpha testing has to be turned on
  41842. * @param defines defines the current list of defines
  41843. */
  41844. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41845. if (defines._areMiscDirty) {
  41846. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41847. defines["POINTSIZE"] = pointsCloud;
  41848. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41849. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41850. defines["ALPHATEST"] = alphaTest;
  41851. }
  41852. };
  41853. /**
  41854. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41855. * @param scene defines the current scene
  41856. * @param engine defines the current engine
  41857. * @param defines specifies the list of active defines
  41858. * @param useInstances defines if instances have to be turned on
  41859. * @param useClipPlane defines if clip plane have to be turned on
  41860. */
  41861. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41862. if (useClipPlane === void 0) { useClipPlane = null; }
  41863. var changed = false;
  41864. if (useClipPlane == null) {
  41865. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41866. }
  41867. if (defines["CLIPPLANE"] !== useClipPlane) {
  41868. defines["CLIPPLANE"] = useClipPlane;
  41869. changed = true;
  41870. }
  41871. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41872. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41873. changed = true;
  41874. }
  41875. if (defines["INSTANCES"] !== useInstances) {
  41876. defines["INSTANCES"] = useInstances;
  41877. changed = true;
  41878. }
  41879. if (changed) {
  41880. defines.markAsUnprocessed();
  41881. }
  41882. };
  41883. /**
  41884. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41885. * @param mesh The mesh containing the geometry data we will draw
  41886. * @param defines The defines to update
  41887. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41888. * @param useBones Precise whether bones should be used or not (override mesh info)
  41889. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41890. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41891. * @returns false if defines are considered not dirty and have not been checked
  41892. */
  41893. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41894. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41895. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41896. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41897. return false;
  41898. }
  41899. defines._normals = defines._needNormals;
  41900. defines._uvs = defines._needUVs;
  41901. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41902. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41903. defines["TANGENT"] = true;
  41904. }
  41905. if (defines._needUVs) {
  41906. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41907. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41908. }
  41909. else {
  41910. defines["UV1"] = false;
  41911. defines["UV2"] = false;
  41912. }
  41913. if (useVertexColor) {
  41914. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41915. defines["VERTEXCOLOR"] = hasVertexColors;
  41916. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41917. }
  41918. if (useBones) {
  41919. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41920. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41921. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41922. }
  41923. else {
  41924. defines["NUM_BONE_INFLUENCERS"] = 0;
  41925. defines["BonesPerMesh"] = 0;
  41926. }
  41927. }
  41928. if (useMorphTargets) {
  41929. var manager = mesh.morphTargetManager;
  41930. if (manager) {
  41931. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41932. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41933. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41934. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41935. }
  41936. else {
  41937. defines["MORPHTARGETS_TANGENT"] = false;
  41938. defines["MORPHTARGETS_NORMAL"] = false;
  41939. defines["MORPHTARGETS"] = false;
  41940. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41941. }
  41942. }
  41943. return true;
  41944. };
  41945. /**
  41946. * Prepares the defines related to the light information passed in parameter
  41947. * @param scene The scene we are intending to draw
  41948. * @param mesh The mesh the effect is compiling for
  41949. * @param defines The defines to update
  41950. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41951. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41952. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41953. * @returns true if normals will be required for the rest of the effect
  41954. */
  41955. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41956. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41957. if (disableLighting === void 0) { disableLighting = false; }
  41958. if (!defines._areLightsDirty) {
  41959. return defines._needNormals;
  41960. }
  41961. var lightIndex = 0;
  41962. var needNormals = false;
  41963. var needRebuild = false;
  41964. var lightmapMode = false;
  41965. var shadowEnabled = false;
  41966. var specularEnabled = false;
  41967. if (scene.lightsEnabled && !disableLighting) {
  41968. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41969. var light = _a[_i];
  41970. needNormals = true;
  41971. if (defines["LIGHT" + lightIndex] === undefined) {
  41972. needRebuild = true;
  41973. }
  41974. defines["LIGHT" + lightIndex] = true;
  41975. defines["SPOTLIGHT" + lightIndex] = false;
  41976. defines["HEMILIGHT" + lightIndex] = false;
  41977. defines["POINTLIGHT" + lightIndex] = false;
  41978. defines["DIRLIGHT" + lightIndex] = false;
  41979. var type;
  41980. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41981. type = "SPOTLIGHT" + lightIndex;
  41982. var spotLight = light;
  41983. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41984. }
  41985. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41986. type = "HEMILIGHT" + lightIndex;
  41987. }
  41988. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41989. type = "POINTLIGHT" + lightIndex;
  41990. }
  41991. else {
  41992. type = "DIRLIGHT" + lightIndex;
  41993. }
  41994. defines[type] = true;
  41995. // Specular
  41996. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41997. specularEnabled = true;
  41998. }
  41999. // Shadows
  42000. defines["SHADOW" + lightIndex] = false;
  42001. defines["SHADOWPCF" + lightIndex] = false;
  42002. defines["SHADOWPCSS" + lightIndex] = false;
  42003. defines["SHADOWPOISSON" + lightIndex] = false;
  42004. defines["SHADOWESM" + lightIndex] = false;
  42005. defines["SHADOWCUBE" + lightIndex] = false;
  42006. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42007. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42008. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42009. var shadowGenerator = light.getShadowGenerator();
  42010. if (shadowGenerator) {
  42011. shadowEnabled = true;
  42012. shadowGenerator.prepareDefines(defines, lightIndex);
  42013. }
  42014. }
  42015. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42016. lightmapMode = true;
  42017. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42018. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42019. }
  42020. else {
  42021. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42022. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42023. }
  42024. lightIndex++;
  42025. if (lightIndex === maxSimultaneousLights)
  42026. break;
  42027. }
  42028. }
  42029. defines["SPECULARTERM"] = specularEnabled;
  42030. defines["SHADOWS"] = shadowEnabled;
  42031. // Resetting all other lights if any
  42032. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42033. if (defines["LIGHT" + index] !== undefined) {
  42034. defines["LIGHT" + index] = false;
  42035. defines["HEMILIGHT" + lightIndex] = false;
  42036. defines["POINTLIGHT" + lightIndex] = false;
  42037. defines["DIRLIGHT" + lightIndex] = false;
  42038. defines["SPOTLIGHT" + lightIndex] = false;
  42039. defines["SHADOW" + lightIndex] = false;
  42040. }
  42041. }
  42042. var caps = scene.getEngine().getCaps();
  42043. if (defines["SHADOWFLOAT"] === undefined) {
  42044. needRebuild = true;
  42045. }
  42046. defines["SHADOWFLOAT"] = shadowEnabled &&
  42047. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42048. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42049. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42050. if (needRebuild) {
  42051. defines.rebuild();
  42052. }
  42053. return needNormals;
  42054. };
  42055. /**
  42056. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42057. * that won t be acctive due to defines being turned off.
  42058. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42059. * @param samplersList The samplers list
  42060. * @param defines The defines helping in the list generation
  42061. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42062. */
  42063. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42064. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42065. var uniformsList;
  42066. var uniformBuffersList = null;
  42067. if (uniformsListOrOptions.uniformsNames) {
  42068. var options = uniformsListOrOptions;
  42069. uniformsList = options.uniformsNames;
  42070. uniformBuffersList = options.uniformBuffersNames;
  42071. samplersList = options.samplers;
  42072. defines = options.defines;
  42073. maxSimultaneousLights = options.maxSimultaneousLights;
  42074. }
  42075. else {
  42076. uniformsList = uniformsListOrOptions;
  42077. if (!samplersList) {
  42078. samplersList = [];
  42079. }
  42080. }
  42081. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42082. if (!defines["LIGHT" + lightIndex]) {
  42083. break;
  42084. }
  42085. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42086. if (uniformBuffersList) {
  42087. uniformBuffersList.push("Light" + lightIndex);
  42088. }
  42089. samplersList.push("shadowSampler" + lightIndex);
  42090. samplersList.push("depthSampler" + lightIndex);
  42091. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42092. samplersList.push("projectionLightSampler" + lightIndex);
  42093. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42094. }
  42095. }
  42096. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42097. uniformsList.push("morphTargetInfluences");
  42098. }
  42099. };
  42100. /**
  42101. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42102. * @param defines The defines to update while falling back
  42103. * @param fallbacks The authorized effect fallbacks
  42104. * @param maxSimultaneousLights The maximum number of lights allowed
  42105. * @param rank the current rank of the Effect
  42106. * @returns The newly affected rank
  42107. */
  42108. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42109. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42110. if (rank === void 0) { rank = 0; }
  42111. var lightFallbackRank = 0;
  42112. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42113. if (!defines["LIGHT" + lightIndex]) {
  42114. break;
  42115. }
  42116. if (lightIndex > 0) {
  42117. lightFallbackRank = rank + lightIndex;
  42118. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42119. }
  42120. if (!defines["SHADOWS"]) {
  42121. if (defines["SHADOW" + lightIndex]) {
  42122. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42123. }
  42124. if (defines["SHADOWPCF" + lightIndex]) {
  42125. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42126. }
  42127. if (defines["SHADOWPCSS" + lightIndex]) {
  42128. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42129. }
  42130. if (defines["SHADOWPOISSON" + lightIndex]) {
  42131. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42132. }
  42133. if (defines["SHADOWESM" + lightIndex]) {
  42134. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42135. }
  42136. }
  42137. }
  42138. return lightFallbackRank++;
  42139. };
  42140. /**
  42141. * Prepares the list of attributes required for morph targets according to the effect defines.
  42142. * @param attribs The current list of supported attribs
  42143. * @param mesh The mesh to prepare the morph targets attributes for
  42144. * @param defines The current Defines of the effect
  42145. */
  42146. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42147. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42148. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42149. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42150. var manager = mesh.morphTargetManager;
  42151. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42152. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42153. for (var index = 0; index < influencers; index++) {
  42154. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42155. if (normal) {
  42156. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42157. }
  42158. if (tangent) {
  42159. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42160. }
  42161. if (attribs.length > maxAttributesCount) {
  42162. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42163. }
  42164. }
  42165. }
  42166. };
  42167. /**
  42168. * Prepares the list of attributes required for bones according to the effect defines.
  42169. * @param attribs The current list of supported attribs
  42170. * @param mesh The mesh to prepare the bones attributes for
  42171. * @param defines The current Defines of the effect
  42172. * @param fallbacks The current efffect fallback strategy
  42173. */
  42174. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42175. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42176. fallbacks.addCPUSkinningFallback(0, mesh);
  42177. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42178. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42179. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42180. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42181. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42182. }
  42183. }
  42184. };
  42185. /**
  42186. * Prepares the list of attributes required for instances according to the effect defines.
  42187. * @param attribs The current list of supported attribs
  42188. * @param defines The current Defines of the effect
  42189. */
  42190. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42191. if (defines["INSTANCES"]) {
  42192. attribs.push("world0");
  42193. attribs.push("world1");
  42194. attribs.push("world2");
  42195. attribs.push("world3");
  42196. }
  42197. };
  42198. /**
  42199. * Binds the light shadow information to the effect for the given mesh.
  42200. * @param light The light containing the generator
  42201. * @param scene The scene the lights belongs to
  42202. * @param mesh The mesh we are binding the information to render
  42203. * @param lightIndex The light index in the effect used to render the mesh
  42204. * @param effect The effect we are binding the data to
  42205. */
  42206. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42207. if (light.shadowEnabled && mesh.receiveShadows) {
  42208. var shadowGenerator = light.getShadowGenerator();
  42209. if (shadowGenerator) {
  42210. shadowGenerator.bindShadowLight(lightIndex, effect);
  42211. }
  42212. }
  42213. };
  42214. /**
  42215. * Binds the light information to the effect.
  42216. * @param light The light containing the generator
  42217. * @param effect The effect we are binding the data to
  42218. * @param lightIndex The light index in the effect used to render
  42219. */
  42220. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42221. light.transferToEffect(effect, lightIndex + "");
  42222. };
  42223. /**
  42224. * Binds the lights information from the scene to the effect for the given mesh.
  42225. * @param scene The scene the lights belongs to
  42226. * @param mesh The mesh we are binding the information to render
  42227. * @param effect The effect we are binding the data to
  42228. * @param defines The generated defines for the effect
  42229. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42230. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42231. */
  42232. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42233. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42234. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42235. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42236. for (var i = 0; i < len; i++) {
  42237. var light = mesh._lightSources[i];
  42238. var iAsString = i.toString();
  42239. var scaledIntensity = light.getScaledIntensity();
  42240. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42241. MaterialHelper.BindLightProperties(light, effect, i);
  42242. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42243. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42244. if (defines["SPECULARTERM"]) {
  42245. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42246. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42247. }
  42248. // Shadows
  42249. if (scene.shadowsEnabled) {
  42250. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42251. }
  42252. light._uniformBuffer.update();
  42253. }
  42254. };
  42255. /**
  42256. * Binds the fog information from the scene to the effect for the given mesh.
  42257. * @param scene The scene the lights belongs to
  42258. * @param mesh The mesh we are binding the information to render
  42259. * @param effect The effect we are binding the data to
  42260. */
  42261. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42262. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42263. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42264. effect.setColor3("vFogColor", scene.fogColor);
  42265. }
  42266. };
  42267. /**
  42268. * Binds the bones information from the mesh to the effect.
  42269. * @param mesh The mesh we are binding the information to render
  42270. * @param effect The effect we are binding the data to
  42271. */
  42272. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42273. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42274. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42275. if (matrices && effect) {
  42276. effect.setMatrices("mBones", matrices);
  42277. }
  42278. }
  42279. };
  42280. /**
  42281. * Binds the morph targets information from the mesh to the effect.
  42282. * @param abstractMesh The mesh we are binding the information to render
  42283. * @param effect The effect we are binding the data to
  42284. */
  42285. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42286. var manager = abstractMesh.morphTargetManager;
  42287. if (!abstractMesh || !manager) {
  42288. return;
  42289. }
  42290. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42291. };
  42292. /**
  42293. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42294. * @param defines The generated defines used in the effect
  42295. * @param effect The effect we are binding the data to
  42296. * @param scene The scene we are willing to render with logarithmic scale for
  42297. */
  42298. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42299. if (defines["LOGARITHMICDEPTH"]) {
  42300. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42301. }
  42302. };
  42303. /**
  42304. * Binds the clip plane information from the scene to the effect.
  42305. * @param scene The scene the clip plane information are extracted from
  42306. * @param effect The effect we are binding the data to
  42307. */
  42308. MaterialHelper.BindClipPlane = function (effect, scene) {
  42309. if (scene.clipPlane) {
  42310. var clipPlane = scene.clipPlane;
  42311. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42312. }
  42313. };
  42314. return MaterialHelper;
  42315. }());
  42316. BABYLON.MaterialHelper = MaterialHelper;
  42317. })(BABYLON || (BABYLON = {}));
  42318. //# sourceMappingURL=babylon.materialHelper.js.map
  42319. var BABYLON;
  42320. (function (BABYLON) {
  42321. var PushMaterial = /** @class */ (function (_super) {
  42322. __extends(PushMaterial, _super);
  42323. function PushMaterial(name, scene) {
  42324. var _this = _super.call(this, name, scene) || this;
  42325. _this._normalMatrix = new BABYLON.Matrix();
  42326. _this.storeEffectOnSubMeshes = true;
  42327. return _this;
  42328. }
  42329. PushMaterial.prototype.getEffect = function () {
  42330. return this._activeEffect;
  42331. };
  42332. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42333. if (!mesh) {
  42334. return false;
  42335. }
  42336. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42337. return true;
  42338. }
  42339. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42340. };
  42341. /**
  42342. * Binds the given world matrix to the active effect
  42343. *
  42344. * @param world the matrix to bind
  42345. */
  42346. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42347. this._activeEffect.setMatrix("world", world);
  42348. };
  42349. /**
  42350. * Binds the given normal matrix to the active effect
  42351. *
  42352. * @param normalMatrix the matrix to bind
  42353. */
  42354. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42355. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42356. };
  42357. PushMaterial.prototype.bind = function (world, mesh) {
  42358. if (!mesh) {
  42359. return;
  42360. }
  42361. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42362. };
  42363. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42364. if (effect === void 0) { effect = null; }
  42365. _super.prototype._afterBind.call(this, mesh);
  42366. this.getScene()._cachedEffect = effect;
  42367. };
  42368. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42369. if (visibility === void 0) { visibility = 1; }
  42370. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42371. };
  42372. return PushMaterial;
  42373. }(BABYLON.Material));
  42374. BABYLON.PushMaterial = PushMaterial;
  42375. })(BABYLON || (BABYLON = {}));
  42376. //# sourceMappingURL=babylon.pushMaterial.js.map
  42377. var BABYLON;
  42378. (function (BABYLON) {
  42379. /** @ignore */
  42380. var StandardMaterialDefines = /** @class */ (function (_super) {
  42381. __extends(StandardMaterialDefines, _super);
  42382. function StandardMaterialDefines() {
  42383. var _this = _super.call(this) || this;
  42384. _this.MAINUV1 = false;
  42385. _this.MAINUV2 = false;
  42386. _this.DIFFUSE = false;
  42387. _this.DIFFUSEDIRECTUV = 0;
  42388. _this.AMBIENT = false;
  42389. _this.AMBIENTDIRECTUV = 0;
  42390. _this.OPACITY = false;
  42391. _this.OPACITYDIRECTUV = 0;
  42392. _this.OPACITYRGB = false;
  42393. _this.REFLECTION = false;
  42394. _this.EMISSIVE = false;
  42395. _this.EMISSIVEDIRECTUV = 0;
  42396. _this.SPECULAR = false;
  42397. _this.SPECULARDIRECTUV = 0;
  42398. _this.BUMP = false;
  42399. _this.BUMPDIRECTUV = 0;
  42400. _this.PARALLAX = false;
  42401. _this.PARALLAXOCCLUSION = false;
  42402. _this.SPECULAROVERALPHA = false;
  42403. _this.CLIPPLANE = false;
  42404. _this.ALPHATEST = false;
  42405. _this.DEPTHPREPASS = false;
  42406. _this.ALPHAFROMDIFFUSE = false;
  42407. _this.POINTSIZE = false;
  42408. _this.FOG = false;
  42409. _this.SPECULARTERM = false;
  42410. _this.DIFFUSEFRESNEL = false;
  42411. _this.OPACITYFRESNEL = false;
  42412. _this.REFLECTIONFRESNEL = false;
  42413. _this.REFRACTIONFRESNEL = false;
  42414. _this.EMISSIVEFRESNEL = false;
  42415. _this.FRESNEL = false;
  42416. _this.NORMAL = false;
  42417. _this.UV1 = false;
  42418. _this.UV2 = false;
  42419. _this.VERTEXCOLOR = false;
  42420. _this.VERTEXALPHA = false;
  42421. _this.NUM_BONE_INFLUENCERS = 0;
  42422. _this.BonesPerMesh = 0;
  42423. _this.INSTANCES = false;
  42424. _this.GLOSSINESS = false;
  42425. _this.ROUGHNESS = false;
  42426. _this.EMISSIVEASILLUMINATION = false;
  42427. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42428. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42429. _this.LIGHTMAP = false;
  42430. _this.LIGHTMAPDIRECTUV = 0;
  42431. _this.OBJECTSPACE_NORMALMAP = false;
  42432. _this.USELIGHTMAPASSHADOWMAP = false;
  42433. _this.REFLECTIONMAP_3D = false;
  42434. _this.REFLECTIONMAP_SPHERICAL = false;
  42435. _this.REFLECTIONMAP_PLANAR = false;
  42436. _this.REFLECTIONMAP_CUBIC = false;
  42437. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42438. _this.REFLECTIONMAP_PROJECTION = false;
  42439. _this.REFLECTIONMAP_SKYBOX = false;
  42440. _this.REFLECTIONMAP_EXPLICIT = false;
  42441. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42442. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42443. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42444. _this.INVERTCUBICMAP = false;
  42445. _this.LOGARITHMICDEPTH = false;
  42446. _this.REFRACTION = false;
  42447. _this.REFRACTIONMAP_3D = false;
  42448. _this.REFLECTIONOVERALPHA = false;
  42449. _this.TWOSIDEDLIGHTING = false;
  42450. _this.SHADOWFLOAT = false;
  42451. _this.MORPHTARGETS = false;
  42452. _this.MORPHTARGETS_NORMAL = false;
  42453. _this.MORPHTARGETS_TANGENT = false;
  42454. _this.NUM_MORPH_INFLUENCERS = 0;
  42455. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42456. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42457. _this.IMAGEPROCESSING = false;
  42458. _this.VIGNETTE = false;
  42459. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42460. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42461. _this.TONEMAPPING = false;
  42462. _this.CONTRAST = false;
  42463. _this.COLORCURVES = false;
  42464. _this.COLORGRADING = false;
  42465. _this.COLORGRADING3D = false;
  42466. _this.SAMPLER3DGREENDEPTH = false;
  42467. _this.SAMPLER3DBGRMAP = false;
  42468. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42469. /**
  42470. * If the reflection texture on this material is in linear color space
  42471. * @ignore
  42472. */
  42473. _this.IS_REFLECTION_LINEAR = false;
  42474. /**
  42475. * If the refraction texture on this material is in linear color space
  42476. * @ignore
  42477. */
  42478. _this.IS_REFRACTION_LINEAR = false;
  42479. _this.EXPOSURE = false;
  42480. _this.rebuild();
  42481. return _this;
  42482. }
  42483. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42484. var modes = [
  42485. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42486. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42487. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42488. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42489. ];
  42490. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42491. var mode = modes_1[_i];
  42492. this[mode] = (mode === modeToEnable);
  42493. }
  42494. };
  42495. return StandardMaterialDefines;
  42496. }(BABYLON.MaterialDefines));
  42497. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42498. var StandardMaterial = /** @class */ (function (_super) {
  42499. __extends(StandardMaterial, _super);
  42500. function StandardMaterial(name, scene) {
  42501. var _this = _super.call(this, name, scene) || this;
  42502. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42503. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42504. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42505. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42506. _this.specularPower = 64;
  42507. _this._useAlphaFromDiffuseTexture = false;
  42508. _this._useEmissiveAsIllumination = false;
  42509. _this._linkEmissiveWithDiffuse = false;
  42510. _this._useSpecularOverAlpha = false;
  42511. _this._useReflectionOverAlpha = false;
  42512. _this._disableLighting = false;
  42513. _this._useObjectSpaceNormalMap = false;
  42514. _this._useParallax = false;
  42515. _this._useParallaxOcclusion = false;
  42516. _this.parallaxScaleBias = 0.05;
  42517. _this._roughness = 0;
  42518. _this.indexOfRefraction = 0.98;
  42519. _this.invertRefractionY = true;
  42520. /**
  42521. * Defines the alpha limits in alpha test mode
  42522. */
  42523. _this.alphaCutOff = 0.4;
  42524. _this._useLightmapAsShadowmap = false;
  42525. _this._useReflectionFresnelFromSpecular = false;
  42526. _this._useGlossinessFromSpecularMapAlpha = false;
  42527. _this._maxSimultaneousLights = 4;
  42528. /**
  42529. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42530. */
  42531. _this._invertNormalMapX = false;
  42532. /**
  42533. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42534. */
  42535. _this._invertNormalMapY = false;
  42536. /**
  42537. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42538. */
  42539. _this._twoSidedLighting = false;
  42540. _this._renderTargets = new BABYLON.SmartArray(16);
  42541. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42542. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42543. // Setup the default processing configuration to the scene.
  42544. _this._attachImageProcessingConfiguration(null);
  42545. _this.getRenderTargetTextures = function () {
  42546. _this._renderTargets.reset();
  42547. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42548. _this._renderTargets.push(_this._reflectionTexture);
  42549. }
  42550. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42551. _this._renderTargets.push(_this._refractionTexture);
  42552. }
  42553. return _this._renderTargets;
  42554. };
  42555. return _this;
  42556. }
  42557. ;
  42558. ;
  42559. ;
  42560. ;
  42561. ;
  42562. ;
  42563. ;
  42564. ;
  42565. ;
  42566. ;
  42567. ;
  42568. ;
  42569. ;
  42570. ;
  42571. ;
  42572. ;
  42573. ;
  42574. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42575. /**
  42576. * Gets the image processing configuration used either in this material.
  42577. */
  42578. get: function () {
  42579. return this._imageProcessingConfiguration;
  42580. },
  42581. /**
  42582. * Sets the Default image processing configuration used either in the this material.
  42583. *
  42584. * If sets to null, the scene one is in use.
  42585. */
  42586. set: function (value) {
  42587. this._attachImageProcessingConfiguration(value);
  42588. // Ensure the effect will be rebuilt.
  42589. this._markAllSubMeshesAsTexturesDirty();
  42590. },
  42591. enumerable: true,
  42592. configurable: true
  42593. });
  42594. /**
  42595. * Attaches a new image processing configuration to the Standard Material.
  42596. * @param configuration
  42597. */
  42598. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42599. var _this = this;
  42600. if (configuration === this._imageProcessingConfiguration) {
  42601. return;
  42602. }
  42603. // Detaches observer.
  42604. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42605. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42606. }
  42607. // Pick the scene configuration if needed.
  42608. if (!configuration) {
  42609. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42610. }
  42611. else {
  42612. this._imageProcessingConfiguration = configuration;
  42613. }
  42614. // Attaches observer.
  42615. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42616. _this._markAllSubMeshesAsImageProcessingDirty();
  42617. });
  42618. };
  42619. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42620. /**
  42621. * Gets wether the color curves effect is enabled.
  42622. */
  42623. get: function () {
  42624. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42625. },
  42626. /**
  42627. * Sets wether the color curves effect is enabled.
  42628. */
  42629. set: function (value) {
  42630. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42631. },
  42632. enumerable: true,
  42633. configurable: true
  42634. });
  42635. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42636. /**
  42637. * Gets wether the color grading effect is enabled.
  42638. */
  42639. get: function () {
  42640. return this.imageProcessingConfiguration.colorGradingEnabled;
  42641. },
  42642. /**
  42643. * Gets wether the color grading effect is enabled.
  42644. */
  42645. set: function (value) {
  42646. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42647. },
  42648. enumerable: true,
  42649. configurable: true
  42650. });
  42651. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42652. /**
  42653. * Gets wether tonemapping is enabled or not.
  42654. */
  42655. get: function () {
  42656. return this._imageProcessingConfiguration.toneMappingEnabled;
  42657. },
  42658. /**
  42659. * Sets wether tonemapping is enabled or not
  42660. */
  42661. set: function (value) {
  42662. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42663. },
  42664. enumerable: true,
  42665. configurable: true
  42666. });
  42667. ;
  42668. ;
  42669. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42670. /**
  42671. * The camera exposure used on this material.
  42672. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42673. * This corresponds to a photographic exposure.
  42674. */
  42675. get: function () {
  42676. return this._imageProcessingConfiguration.exposure;
  42677. },
  42678. /**
  42679. * The camera exposure used on this material.
  42680. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42681. * This corresponds to a photographic exposure.
  42682. */
  42683. set: function (value) {
  42684. this._imageProcessingConfiguration.exposure = value;
  42685. },
  42686. enumerable: true,
  42687. configurable: true
  42688. });
  42689. ;
  42690. ;
  42691. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42692. /**
  42693. * Gets The camera contrast used on this material.
  42694. */
  42695. get: function () {
  42696. return this._imageProcessingConfiguration.contrast;
  42697. },
  42698. /**
  42699. * Sets The camera contrast used on this material.
  42700. */
  42701. set: function (value) {
  42702. this._imageProcessingConfiguration.contrast = value;
  42703. },
  42704. enumerable: true,
  42705. configurable: true
  42706. });
  42707. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42708. /**
  42709. * Gets the Color Grading 2D Lookup Texture.
  42710. */
  42711. get: function () {
  42712. return this._imageProcessingConfiguration.colorGradingTexture;
  42713. },
  42714. /**
  42715. * Sets the Color Grading 2D Lookup Texture.
  42716. */
  42717. set: function (value) {
  42718. this._imageProcessingConfiguration.colorGradingTexture = value;
  42719. },
  42720. enumerable: true,
  42721. configurable: true
  42722. });
  42723. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42724. /**
  42725. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42726. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42727. * 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;
  42728. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42729. */
  42730. get: function () {
  42731. return this._imageProcessingConfiguration.colorCurves;
  42732. },
  42733. /**
  42734. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42735. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42736. * 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;
  42737. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42738. */
  42739. set: function (value) {
  42740. this._imageProcessingConfiguration.colorCurves = value;
  42741. },
  42742. enumerable: true,
  42743. configurable: true
  42744. });
  42745. StandardMaterial.prototype.getClassName = function () {
  42746. return "StandardMaterial";
  42747. };
  42748. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42749. get: function () {
  42750. return this._useLogarithmicDepth;
  42751. },
  42752. set: function (value) {
  42753. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42754. this._markAllSubMeshesAsMiscDirty();
  42755. },
  42756. enumerable: true,
  42757. configurable: true
  42758. });
  42759. StandardMaterial.prototype.needAlphaBlending = function () {
  42760. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42761. };
  42762. StandardMaterial.prototype.needAlphaTesting = function () {
  42763. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42764. };
  42765. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42766. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42767. };
  42768. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42769. return this._diffuseTexture;
  42770. };
  42771. /**
  42772. * Child classes can use it to update shaders
  42773. */
  42774. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42775. if (useInstances === void 0) { useInstances = false; }
  42776. if (subMesh.effect && this.isFrozen) {
  42777. if (this._wasPreviouslyReady && subMesh.effect) {
  42778. return true;
  42779. }
  42780. }
  42781. if (!subMesh._materialDefines) {
  42782. subMesh._materialDefines = new StandardMaterialDefines();
  42783. }
  42784. var scene = this.getScene();
  42785. var defines = subMesh._materialDefines;
  42786. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42787. if (defines._renderId === scene.getRenderId()) {
  42788. return true;
  42789. }
  42790. }
  42791. var engine = scene.getEngine();
  42792. // Lights
  42793. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42794. // Textures
  42795. if (defines._areTexturesDirty) {
  42796. defines._needUVs = false;
  42797. defines.MAINUV1 = false;
  42798. defines.MAINUV2 = false;
  42799. if (scene.texturesEnabled) {
  42800. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42801. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42802. return false;
  42803. }
  42804. else {
  42805. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42806. }
  42807. }
  42808. else {
  42809. defines.DIFFUSE = false;
  42810. }
  42811. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42812. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42813. return false;
  42814. }
  42815. else {
  42816. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42817. }
  42818. }
  42819. else {
  42820. defines.AMBIENT = false;
  42821. }
  42822. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42823. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42824. return false;
  42825. }
  42826. else {
  42827. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42828. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42829. }
  42830. }
  42831. else {
  42832. defines.OPACITY = false;
  42833. }
  42834. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42835. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42836. return false;
  42837. }
  42838. else {
  42839. defines._needNormals = true;
  42840. defines.REFLECTION = true;
  42841. defines.ROUGHNESS = (this._roughness > 0);
  42842. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42843. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42844. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42845. switch (this._reflectionTexture.coordinatesMode) {
  42846. case BABYLON.Texture.CUBIC_MODE:
  42847. case BABYLON.Texture.INVCUBIC_MODE:
  42848. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42849. break;
  42850. case BABYLON.Texture.EXPLICIT_MODE:
  42851. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42852. break;
  42853. case BABYLON.Texture.PLANAR_MODE:
  42854. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42855. break;
  42856. case BABYLON.Texture.PROJECTION_MODE:
  42857. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42858. break;
  42859. case BABYLON.Texture.SKYBOX_MODE:
  42860. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42861. break;
  42862. case BABYLON.Texture.SPHERICAL_MODE:
  42863. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42864. break;
  42865. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42866. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42867. break;
  42868. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42869. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42870. break;
  42871. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42872. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42873. break;
  42874. }
  42875. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42876. }
  42877. }
  42878. else {
  42879. defines.REFLECTION = false;
  42880. }
  42881. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42882. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42883. return false;
  42884. }
  42885. else {
  42886. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42887. }
  42888. }
  42889. else {
  42890. defines.EMISSIVE = false;
  42891. }
  42892. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42893. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42894. return false;
  42895. }
  42896. else {
  42897. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42898. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42899. }
  42900. }
  42901. else {
  42902. defines.LIGHTMAP = false;
  42903. }
  42904. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42905. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42906. return false;
  42907. }
  42908. else {
  42909. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42910. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42911. }
  42912. }
  42913. else {
  42914. defines.SPECULAR = false;
  42915. }
  42916. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42917. // Bump texure can not be not blocking.
  42918. if (!this._bumpTexture.isReady()) {
  42919. return false;
  42920. }
  42921. else {
  42922. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42923. defines.PARALLAX = this._useParallax;
  42924. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42925. }
  42926. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42927. }
  42928. else {
  42929. defines.BUMP = false;
  42930. }
  42931. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42932. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42933. return false;
  42934. }
  42935. else {
  42936. defines._needUVs = true;
  42937. defines.REFRACTION = true;
  42938. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42939. }
  42940. }
  42941. else {
  42942. defines.REFRACTION = false;
  42943. }
  42944. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42945. }
  42946. else {
  42947. defines.DIFFUSE = false;
  42948. defines.AMBIENT = false;
  42949. defines.OPACITY = false;
  42950. defines.REFLECTION = false;
  42951. defines.EMISSIVE = false;
  42952. defines.LIGHTMAP = false;
  42953. defines.BUMP = false;
  42954. defines.REFRACTION = false;
  42955. }
  42956. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42957. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42958. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42959. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42960. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42961. }
  42962. if (defines._areImageProcessingDirty) {
  42963. if (!this._imageProcessingConfiguration.isReady()) {
  42964. return false;
  42965. }
  42966. this._imageProcessingConfiguration.prepareDefines(defines);
  42967. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42968. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42969. }
  42970. if (defines._areFresnelDirty) {
  42971. if (StandardMaterial.FresnelEnabled) {
  42972. // Fresnel
  42973. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42974. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42975. this._reflectionFresnelParameters) {
  42976. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42977. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42978. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42979. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42980. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42981. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42982. defines._needNormals = true;
  42983. defines.FRESNEL = true;
  42984. }
  42985. }
  42986. else {
  42987. defines.FRESNEL = false;
  42988. }
  42989. }
  42990. // Misc.
  42991. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42992. // Attribs
  42993. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42994. // Values that need to be evaluated on every frame
  42995. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42996. // Get correct effect
  42997. if (defines.isDirty) {
  42998. defines.markAsProcessed();
  42999. scene.resetCachedMaterial();
  43000. // Fallbacks
  43001. var fallbacks = new BABYLON.EffectFallbacks();
  43002. if (defines.REFLECTION) {
  43003. fallbacks.addFallback(0, "REFLECTION");
  43004. }
  43005. if (defines.SPECULAR) {
  43006. fallbacks.addFallback(0, "SPECULAR");
  43007. }
  43008. if (defines.BUMP) {
  43009. fallbacks.addFallback(0, "BUMP");
  43010. }
  43011. if (defines.PARALLAX) {
  43012. fallbacks.addFallback(1, "PARALLAX");
  43013. }
  43014. if (defines.PARALLAXOCCLUSION) {
  43015. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43016. }
  43017. if (defines.SPECULAROVERALPHA) {
  43018. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43019. }
  43020. if (defines.FOG) {
  43021. fallbacks.addFallback(1, "FOG");
  43022. }
  43023. if (defines.POINTSIZE) {
  43024. fallbacks.addFallback(0, "POINTSIZE");
  43025. }
  43026. if (defines.LOGARITHMICDEPTH) {
  43027. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43028. }
  43029. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43030. if (defines.SPECULARTERM) {
  43031. fallbacks.addFallback(0, "SPECULARTERM");
  43032. }
  43033. if (defines.DIFFUSEFRESNEL) {
  43034. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43035. }
  43036. if (defines.OPACITYFRESNEL) {
  43037. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43038. }
  43039. if (defines.REFLECTIONFRESNEL) {
  43040. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43041. }
  43042. if (defines.EMISSIVEFRESNEL) {
  43043. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43044. }
  43045. if (defines.FRESNEL) {
  43046. fallbacks.addFallback(4, "FRESNEL");
  43047. }
  43048. //Attributes
  43049. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43050. if (defines.NORMAL) {
  43051. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43052. }
  43053. if (defines.UV1) {
  43054. attribs.push(BABYLON.VertexBuffer.UVKind);
  43055. }
  43056. if (defines.UV2) {
  43057. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43058. }
  43059. if (defines.VERTEXCOLOR) {
  43060. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43061. }
  43062. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43063. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43064. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43065. var shaderName = "default";
  43066. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43067. "vFogInfos", "vFogColor", "pointSize",
  43068. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43069. "mBones",
  43070. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43071. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43072. "vReflectionPosition", "vReflectionSize",
  43073. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43074. ];
  43075. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43076. var uniformBuffers = ["Material", "Scene"];
  43077. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43078. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43079. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43080. uniformsNames: uniforms,
  43081. uniformBuffersNames: uniformBuffers,
  43082. samplers: samplers,
  43083. defines: defines,
  43084. maxSimultaneousLights: this._maxSimultaneousLights
  43085. });
  43086. if (this.customShaderNameResolve) {
  43087. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43088. }
  43089. var join = defines.toString();
  43090. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43091. attributes: attribs,
  43092. uniformsNames: uniforms,
  43093. uniformBuffersNames: uniformBuffers,
  43094. samplers: samplers,
  43095. defines: join,
  43096. fallbacks: fallbacks,
  43097. onCompiled: this.onCompiled,
  43098. onError: this.onError,
  43099. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43100. }, engine), defines);
  43101. this.buildUniformLayout();
  43102. }
  43103. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43104. return false;
  43105. }
  43106. defines._renderId = scene.getRenderId();
  43107. this._wasPreviouslyReady = true;
  43108. return true;
  43109. };
  43110. StandardMaterial.prototype.buildUniformLayout = function () {
  43111. // Order is important !
  43112. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43113. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43114. this._uniformBuffer.addUniform("opacityParts", 4);
  43115. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43116. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43117. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43118. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43119. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43120. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43121. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43122. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43123. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43124. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43125. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43126. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43127. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43128. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43129. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43130. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43131. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43132. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43133. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43134. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43135. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43136. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43137. this._uniformBuffer.addUniform("specularMatrix", 16);
  43138. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43139. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43140. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43141. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43142. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43143. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43144. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43145. this._uniformBuffer.addUniform("pointSize", 1);
  43146. this._uniformBuffer.create();
  43147. };
  43148. StandardMaterial.prototype.unbind = function () {
  43149. if (this._activeEffect) {
  43150. var needFlag = false;
  43151. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43152. this._activeEffect.setTexture("reflection2DSampler", null);
  43153. needFlag = true;
  43154. }
  43155. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43156. this._activeEffect.setTexture("refraction2DSampler", null);
  43157. needFlag = true;
  43158. }
  43159. if (needFlag) {
  43160. this._markAllSubMeshesAsTexturesDirty();
  43161. }
  43162. }
  43163. _super.prototype.unbind.call(this);
  43164. };
  43165. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43166. var scene = this.getScene();
  43167. var defines = subMesh._materialDefines;
  43168. if (!defines) {
  43169. return;
  43170. }
  43171. var effect = subMesh.effect;
  43172. if (!effect) {
  43173. return;
  43174. }
  43175. this._activeEffect = effect;
  43176. // Matrices
  43177. this.bindOnlyWorldMatrix(world);
  43178. // Normal Matrix
  43179. if (defines.OBJECTSPACE_NORMALMAP) {
  43180. world.toNormalMatrix(this._normalMatrix);
  43181. this.bindOnlyNormalMatrix(this._normalMatrix);
  43182. }
  43183. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43184. // Bones
  43185. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43186. if (mustRebind) {
  43187. this._uniformBuffer.bindToEffect(effect, "Material");
  43188. this.bindViewProjection(effect);
  43189. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43190. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43191. // Fresnel
  43192. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43193. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43194. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43195. }
  43196. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43197. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43198. }
  43199. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43200. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43201. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43202. }
  43203. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43204. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43205. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43206. }
  43207. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43208. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43209. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43210. }
  43211. }
  43212. // Textures
  43213. if (scene.texturesEnabled) {
  43214. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43215. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43216. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43217. if (this._diffuseTexture.hasAlpha) {
  43218. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43219. }
  43220. }
  43221. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43222. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43223. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43224. }
  43225. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43226. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43227. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43228. }
  43229. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43230. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43231. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43232. if (this._reflectionTexture.boundingBoxSize) {
  43233. var cubeTexture = this._reflectionTexture;
  43234. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43235. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43236. }
  43237. }
  43238. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43239. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43240. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43241. }
  43242. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43243. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43244. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43245. }
  43246. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43247. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43248. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43249. }
  43250. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43251. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43252. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43253. if (scene._mirroredCameraPosition) {
  43254. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43255. }
  43256. else {
  43257. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43258. }
  43259. }
  43260. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43261. var depth = 1.0;
  43262. if (!this._refractionTexture.isCube) {
  43263. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43264. if (this._refractionTexture.depth) {
  43265. depth = this._refractionTexture.depth;
  43266. }
  43267. }
  43268. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43269. }
  43270. }
  43271. // Point size
  43272. if (this.pointsCloud) {
  43273. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43274. }
  43275. if (defines.SPECULARTERM) {
  43276. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43277. }
  43278. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43279. // Diffuse
  43280. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43281. }
  43282. // Textures
  43283. if (scene.texturesEnabled) {
  43284. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43285. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43286. }
  43287. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43288. effect.setTexture("ambientSampler", this._ambientTexture);
  43289. }
  43290. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43291. effect.setTexture("opacitySampler", this._opacityTexture);
  43292. }
  43293. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43294. if (this._reflectionTexture.isCube) {
  43295. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43296. }
  43297. else {
  43298. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43299. }
  43300. }
  43301. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43302. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43303. }
  43304. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43305. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43306. }
  43307. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43308. effect.setTexture("specularSampler", this._specularTexture);
  43309. }
  43310. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43311. effect.setTexture("bumpSampler", this._bumpTexture);
  43312. }
  43313. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43314. var depth = 1.0;
  43315. if (this._refractionTexture.isCube) {
  43316. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43317. }
  43318. else {
  43319. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43320. }
  43321. }
  43322. }
  43323. // Clip plane
  43324. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43325. // Colors
  43326. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43327. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43328. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43329. }
  43330. if (mustRebind || !this.isFrozen) {
  43331. // Lights
  43332. if (scene.lightsEnabled && !this._disableLighting) {
  43333. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43334. }
  43335. // View
  43336. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43337. this.bindView(effect);
  43338. }
  43339. // Fog
  43340. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43341. // Morph targets
  43342. if (defines.NUM_MORPH_INFLUENCERS) {
  43343. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43344. }
  43345. // Log. depth
  43346. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43347. // image processing
  43348. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43349. this._imageProcessingConfiguration.bind(this._activeEffect);
  43350. }
  43351. }
  43352. this._uniformBuffer.update();
  43353. this._afterBind(mesh, this._activeEffect);
  43354. };
  43355. StandardMaterial.prototype.getAnimatables = function () {
  43356. var results = [];
  43357. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43358. results.push(this._diffuseTexture);
  43359. }
  43360. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43361. results.push(this._ambientTexture);
  43362. }
  43363. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43364. results.push(this._opacityTexture);
  43365. }
  43366. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43367. results.push(this._reflectionTexture);
  43368. }
  43369. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43370. results.push(this._emissiveTexture);
  43371. }
  43372. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43373. results.push(this._specularTexture);
  43374. }
  43375. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43376. results.push(this._bumpTexture);
  43377. }
  43378. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43379. results.push(this._lightmapTexture);
  43380. }
  43381. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43382. results.push(this._refractionTexture);
  43383. }
  43384. return results;
  43385. };
  43386. StandardMaterial.prototype.getActiveTextures = function () {
  43387. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43388. if (this._diffuseTexture) {
  43389. activeTextures.push(this._diffuseTexture);
  43390. }
  43391. if (this._ambientTexture) {
  43392. activeTextures.push(this._ambientTexture);
  43393. }
  43394. if (this._opacityTexture) {
  43395. activeTextures.push(this._opacityTexture);
  43396. }
  43397. if (this._reflectionTexture) {
  43398. activeTextures.push(this._reflectionTexture);
  43399. }
  43400. if (this._emissiveTexture) {
  43401. activeTextures.push(this._emissiveTexture);
  43402. }
  43403. if (this._specularTexture) {
  43404. activeTextures.push(this._specularTexture);
  43405. }
  43406. if (this._bumpTexture) {
  43407. activeTextures.push(this._bumpTexture);
  43408. }
  43409. if (this._lightmapTexture) {
  43410. activeTextures.push(this._lightmapTexture);
  43411. }
  43412. if (this._refractionTexture) {
  43413. activeTextures.push(this._refractionTexture);
  43414. }
  43415. return activeTextures;
  43416. };
  43417. StandardMaterial.prototype.hasTexture = function (texture) {
  43418. if (_super.prototype.hasTexture.call(this, texture)) {
  43419. return true;
  43420. }
  43421. if (this._diffuseTexture === texture) {
  43422. return true;
  43423. }
  43424. if (this._ambientTexture === texture) {
  43425. return true;
  43426. }
  43427. if (this._opacityTexture === texture) {
  43428. return true;
  43429. }
  43430. if (this._reflectionTexture === texture) {
  43431. return true;
  43432. }
  43433. if (this._emissiveTexture === texture) {
  43434. return true;
  43435. }
  43436. if (this._specularTexture === texture) {
  43437. return true;
  43438. }
  43439. if (this._bumpTexture === texture) {
  43440. return true;
  43441. }
  43442. if (this._lightmapTexture === texture) {
  43443. return true;
  43444. }
  43445. if (this._refractionTexture === texture) {
  43446. return true;
  43447. }
  43448. return false;
  43449. };
  43450. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43451. if (forceDisposeTextures) {
  43452. if (this._diffuseTexture) {
  43453. this._diffuseTexture.dispose();
  43454. }
  43455. if (this._ambientTexture) {
  43456. this._ambientTexture.dispose();
  43457. }
  43458. if (this._opacityTexture) {
  43459. this._opacityTexture.dispose();
  43460. }
  43461. if (this._reflectionTexture) {
  43462. this._reflectionTexture.dispose();
  43463. }
  43464. if (this._emissiveTexture) {
  43465. this._emissiveTexture.dispose();
  43466. }
  43467. if (this._specularTexture) {
  43468. this._specularTexture.dispose();
  43469. }
  43470. if (this._bumpTexture) {
  43471. this._bumpTexture.dispose();
  43472. }
  43473. if (this._lightmapTexture) {
  43474. this._lightmapTexture.dispose();
  43475. }
  43476. if (this._refractionTexture) {
  43477. this._refractionTexture.dispose();
  43478. }
  43479. }
  43480. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43481. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43482. }
  43483. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43484. };
  43485. StandardMaterial.prototype.clone = function (name) {
  43486. var _this = this;
  43487. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43488. result.name = name;
  43489. result.id = name;
  43490. return result;
  43491. };
  43492. StandardMaterial.prototype.serialize = function () {
  43493. return BABYLON.SerializationHelper.Serialize(this);
  43494. };
  43495. // Statics
  43496. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43497. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43498. };
  43499. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43500. get: function () {
  43501. return StandardMaterial._DiffuseTextureEnabled;
  43502. },
  43503. set: function (value) {
  43504. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43505. return;
  43506. }
  43507. StandardMaterial._DiffuseTextureEnabled = value;
  43508. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43509. },
  43510. enumerable: true,
  43511. configurable: true
  43512. });
  43513. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43514. get: function () {
  43515. return StandardMaterial._AmbientTextureEnabled;
  43516. },
  43517. set: function (value) {
  43518. if (StandardMaterial._AmbientTextureEnabled === value) {
  43519. return;
  43520. }
  43521. StandardMaterial._AmbientTextureEnabled = value;
  43522. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43523. },
  43524. enumerable: true,
  43525. configurable: true
  43526. });
  43527. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43528. get: function () {
  43529. return StandardMaterial._OpacityTextureEnabled;
  43530. },
  43531. set: function (value) {
  43532. if (StandardMaterial._OpacityTextureEnabled === value) {
  43533. return;
  43534. }
  43535. StandardMaterial._OpacityTextureEnabled = value;
  43536. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43537. },
  43538. enumerable: true,
  43539. configurable: true
  43540. });
  43541. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43542. get: function () {
  43543. return StandardMaterial._ReflectionTextureEnabled;
  43544. },
  43545. set: function (value) {
  43546. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43547. return;
  43548. }
  43549. StandardMaterial._ReflectionTextureEnabled = value;
  43550. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43551. },
  43552. enumerable: true,
  43553. configurable: true
  43554. });
  43555. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43556. get: function () {
  43557. return StandardMaterial._EmissiveTextureEnabled;
  43558. },
  43559. set: function (value) {
  43560. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43561. return;
  43562. }
  43563. StandardMaterial._EmissiveTextureEnabled = value;
  43564. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43565. },
  43566. enumerable: true,
  43567. configurable: true
  43568. });
  43569. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43570. get: function () {
  43571. return StandardMaterial._SpecularTextureEnabled;
  43572. },
  43573. set: function (value) {
  43574. if (StandardMaterial._SpecularTextureEnabled === value) {
  43575. return;
  43576. }
  43577. StandardMaterial._SpecularTextureEnabled = value;
  43578. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43579. },
  43580. enumerable: true,
  43581. configurable: true
  43582. });
  43583. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43584. get: function () {
  43585. return StandardMaterial._BumpTextureEnabled;
  43586. },
  43587. set: function (value) {
  43588. if (StandardMaterial._BumpTextureEnabled === value) {
  43589. return;
  43590. }
  43591. StandardMaterial._BumpTextureEnabled = value;
  43592. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43593. },
  43594. enumerable: true,
  43595. configurable: true
  43596. });
  43597. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43598. get: function () {
  43599. return StandardMaterial._LightmapTextureEnabled;
  43600. },
  43601. set: function (value) {
  43602. if (StandardMaterial._LightmapTextureEnabled === value) {
  43603. return;
  43604. }
  43605. StandardMaterial._LightmapTextureEnabled = value;
  43606. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43607. },
  43608. enumerable: true,
  43609. configurable: true
  43610. });
  43611. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43612. get: function () {
  43613. return StandardMaterial._RefractionTextureEnabled;
  43614. },
  43615. set: function (value) {
  43616. if (StandardMaterial._RefractionTextureEnabled === value) {
  43617. return;
  43618. }
  43619. StandardMaterial._RefractionTextureEnabled = value;
  43620. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43621. },
  43622. enumerable: true,
  43623. configurable: true
  43624. });
  43625. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43626. get: function () {
  43627. return StandardMaterial._ColorGradingTextureEnabled;
  43628. },
  43629. set: function (value) {
  43630. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43631. return;
  43632. }
  43633. StandardMaterial._ColorGradingTextureEnabled = value;
  43634. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43635. },
  43636. enumerable: true,
  43637. configurable: true
  43638. });
  43639. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43640. get: function () {
  43641. return StandardMaterial._FresnelEnabled;
  43642. },
  43643. set: function (value) {
  43644. if (StandardMaterial._FresnelEnabled === value) {
  43645. return;
  43646. }
  43647. StandardMaterial._FresnelEnabled = value;
  43648. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43649. },
  43650. enumerable: true,
  43651. configurable: true
  43652. });
  43653. // Flags used to enable or disable a type of texture for all Standard Materials
  43654. StandardMaterial._DiffuseTextureEnabled = true;
  43655. StandardMaterial._AmbientTextureEnabled = true;
  43656. StandardMaterial._OpacityTextureEnabled = true;
  43657. StandardMaterial._ReflectionTextureEnabled = true;
  43658. StandardMaterial._EmissiveTextureEnabled = true;
  43659. StandardMaterial._SpecularTextureEnabled = true;
  43660. StandardMaterial._BumpTextureEnabled = true;
  43661. StandardMaterial._LightmapTextureEnabled = true;
  43662. StandardMaterial._RefractionTextureEnabled = true;
  43663. StandardMaterial._ColorGradingTextureEnabled = true;
  43664. StandardMaterial._FresnelEnabled = true;
  43665. __decorate([
  43666. BABYLON.serializeAsTexture("diffuseTexture")
  43667. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43668. __decorate([
  43669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43670. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43671. __decorate([
  43672. BABYLON.serializeAsTexture("ambientTexture")
  43673. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43674. __decorate([
  43675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43676. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43677. __decorate([
  43678. BABYLON.serializeAsTexture("opacityTexture")
  43679. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43680. __decorate([
  43681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43682. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43683. __decorate([
  43684. BABYLON.serializeAsTexture("reflectionTexture")
  43685. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43686. __decorate([
  43687. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43688. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43689. __decorate([
  43690. BABYLON.serializeAsTexture("emissiveTexture")
  43691. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43692. __decorate([
  43693. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43694. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43695. __decorate([
  43696. BABYLON.serializeAsTexture("specularTexture")
  43697. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43698. __decorate([
  43699. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43700. ], StandardMaterial.prototype, "specularTexture", void 0);
  43701. __decorate([
  43702. BABYLON.serializeAsTexture("bumpTexture")
  43703. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43704. __decorate([
  43705. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43706. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43707. __decorate([
  43708. BABYLON.serializeAsTexture("lightmapTexture")
  43709. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43710. __decorate([
  43711. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43712. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43713. __decorate([
  43714. BABYLON.serializeAsTexture("refractionTexture")
  43715. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43716. __decorate([
  43717. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43718. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43719. __decorate([
  43720. BABYLON.serializeAsColor3("ambient")
  43721. ], StandardMaterial.prototype, "ambientColor", void 0);
  43722. __decorate([
  43723. BABYLON.serializeAsColor3("diffuse")
  43724. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43725. __decorate([
  43726. BABYLON.serializeAsColor3("specular")
  43727. ], StandardMaterial.prototype, "specularColor", void 0);
  43728. __decorate([
  43729. BABYLON.serializeAsColor3("emissive")
  43730. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43731. __decorate([
  43732. BABYLON.serialize()
  43733. ], StandardMaterial.prototype, "specularPower", void 0);
  43734. __decorate([
  43735. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43736. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43737. __decorate([
  43738. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43739. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43740. __decorate([
  43741. BABYLON.serialize("useEmissiveAsIllumination")
  43742. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43743. __decorate([
  43744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43745. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43746. __decorate([
  43747. BABYLON.serialize("linkEmissiveWithDiffuse")
  43748. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43749. __decorate([
  43750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43751. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43752. __decorate([
  43753. BABYLON.serialize("useSpecularOverAlpha")
  43754. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43755. __decorate([
  43756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43757. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43758. __decorate([
  43759. BABYLON.serialize("useReflectionOverAlpha")
  43760. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43761. __decorate([
  43762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43763. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43764. __decorate([
  43765. BABYLON.serialize("disableLighting")
  43766. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43767. __decorate([
  43768. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43769. ], StandardMaterial.prototype, "disableLighting", void 0);
  43770. __decorate([
  43771. BABYLON.serialize("useObjectSpaceNormalMap")
  43772. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43773. __decorate([
  43774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43775. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43776. __decorate([
  43777. BABYLON.serialize("useParallax")
  43778. ], StandardMaterial.prototype, "_useParallax", void 0);
  43779. __decorate([
  43780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43781. ], StandardMaterial.prototype, "useParallax", void 0);
  43782. __decorate([
  43783. BABYLON.serialize("useParallaxOcclusion")
  43784. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43785. __decorate([
  43786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43787. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43788. __decorate([
  43789. BABYLON.serialize()
  43790. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43791. __decorate([
  43792. BABYLON.serialize("roughness")
  43793. ], StandardMaterial.prototype, "_roughness", void 0);
  43794. __decorate([
  43795. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43796. ], StandardMaterial.prototype, "roughness", void 0);
  43797. __decorate([
  43798. BABYLON.serialize()
  43799. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43800. __decorate([
  43801. BABYLON.serialize()
  43802. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43803. __decorate([
  43804. BABYLON.serialize()
  43805. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43806. __decorate([
  43807. BABYLON.serialize("useLightmapAsShadowmap")
  43808. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43809. __decorate([
  43810. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43811. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43812. __decorate([
  43813. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43814. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43815. __decorate([
  43816. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43817. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43818. __decorate([
  43819. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43820. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43821. __decorate([
  43822. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43823. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43824. __decorate([
  43825. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43826. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43827. __decorate([
  43828. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43829. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43830. __decorate([
  43831. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43832. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43833. __decorate([
  43834. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43835. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43836. __decorate([
  43837. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43838. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43839. __decorate([
  43840. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43841. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43842. __decorate([
  43843. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43844. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43845. __decorate([
  43846. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43847. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43848. __decorate([
  43849. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43850. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43851. __decorate([
  43852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43853. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43854. __decorate([
  43855. BABYLON.serialize("maxSimultaneousLights")
  43856. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43857. __decorate([
  43858. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43859. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43860. __decorate([
  43861. BABYLON.serialize("invertNormalMapX")
  43862. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43863. __decorate([
  43864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43865. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43866. __decorate([
  43867. BABYLON.serialize("invertNormalMapY")
  43868. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43869. __decorate([
  43870. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43871. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43872. __decorate([
  43873. BABYLON.serialize("twoSidedLighting")
  43874. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43875. __decorate([
  43876. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43877. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43878. __decorate([
  43879. BABYLON.serialize()
  43880. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43881. return StandardMaterial;
  43882. }(BABYLON.PushMaterial));
  43883. BABYLON.StandardMaterial = StandardMaterial;
  43884. })(BABYLON || (BABYLON = {}));
  43885. //# sourceMappingURL=babylon.standardMaterial.js.map
  43886. var BABYLON;
  43887. (function (BABYLON) {
  43888. /**
  43889. * Manages the defines for the PBR Material.
  43890. * @ignoreChildren
  43891. */
  43892. var PBRMaterialDefines = /** @class */ (function (_super) {
  43893. __extends(PBRMaterialDefines, _super);
  43894. /**
  43895. * Initializes the PBR Material defines.
  43896. */
  43897. function PBRMaterialDefines() {
  43898. var _this = _super.call(this) || this;
  43899. _this.PBR = true;
  43900. _this.MAINUV1 = false;
  43901. _this.MAINUV2 = false;
  43902. _this.UV1 = false;
  43903. _this.UV2 = false;
  43904. _this.ALBEDO = false;
  43905. _this.ALBEDODIRECTUV = 0;
  43906. _this.VERTEXCOLOR = false;
  43907. _this.AMBIENT = false;
  43908. _this.AMBIENTDIRECTUV = 0;
  43909. _this.AMBIENTINGRAYSCALE = false;
  43910. _this.OPACITY = false;
  43911. _this.VERTEXALPHA = false;
  43912. _this.OPACITYDIRECTUV = 0;
  43913. _this.OPACITYRGB = false;
  43914. _this.ALPHATEST = false;
  43915. _this.DEPTHPREPASS = false;
  43916. _this.ALPHABLEND = false;
  43917. _this.ALPHAFROMALBEDO = false;
  43918. _this.ALPHATESTVALUE = "0.5";
  43919. _this.SPECULAROVERALPHA = false;
  43920. _this.RADIANCEOVERALPHA = false;
  43921. _this.ALPHAFRESNEL = false;
  43922. _this.LINEARALPHAFRESNEL = false;
  43923. _this.PREMULTIPLYALPHA = false;
  43924. _this.EMISSIVE = false;
  43925. _this.EMISSIVEDIRECTUV = 0;
  43926. _this.REFLECTIVITY = false;
  43927. _this.REFLECTIVITYDIRECTUV = 0;
  43928. _this.SPECULARTERM = false;
  43929. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43930. _this.MICROSURFACEAUTOMATIC = false;
  43931. _this.LODBASEDMICROSFURACE = false;
  43932. _this.MICROSURFACEMAP = false;
  43933. _this.MICROSURFACEMAPDIRECTUV = 0;
  43934. _this.METALLICWORKFLOW = false;
  43935. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43936. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43937. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43938. _this.AOSTOREINMETALMAPRED = false;
  43939. _this.ENVIRONMENTBRDF = false;
  43940. _this.NORMAL = false;
  43941. _this.TANGENT = false;
  43942. _this.BUMP = false;
  43943. _this.BUMPDIRECTUV = 0;
  43944. _this.OBJECTSPACE_NORMALMAP = false;
  43945. _this.PARALLAX = false;
  43946. _this.PARALLAXOCCLUSION = false;
  43947. _this.NORMALXYSCALE = true;
  43948. _this.LIGHTMAP = false;
  43949. _this.LIGHTMAPDIRECTUV = 0;
  43950. _this.USELIGHTMAPASSHADOWMAP = false;
  43951. _this.GAMMALIGHTMAP = false;
  43952. _this.REFLECTION = false;
  43953. _this.REFLECTIONMAP_3D = false;
  43954. _this.REFLECTIONMAP_SPHERICAL = false;
  43955. _this.REFLECTIONMAP_PLANAR = false;
  43956. _this.REFLECTIONMAP_CUBIC = false;
  43957. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43958. _this.REFLECTIONMAP_PROJECTION = false;
  43959. _this.REFLECTIONMAP_SKYBOX = false;
  43960. _this.REFLECTIONMAP_EXPLICIT = false;
  43961. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43962. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43963. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43964. _this.INVERTCUBICMAP = false;
  43965. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43966. _this.USESPHERICALINVERTEX = false;
  43967. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43968. _this.LODINREFLECTIONALPHA = false;
  43969. _this.GAMMAREFLECTION = false;
  43970. _this.RADIANCEOCCLUSION = false;
  43971. _this.HORIZONOCCLUSION = false;
  43972. _this.REFRACTION = false;
  43973. _this.REFRACTIONMAP_3D = false;
  43974. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43975. _this.LODINREFRACTIONALPHA = false;
  43976. _this.GAMMAREFRACTION = false;
  43977. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43978. _this.INSTANCES = false;
  43979. _this.NUM_BONE_INFLUENCERS = 0;
  43980. _this.BonesPerMesh = 0;
  43981. _this.NONUNIFORMSCALING = false;
  43982. _this.MORPHTARGETS = false;
  43983. _this.MORPHTARGETS_NORMAL = false;
  43984. _this.MORPHTARGETS_TANGENT = false;
  43985. _this.NUM_MORPH_INFLUENCERS = 0;
  43986. _this.IMAGEPROCESSING = false;
  43987. _this.VIGNETTE = false;
  43988. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43989. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43990. _this.TONEMAPPING = false;
  43991. _this.CONTRAST = false;
  43992. _this.COLORCURVES = false;
  43993. _this.COLORGRADING = false;
  43994. _this.COLORGRADING3D = false;
  43995. _this.SAMPLER3DGREENDEPTH = false;
  43996. _this.SAMPLER3DBGRMAP = false;
  43997. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43998. _this.EXPOSURE = false;
  43999. _this.USEPHYSICALLIGHTFALLOFF = false;
  44000. _this.TWOSIDEDLIGHTING = false;
  44001. _this.SHADOWFLOAT = false;
  44002. _this.CLIPPLANE = false;
  44003. _this.POINTSIZE = false;
  44004. _this.FOG = false;
  44005. _this.LOGARITHMICDEPTH = false;
  44006. _this.FORCENORMALFORWARD = false;
  44007. _this.GEOMETRYAA = false;
  44008. _this.UNLIT = false;
  44009. _this.rebuild();
  44010. return _this;
  44011. }
  44012. /**
  44013. * Resets the PBR Material defines.
  44014. */
  44015. PBRMaterialDefines.prototype.reset = function () {
  44016. _super.prototype.reset.call(this);
  44017. this.ALPHATESTVALUE = "0.5";
  44018. this.PBR = true;
  44019. };
  44020. return PBRMaterialDefines;
  44021. }(BABYLON.MaterialDefines));
  44022. /**
  44023. * The Physically based material base class of BJS.
  44024. *
  44025. * This offers the main features of a standard PBR material.
  44026. * For more information, please refer to the documentation :
  44027. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44028. */
  44029. var PBRBaseMaterial = /** @class */ (function (_super) {
  44030. __extends(PBRBaseMaterial, _super);
  44031. /**
  44032. * Instantiates a new PBRMaterial instance.
  44033. *
  44034. * @param name The material name
  44035. * @param scene The scene the material will be use in.
  44036. */
  44037. function PBRBaseMaterial(name, scene) {
  44038. var _this = _super.call(this, name, scene) || this;
  44039. /**
  44040. * Intensity of the direct lights e.g. the four lights available in your scene.
  44041. * This impacts both the direct diffuse and specular highlights.
  44042. */
  44043. _this._directIntensity = 1.0;
  44044. /**
  44045. * Intensity of the emissive part of the material.
  44046. * This helps controlling the emissive effect without modifying the emissive color.
  44047. */
  44048. _this._emissiveIntensity = 1.0;
  44049. /**
  44050. * Intensity of the environment e.g. how much the environment will light the object
  44051. * either through harmonics for rough material or through the refelction for shiny ones.
  44052. */
  44053. _this._environmentIntensity = 1.0;
  44054. /**
  44055. * This is a special control allowing the reduction of the specular highlights coming from the
  44056. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44057. */
  44058. _this._specularIntensity = 1.0;
  44059. /**
  44060. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44061. */
  44062. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44063. /**
  44064. * Debug Control allowing disabling the bump map on this material.
  44065. */
  44066. _this._disableBumpMap = false;
  44067. /**
  44068. * AKA Occlusion Texture Intensity in other nomenclature.
  44069. */
  44070. _this._ambientTextureStrength = 1.0;
  44071. /**
  44072. * The color of a material in ambient lighting.
  44073. */
  44074. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44075. /**
  44076. * AKA Diffuse Color in other nomenclature.
  44077. */
  44078. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44079. /**
  44080. * AKA Specular Color in other nomenclature.
  44081. */
  44082. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44083. /**
  44084. * The color applied when light is reflected from a material.
  44085. */
  44086. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44087. /**
  44088. * The color applied when light is emitted from a material.
  44089. */
  44090. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44091. /**
  44092. * AKA Glossiness in other nomenclature.
  44093. */
  44094. _this._microSurface = 0.9;
  44095. /**
  44096. * source material index of refraction (IOR)' / 'destination material IOR.
  44097. */
  44098. _this._indexOfRefraction = 0.66;
  44099. /**
  44100. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44101. */
  44102. _this._invertRefractionY = false;
  44103. /**
  44104. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44105. * Materials half opaque for instance using refraction could benefit from this control.
  44106. */
  44107. _this._linkRefractionWithTransparency = false;
  44108. /**
  44109. * Specifies that the material will use the light map as a show map.
  44110. */
  44111. _this._useLightmapAsShadowmap = false;
  44112. /**
  44113. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44114. * makes the reflect vector face the model (under horizon).
  44115. */
  44116. _this._useHorizonOcclusion = true;
  44117. /**
  44118. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44119. * too much the area relying on ambient texture to define their ambient occlusion.
  44120. */
  44121. _this._useRadianceOcclusion = true;
  44122. /**
  44123. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44124. */
  44125. _this._useAlphaFromAlbedoTexture = false;
  44126. /**
  44127. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44128. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44129. */
  44130. _this._useSpecularOverAlpha = true;
  44131. /**
  44132. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44133. */
  44134. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44135. /**
  44136. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44137. */
  44138. _this._useRoughnessFromMetallicTextureAlpha = true;
  44139. /**
  44140. * Specifies if the metallic texture contains the roughness information in its green channel.
  44141. */
  44142. _this._useRoughnessFromMetallicTextureGreen = false;
  44143. /**
  44144. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44145. */
  44146. _this._useMetallnessFromMetallicTextureBlue = false;
  44147. /**
  44148. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44149. */
  44150. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44151. /**
  44152. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44153. */
  44154. _this._useAmbientInGrayScale = false;
  44155. /**
  44156. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44157. * The material will try to infer what glossiness each pixel should be.
  44158. */
  44159. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44160. /**
  44161. * BJS is using an harcoded light falloff based on a manually sets up range.
  44162. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44163. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44164. */
  44165. _this._usePhysicalLightFalloff = true;
  44166. /**
  44167. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44168. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44169. */
  44170. _this._useRadianceOverAlpha = true;
  44171. /**
  44172. * Allows using an object space normal map (instead of tangent space).
  44173. */
  44174. _this._useObjectSpaceNormalMap = false;
  44175. /**
  44176. * Allows using the bump map in parallax mode.
  44177. */
  44178. _this._useParallax = false;
  44179. /**
  44180. * Allows using the bump map in parallax occlusion mode.
  44181. */
  44182. _this._useParallaxOcclusion = false;
  44183. /**
  44184. * Controls the scale bias of the parallax mode.
  44185. */
  44186. _this._parallaxScaleBias = 0.05;
  44187. /**
  44188. * If sets to true, disables all the lights affecting the material.
  44189. */
  44190. _this._disableLighting = false;
  44191. /**
  44192. * Number of Simultaneous lights allowed on the material.
  44193. */
  44194. _this._maxSimultaneousLights = 4;
  44195. /**
  44196. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44197. */
  44198. _this._invertNormalMapX = false;
  44199. /**
  44200. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44201. */
  44202. _this._invertNormalMapY = false;
  44203. /**
  44204. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44205. */
  44206. _this._twoSidedLighting = false;
  44207. /**
  44208. * Defines the alpha limits in alpha test mode.
  44209. */
  44210. _this._alphaCutOff = 0.4;
  44211. /**
  44212. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44213. */
  44214. _this._forceAlphaTest = false;
  44215. /**
  44216. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44217. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44218. */
  44219. _this._useAlphaFresnel = false;
  44220. /**
  44221. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44222. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44223. */
  44224. _this._useLinearAlphaFresnel = false;
  44225. /**
  44226. * The transparency mode of the material.
  44227. */
  44228. _this._transparencyMode = null;
  44229. /**
  44230. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44231. * from cos thetav and roughness:
  44232. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44233. */
  44234. _this._environmentBRDFTexture = null;
  44235. /**
  44236. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44237. */
  44238. _this._forceIrradianceInFragment = false;
  44239. /**
  44240. * Force normal to face away from face.
  44241. */
  44242. _this._forceNormalForward = false;
  44243. /**
  44244. * Enables specular anti aliasing in the PBR shader.
  44245. * It will both interacts on the Geometry for analytical and IBL lighting.
  44246. * It also prefilter the roughness map based on the bump values.
  44247. */
  44248. _this._enableSpecularAntiAliasing = false;
  44249. /**
  44250. * Stores the available render targets.
  44251. */
  44252. _this._renderTargets = new BABYLON.SmartArray(16);
  44253. /**
  44254. * Sets the global ambient color for the material used in lighting calculations.
  44255. */
  44256. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44257. /**
  44258. * If set to true, no lighting calculations will be applied.
  44259. */
  44260. _this._unlit = false;
  44261. // Setup the default processing configuration to the scene.
  44262. _this._attachImageProcessingConfiguration(null);
  44263. _this.getRenderTargetTextures = function () {
  44264. _this._renderTargets.reset();
  44265. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44266. _this._renderTargets.push(_this._reflectionTexture);
  44267. }
  44268. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44269. _this._renderTargets.push(_this._refractionTexture);
  44270. }
  44271. return _this._renderTargets;
  44272. };
  44273. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44274. return _this;
  44275. }
  44276. /**
  44277. * Attaches a new image processing configuration to the PBR Material.
  44278. * @param configuration
  44279. */
  44280. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44281. var _this = this;
  44282. if (configuration === this._imageProcessingConfiguration) {
  44283. return;
  44284. }
  44285. // Detaches observer.
  44286. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44287. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44288. }
  44289. // Pick the scene configuration if needed.
  44290. if (!configuration) {
  44291. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44292. }
  44293. else {
  44294. this._imageProcessingConfiguration = configuration;
  44295. }
  44296. // Attaches observer.
  44297. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44298. _this._markAllSubMeshesAsImageProcessingDirty();
  44299. });
  44300. };
  44301. /**
  44302. * Gets the name of the material class.
  44303. */
  44304. PBRBaseMaterial.prototype.getClassName = function () {
  44305. return "PBRBaseMaterial";
  44306. };
  44307. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44308. /**
  44309. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44310. */
  44311. get: function () {
  44312. return this._useLogarithmicDepth;
  44313. },
  44314. /**
  44315. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44316. */
  44317. set: function (value) {
  44318. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44319. },
  44320. enumerable: true,
  44321. configurable: true
  44322. });
  44323. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44324. /**
  44325. * Gets the current transparency mode.
  44326. */
  44327. get: function () {
  44328. return this._transparencyMode;
  44329. },
  44330. /**
  44331. * Sets the transparency mode of the material.
  44332. */
  44333. set: function (value) {
  44334. if (this._transparencyMode === value) {
  44335. return;
  44336. }
  44337. this._transparencyMode = value;
  44338. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44339. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44340. },
  44341. enumerable: true,
  44342. configurable: true
  44343. });
  44344. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44345. /**
  44346. * Returns true if alpha blending should be disabled.
  44347. */
  44348. get: function () {
  44349. return (this._linkRefractionWithTransparency ||
  44350. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44351. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44352. },
  44353. enumerable: true,
  44354. configurable: true
  44355. });
  44356. /**
  44357. * Specifies whether or not this material should be rendered in alpha blend mode.
  44358. */
  44359. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44360. if (this._disableAlphaBlending) {
  44361. return false;
  44362. }
  44363. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44364. };
  44365. /**
  44366. * Specifies if the mesh will require alpha blending.
  44367. * @param mesh - BJS mesh.
  44368. */
  44369. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44370. if (this._disableAlphaBlending) {
  44371. return false;
  44372. }
  44373. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44374. };
  44375. /**
  44376. * Specifies whether or not this material should be rendered in alpha test mode.
  44377. */
  44378. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44379. if (this._forceAlphaTest) {
  44380. return true;
  44381. }
  44382. if (this._linkRefractionWithTransparency) {
  44383. return false;
  44384. }
  44385. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44386. };
  44387. /**
  44388. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44389. */
  44390. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44391. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44392. };
  44393. /**
  44394. * Gets the texture used for the alpha test.
  44395. */
  44396. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44397. return this._albedoTexture;
  44398. };
  44399. /**
  44400. * Specifies that the submesh is ready to be used.
  44401. * @param mesh - BJS mesh.
  44402. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44403. * @param useInstances - Specifies that instances should be used.
  44404. * @returns - boolean indicating that the submesh is ready or not.
  44405. */
  44406. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44407. if (subMesh.effect && this.isFrozen) {
  44408. if (this._wasPreviouslyReady) {
  44409. return true;
  44410. }
  44411. }
  44412. if (!subMesh._materialDefines) {
  44413. subMesh._materialDefines = new PBRMaterialDefines();
  44414. }
  44415. var defines = subMesh._materialDefines;
  44416. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44417. if (defines._renderId === this.getScene().getRenderId()) {
  44418. return true;
  44419. }
  44420. }
  44421. var scene = this.getScene();
  44422. var engine = scene.getEngine();
  44423. if (defines._areTexturesDirty) {
  44424. if (scene.texturesEnabled) {
  44425. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44426. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44427. return false;
  44428. }
  44429. }
  44430. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44431. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44432. return false;
  44433. }
  44434. }
  44435. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44436. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44437. return false;
  44438. }
  44439. }
  44440. var reflectionTexture = this._getReflectionTexture();
  44441. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44442. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44443. return false;
  44444. }
  44445. }
  44446. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44447. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44448. return false;
  44449. }
  44450. }
  44451. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44452. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44453. return false;
  44454. }
  44455. }
  44456. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44457. if (this._metallicTexture) {
  44458. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44459. return false;
  44460. }
  44461. }
  44462. else if (this._reflectivityTexture) {
  44463. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44464. return false;
  44465. }
  44466. }
  44467. if (this._microSurfaceTexture) {
  44468. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44469. return false;
  44470. }
  44471. }
  44472. }
  44473. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44474. // Bump texture cannot be not blocking.
  44475. if (!this._bumpTexture.isReady()) {
  44476. return false;
  44477. }
  44478. }
  44479. var refractionTexture = this._getRefractionTexture();
  44480. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44481. if (!refractionTexture.isReadyOrNotBlocking()) {
  44482. return false;
  44483. }
  44484. }
  44485. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44486. // This is blocking.
  44487. if (!this._environmentBRDFTexture.isReady()) {
  44488. return false;
  44489. }
  44490. }
  44491. }
  44492. }
  44493. if (defines._areImageProcessingDirty) {
  44494. if (!this._imageProcessingConfiguration.isReady()) {
  44495. return false;
  44496. }
  44497. }
  44498. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44499. mesh.createNormals(true);
  44500. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44501. }
  44502. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44503. if (effect) {
  44504. scene.resetCachedMaterial();
  44505. subMesh.setEffect(effect, defines);
  44506. this.buildUniformLayout();
  44507. }
  44508. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44509. return false;
  44510. }
  44511. defines._renderId = scene.getRenderId();
  44512. this._wasPreviouslyReady = true;
  44513. return true;
  44514. };
  44515. /**
  44516. * Specifies if the material uses metallic roughness workflow.
  44517. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44518. */
  44519. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44520. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44521. return true;
  44522. }
  44523. return false;
  44524. };
  44525. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44526. if (onCompiled === void 0) { onCompiled = null; }
  44527. if (onError === void 0) { onError = null; }
  44528. if (useInstances === void 0) { useInstances = null; }
  44529. if (useClipPlane === void 0) { useClipPlane = null; }
  44530. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44531. if (!defines.isDirty) {
  44532. return null;
  44533. }
  44534. defines.markAsProcessed();
  44535. var scene = this.getScene();
  44536. var engine = scene.getEngine();
  44537. // Fallbacks
  44538. var fallbacks = new BABYLON.EffectFallbacks();
  44539. var fallbackRank = 0;
  44540. if (defines.USESPHERICALINVERTEX) {
  44541. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44542. }
  44543. if (defines.FOG) {
  44544. fallbacks.addFallback(fallbackRank, "FOG");
  44545. }
  44546. if (defines.POINTSIZE) {
  44547. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44548. }
  44549. if (defines.LOGARITHMICDEPTH) {
  44550. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44551. }
  44552. if (defines.PARALLAX) {
  44553. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44554. }
  44555. if (defines.PARALLAXOCCLUSION) {
  44556. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44557. }
  44558. if (defines.ENVIRONMENTBRDF) {
  44559. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44560. }
  44561. if (defines.TANGENT) {
  44562. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44563. }
  44564. if (defines.BUMP) {
  44565. fallbacks.addFallback(fallbackRank++, "BUMP");
  44566. }
  44567. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44568. if (defines.SPECULARTERM) {
  44569. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44570. }
  44571. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44572. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44573. }
  44574. if (defines.LIGHTMAP) {
  44575. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44576. }
  44577. if (defines.NORMAL) {
  44578. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44579. }
  44580. if (defines.AMBIENT) {
  44581. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44582. }
  44583. if (defines.EMISSIVE) {
  44584. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44585. }
  44586. if (defines.VERTEXCOLOR) {
  44587. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44588. }
  44589. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44590. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44591. }
  44592. if (defines.MORPHTARGETS) {
  44593. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44594. }
  44595. //Attributes
  44596. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44597. if (defines.NORMAL) {
  44598. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44599. }
  44600. if (defines.TANGENT) {
  44601. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44602. }
  44603. if (defines.UV1) {
  44604. attribs.push(BABYLON.VertexBuffer.UVKind);
  44605. }
  44606. if (defines.UV2) {
  44607. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44608. }
  44609. if (defines.VERTEXCOLOR) {
  44610. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44611. }
  44612. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44613. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44614. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44615. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44616. "vFogInfos", "vFogColor", "pointSize",
  44617. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44618. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44619. "mBones",
  44620. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44621. "vLightingIntensity",
  44622. "logarithmicDepthConstant",
  44623. "vSphericalX", "vSphericalY", "vSphericalZ",
  44624. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44625. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44626. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44627. "vTangentSpaceParams"
  44628. ];
  44629. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44630. "bumpSampler", "lightmapSampler", "opacitySampler",
  44631. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44632. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44633. "microSurfaceSampler", "environmentBrdfSampler"];
  44634. var uniformBuffers = ["Material", "Scene"];
  44635. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44636. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44637. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44638. uniformsNames: uniforms,
  44639. uniformBuffersNames: uniformBuffers,
  44640. samplers: samplers,
  44641. defines: defines,
  44642. maxSimultaneousLights: this._maxSimultaneousLights
  44643. });
  44644. var join = defines.toString();
  44645. return engine.createEffect("pbr", {
  44646. attributes: attribs,
  44647. uniformsNames: uniforms,
  44648. uniformBuffersNames: uniformBuffers,
  44649. samplers: samplers,
  44650. defines: join,
  44651. fallbacks: fallbacks,
  44652. onCompiled: onCompiled,
  44653. onError: onError,
  44654. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44655. }, engine);
  44656. };
  44657. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44658. if (useInstances === void 0) { useInstances = null; }
  44659. if (useClipPlane === void 0) { useClipPlane = null; }
  44660. var scene = this.getScene();
  44661. var engine = scene.getEngine();
  44662. // Lights
  44663. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44664. defines._needNormals = true;
  44665. // Textures
  44666. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44667. if (defines._areTexturesDirty) {
  44668. defines._needUVs = false;
  44669. if (scene.texturesEnabled) {
  44670. if (scene.getEngine().getCaps().textureLOD) {
  44671. defines.LODBASEDMICROSFURACE = true;
  44672. }
  44673. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44674. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44675. }
  44676. else {
  44677. defines.ALBEDO = false;
  44678. }
  44679. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44680. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44681. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44682. }
  44683. else {
  44684. defines.AMBIENT = false;
  44685. }
  44686. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44687. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44688. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44689. }
  44690. else {
  44691. defines.OPACITY = false;
  44692. }
  44693. var reflectionTexture = this._getReflectionTexture();
  44694. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44695. defines.REFLECTION = true;
  44696. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44697. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44698. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44699. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44700. defines.INVERTCUBICMAP = true;
  44701. }
  44702. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44703. switch (reflectionTexture.coordinatesMode) {
  44704. case BABYLON.Texture.CUBIC_MODE:
  44705. case BABYLON.Texture.INVCUBIC_MODE:
  44706. defines.REFLECTIONMAP_CUBIC = true;
  44707. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44708. break;
  44709. case BABYLON.Texture.EXPLICIT_MODE:
  44710. defines.REFLECTIONMAP_EXPLICIT = true;
  44711. break;
  44712. case BABYLON.Texture.PLANAR_MODE:
  44713. defines.REFLECTIONMAP_PLANAR = true;
  44714. break;
  44715. case BABYLON.Texture.PROJECTION_MODE:
  44716. defines.REFLECTIONMAP_PROJECTION = true;
  44717. break;
  44718. case BABYLON.Texture.SKYBOX_MODE:
  44719. defines.REFLECTIONMAP_SKYBOX = true;
  44720. break;
  44721. case BABYLON.Texture.SPHERICAL_MODE:
  44722. defines.REFLECTIONMAP_SPHERICAL = true;
  44723. break;
  44724. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44725. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44726. break;
  44727. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44728. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44729. break;
  44730. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44731. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44732. break;
  44733. }
  44734. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44735. if (reflectionTexture.sphericalPolynomial) {
  44736. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44737. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44738. defines.USESPHERICALINVERTEX = false;
  44739. }
  44740. else {
  44741. defines.USESPHERICALINVERTEX = true;
  44742. }
  44743. }
  44744. }
  44745. }
  44746. else {
  44747. defines.REFLECTION = false;
  44748. defines.REFLECTIONMAP_3D = false;
  44749. defines.REFLECTIONMAP_SPHERICAL = false;
  44750. defines.REFLECTIONMAP_PLANAR = false;
  44751. defines.REFLECTIONMAP_CUBIC = false;
  44752. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44753. defines.REFLECTIONMAP_PROJECTION = false;
  44754. defines.REFLECTIONMAP_SKYBOX = false;
  44755. defines.REFLECTIONMAP_EXPLICIT = false;
  44756. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44757. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44758. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44759. defines.INVERTCUBICMAP = false;
  44760. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44761. defines.USESPHERICALINVERTEX = false;
  44762. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44763. defines.LODINREFLECTIONALPHA = false;
  44764. defines.GAMMAREFLECTION = false;
  44765. }
  44766. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44767. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44768. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44769. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44770. }
  44771. else {
  44772. defines.LIGHTMAP = false;
  44773. }
  44774. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44775. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44776. }
  44777. else {
  44778. defines.EMISSIVE = false;
  44779. }
  44780. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44781. if (this._metallicTexture) {
  44782. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44783. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44784. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44785. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44786. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44787. }
  44788. else if (this._reflectivityTexture) {
  44789. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44790. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44791. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44792. }
  44793. else {
  44794. defines.REFLECTIVITY = false;
  44795. }
  44796. if (this._microSurfaceTexture) {
  44797. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44798. }
  44799. else {
  44800. defines.MICROSURFACEMAP = false;
  44801. }
  44802. }
  44803. else {
  44804. defines.REFLECTIVITY = false;
  44805. defines.MICROSURFACEMAP = false;
  44806. }
  44807. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44808. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44809. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44810. defines.PARALLAX = true;
  44811. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44812. }
  44813. else {
  44814. defines.PARALLAX = false;
  44815. }
  44816. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44817. }
  44818. else {
  44819. defines.BUMP = false;
  44820. }
  44821. var refractionTexture = this._getRefractionTexture();
  44822. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44823. defines.REFRACTION = true;
  44824. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44825. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44826. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44827. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44828. if (this._linkRefractionWithTransparency) {
  44829. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44830. }
  44831. }
  44832. else {
  44833. defines.REFRACTION = false;
  44834. }
  44835. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44836. defines.ENVIRONMENTBRDF = true;
  44837. }
  44838. else {
  44839. defines.ENVIRONMENTBRDF = false;
  44840. }
  44841. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44842. defines.ALPHAFROMALBEDO = true;
  44843. }
  44844. else {
  44845. defines.ALPHAFROMALBEDO = false;
  44846. }
  44847. }
  44848. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44849. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44850. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44851. if (!this.backFaceCulling && this._twoSidedLighting) {
  44852. defines.TWOSIDEDLIGHTING = true;
  44853. }
  44854. else {
  44855. defines.TWOSIDEDLIGHTING = false;
  44856. }
  44857. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44858. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44859. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44860. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44861. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44862. defines.GEOMETRYAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44863. }
  44864. if (defines._areImageProcessingDirty) {
  44865. this._imageProcessingConfiguration.prepareDefines(defines);
  44866. }
  44867. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44868. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44869. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44870. // Misc.
  44871. if (defines._areMiscDirty) {
  44872. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44873. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44874. }
  44875. // Values that need to be evaluated on every frame
  44876. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44877. // Attribs
  44878. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44879. };
  44880. /**
  44881. * Force shader compilation
  44882. */
  44883. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44884. var _this = this;
  44885. var localOptions = __assign({ clipPlane: false }, options);
  44886. var defines = new PBRMaterialDefines();
  44887. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44888. if (effect.isReady()) {
  44889. if (onCompiled) {
  44890. onCompiled(this);
  44891. }
  44892. }
  44893. else {
  44894. effect.onCompileObservable.add(function () {
  44895. if (onCompiled) {
  44896. onCompiled(_this);
  44897. }
  44898. });
  44899. }
  44900. };
  44901. /**
  44902. * Initializes the uniform buffer layout for the shader.
  44903. */
  44904. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44905. // Order is important !
  44906. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44907. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44908. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44909. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44910. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44911. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44912. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44913. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44914. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44915. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44916. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44917. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44918. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44919. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44920. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44921. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44922. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44923. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44924. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44925. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44926. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44927. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44928. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44929. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44930. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44931. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44932. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44933. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44934. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44935. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44936. this._uniformBuffer.addUniform("pointSize", 1);
  44937. this._uniformBuffer.create();
  44938. };
  44939. /**
  44940. * Unbinds the textures.
  44941. */
  44942. PBRBaseMaterial.prototype.unbind = function () {
  44943. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44944. this._uniformBuffer.setTexture("reflectionSampler", null);
  44945. }
  44946. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44947. this._uniformBuffer.setTexture("refractionSampler", null);
  44948. }
  44949. _super.prototype.unbind.call(this);
  44950. };
  44951. /**
  44952. * Binds the submesh data.
  44953. * @param world - The world matrix.
  44954. * @param mesh - The BJS mesh.
  44955. * @param subMesh - A submesh of the BJS mesh.
  44956. */
  44957. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44958. var scene = this.getScene();
  44959. var defines = subMesh._materialDefines;
  44960. if (!defines) {
  44961. return;
  44962. }
  44963. var effect = subMesh.effect;
  44964. if (!effect) {
  44965. return;
  44966. }
  44967. this._activeEffect = effect;
  44968. // Matrices
  44969. this.bindOnlyWorldMatrix(world);
  44970. // Normal Matrix
  44971. if (defines.OBJECTSPACE_NORMALMAP) {
  44972. world.toNormalMatrix(this._normalMatrix);
  44973. this.bindOnlyNormalMatrix(this._normalMatrix);
  44974. }
  44975. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44976. // Bones
  44977. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44978. var reflectionTexture = null;
  44979. if (mustRebind) {
  44980. this._uniformBuffer.bindToEffect(effect, "Material");
  44981. this.bindViewProjection(effect);
  44982. reflectionTexture = this._getReflectionTexture();
  44983. var refractionTexture = this._getRefractionTexture();
  44984. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44985. // Texture uniforms
  44986. if (scene.texturesEnabled) {
  44987. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44988. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44989. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44990. }
  44991. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44992. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44993. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44994. }
  44995. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44996. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44997. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44998. }
  44999. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45000. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45001. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45002. if (reflectionTexture.boundingBoxSize) {
  45003. var cubeTexture = reflectionTexture;
  45004. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45005. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45006. }
  45007. var polynomials = reflectionTexture.sphericalPolynomial;
  45008. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45009. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45010. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45011. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45012. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45013. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45014. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45015. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45016. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45017. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45018. }
  45019. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45020. }
  45021. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45022. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45023. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45024. }
  45025. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45026. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45027. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45028. }
  45029. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45030. if (this._metallicTexture) {
  45031. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45032. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45033. }
  45034. else if (this._reflectivityTexture) {
  45035. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45036. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45037. }
  45038. if (this._microSurfaceTexture) {
  45039. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45040. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45041. }
  45042. }
  45043. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45044. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45045. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45046. if (scene._mirroredCameraPosition) {
  45047. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45048. }
  45049. else {
  45050. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45051. }
  45052. }
  45053. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45054. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45055. var depth = 1.0;
  45056. if (!refractionTexture.isCube) {
  45057. if (refractionTexture.depth) {
  45058. depth = refractionTexture.depth;
  45059. }
  45060. }
  45061. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45062. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45063. }
  45064. }
  45065. // Point size
  45066. if (this.pointsCloud) {
  45067. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45068. }
  45069. // Colors
  45070. if (defines.METALLICWORKFLOW) {
  45071. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45072. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45073. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45074. }
  45075. else {
  45076. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45077. }
  45078. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45079. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45080. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45081. // Misc
  45082. this._lightingInfos.x = this._directIntensity;
  45083. this._lightingInfos.y = this._emissiveIntensity;
  45084. this._lightingInfos.z = this._environmentIntensity;
  45085. this._lightingInfos.w = this._specularIntensity;
  45086. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45087. }
  45088. // Textures
  45089. if (scene.texturesEnabled) {
  45090. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45091. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45092. }
  45093. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45094. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45095. }
  45096. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45097. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45098. }
  45099. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45100. if (defines.LODBASEDMICROSFURACE) {
  45101. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45102. }
  45103. else {
  45104. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45105. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45106. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45107. }
  45108. }
  45109. if (defines.ENVIRONMENTBRDF) {
  45110. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45111. }
  45112. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45113. if (defines.LODBASEDMICROSFURACE) {
  45114. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45115. }
  45116. else {
  45117. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45118. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45119. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45120. }
  45121. }
  45122. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45123. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45124. }
  45125. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45126. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45127. }
  45128. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45129. if (this._metallicTexture) {
  45130. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45131. }
  45132. else if (this._reflectivityTexture) {
  45133. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45134. }
  45135. if (this._microSurfaceTexture) {
  45136. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45137. }
  45138. }
  45139. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45140. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45141. }
  45142. }
  45143. // Clip plane
  45144. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45145. // Colors
  45146. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45147. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45148. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45149. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45150. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45151. }
  45152. if (mustRebind || !this.isFrozen) {
  45153. // Lights
  45154. if (scene.lightsEnabled && !this._disableLighting) {
  45155. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45156. }
  45157. // View
  45158. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45159. this.bindView(effect);
  45160. }
  45161. // Fog
  45162. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45163. // Morph targets
  45164. if (defines.NUM_MORPH_INFLUENCERS) {
  45165. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45166. }
  45167. // image processing
  45168. this._imageProcessingConfiguration.bind(this._activeEffect);
  45169. // Log. depth
  45170. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45171. }
  45172. this._uniformBuffer.update();
  45173. this._afterBind(mesh);
  45174. };
  45175. /**
  45176. * Returns the animatable textures.
  45177. * @returns - Array of animatable textures.
  45178. */
  45179. PBRBaseMaterial.prototype.getAnimatables = function () {
  45180. var results = [];
  45181. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45182. results.push(this._albedoTexture);
  45183. }
  45184. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45185. results.push(this._ambientTexture);
  45186. }
  45187. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45188. results.push(this._opacityTexture);
  45189. }
  45190. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45191. results.push(this._reflectionTexture);
  45192. }
  45193. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45194. results.push(this._emissiveTexture);
  45195. }
  45196. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45197. results.push(this._metallicTexture);
  45198. }
  45199. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45200. results.push(this._reflectivityTexture);
  45201. }
  45202. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45203. results.push(this._bumpTexture);
  45204. }
  45205. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45206. results.push(this._lightmapTexture);
  45207. }
  45208. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45209. results.push(this._refractionTexture);
  45210. }
  45211. return results;
  45212. };
  45213. /**
  45214. * Returns the texture used for reflections.
  45215. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45216. */
  45217. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45218. if (this._reflectionTexture) {
  45219. return this._reflectionTexture;
  45220. }
  45221. return this.getScene().environmentTexture;
  45222. };
  45223. /**
  45224. * Returns the texture used for refraction or null if none is used.
  45225. * @returns - Refection texture if present. If no refraction texture and refraction
  45226. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45227. */
  45228. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45229. if (this._refractionTexture) {
  45230. return this._refractionTexture;
  45231. }
  45232. if (this._linkRefractionWithTransparency) {
  45233. return this.getScene().environmentTexture;
  45234. }
  45235. return null;
  45236. };
  45237. /**
  45238. * Disposes the resources of the material.
  45239. * @param forceDisposeEffect - Forces the disposal of effects.
  45240. * @param forceDisposeTextures - Forces the disposal of all textures.
  45241. */
  45242. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45243. if (forceDisposeTextures) {
  45244. if (this._albedoTexture) {
  45245. this._albedoTexture.dispose();
  45246. }
  45247. if (this._ambientTexture) {
  45248. this._ambientTexture.dispose();
  45249. }
  45250. if (this._opacityTexture) {
  45251. this._opacityTexture.dispose();
  45252. }
  45253. if (this._reflectionTexture) {
  45254. this._reflectionTexture.dispose();
  45255. }
  45256. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45257. this._environmentBRDFTexture.dispose();
  45258. }
  45259. if (this._emissiveTexture) {
  45260. this._emissiveTexture.dispose();
  45261. }
  45262. if (this._metallicTexture) {
  45263. this._metallicTexture.dispose();
  45264. }
  45265. if (this._reflectivityTexture) {
  45266. this._reflectivityTexture.dispose();
  45267. }
  45268. if (this._bumpTexture) {
  45269. this._bumpTexture.dispose();
  45270. }
  45271. if (this._lightmapTexture) {
  45272. this._lightmapTexture.dispose();
  45273. }
  45274. if (this._refractionTexture) {
  45275. this._refractionTexture.dispose();
  45276. }
  45277. }
  45278. this._renderTargets.dispose();
  45279. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45280. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45281. }
  45282. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45283. };
  45284. /**
  45285. * Stores the reflectivity values based on metallic roughness workflow.
  45286. */
  45287. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45288. __decorate([
  45289. BABYLON.serializeAsImageProcessingConfiguration()
  45290. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45291. __decorate([
  45292. BABYLON.serialize()
  45293. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45294. __decorate([
  45295. BABYLON.serialize()
  45296. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45297. return PBRBaseMaterial;
  45298. }(BABYLON.PushMaterial));
  45299. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45300. })(BABYLON || (BABYLON = {}));
  45301. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45302. var BABYLON;
  45303. (function (BABYLON) {
  45304. /**
  45305. * The Physically based simple base material of BJS.
  45306. *
  45307. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45308. * It is used as the base class for both the specGloss and metalRough conventions.
  45309. */
  45310. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45311. __extends(PBRBaseSimpleMaterial, _super);
  45312. /**
  45313. * Instantiates a new PBRMaterial instance.
  45314. *
  45315. * @param name The material name
  45316. * @param scene The scene the material will be use in.
  45317. */
  45318. function PBRBaseSimpleMaterial(name, scene) {
  45319. var _this = _super.call(this, name, scene) || this;
  45320. /**
  45321. * Number of Simultaneous lights allowed on the material.
  45322. */
  45323. _this.maxSimultaneousLights = 4;
  45324. /**
  45325. * If sets to true, disables all the lights affecting the material.
  45326. */
  45327. _this.disableLighting = false;
  45328. /**
  45329. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45330. */
  45331. _this.invertNormalMapX = false;
  45332. /**
  45333. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45334. */
  45335. _this.invertNormalMapY = false;
  45336. /**
  45337. * Emissivie color used to self-illuminate the model.
  45338. */
  45339. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45340. /**
  45341. * Occlusion Channel Strenght.
  45342. */
  45343. _this.occlusionStrength = 1.0;
  45344. _this.useLightmapAsShadowmap = false;
  45345. _this._useAlphaFromAlbedoTexture = true;
  45346. _this._useAmbientInGrayScale = true;
  45347. return _this;
  45348. }
  45349. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45350. /**
  45351. * Gets the current double sided mode.
  45352. */
  45353. get: function () {
  45354. return this._twoSidedLighting;
  45355. },
  45356. /**
  45357. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45358. */
  45359. set: function (value) {
  45360. if (this._twoSidedLighting === value) {
  45361. return;
  45362. }
  45363. this._twoSidedLighting = value;
  45364. this.backFaceCulling = !value;
  45365. this._markAllSubMeshesAsTexturesDirty();
  45366. },
  45367. enumerable: true,
  45368. configurable: true
  45369. });
  45370. /**
  45371. * Return the active textures of the material.
  45372. */
  45373. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45374. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45375. if (this.environmentTexture) {
  45376. activeTextures.push(this.environmentTexture);
  45377. }
  45378. if (this.normalTexture) {
  45379. activeTextures.push(this.normalTexture);
  45380. }
  45381. if (this.emissiveTexture) {
  45382. activeTextures.push(this.emissiveTexture);
  45383. }
  45384. if (this.occlusionTexture) {
  45385. activeTextures.push(this.occlusionTexture);
  45386. }
  45387. if (this.lightmapTexture) {
  45388. activeTextures.push(this.lightmapTexture);
  45389. }
  45390. return activeTextures;
  45391. };
  45392. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45393. if (_super.prototype.hasTexture.call(this, texture)) {
  45394. return true;
  45395. }
  45396. if (this.lightmapTexture === texture) {
  45397. return true;
  45398. }
  45399. return false;
  45400. };
  45401. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45402. return "PBRBaseSimpleMaterial";
  45403. };
  45404. __decorate([
  45405. BABYLON.serialize(),
  45406. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45407. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45408. __decorate([
  45409. BABYLON.serialize(),
  45410. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45411. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45412. __decorate([
  45413. BABYLON.serializeAsTexture(),
  45414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45415. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45416. __decorate([
  45417. BABYLON.serialize(),
  45418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45419. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45420. __decorate([
  45421. BABYLON.serialize(),
  45422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45423. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45424. __decorate([
  45425. BABYLON.serializeAsTexture(),
  45426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45427. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45428. __decorate([
  45429. BABYLON.serializeAsColor3("emissive"),
  45430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45431. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45432. __decorate([
  45433. BABYLON.serializeAsTexture(),
  45434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45435. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45436. __decorate([
  45437. BABYLON.serialize(),
  45438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45439. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45440. __decorate([
  45441. BABYLON.serializeAsTexture(),
  45442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45443. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45444. __decorate([
  45445. BABYLON.serialize(),
  45446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45447. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45448. __decorate([
  45449. BABYLON.serialize()
  45450. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45451. __decorate([
  45452. BABYLON.serializeAsTexture(),
  45453. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45454. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45455. __decorate([
  45456. BABYLON.serialize(),
  45457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45458. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45459. return PBRBaseSimpleMaterial;
  45460. }(BABYLON.PBRBaseMaterial));
  45461. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45462. })(BABYLON || (BABYLON = {}));
  45463. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45464. var BABYLON;
  45465. (function (BABYLON) {
  45466. /**
  45467. * The Physically based material of BJS.
  45468. *
  45469. * This offers the main features of a standard PBR material.
  45470. * For more information, please refer to the documentation :
  45471. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45472. */
  45473. var PBRMaterial = /** @class */ (function (_super) {
  45474. __extends(PBRMaterial, _super);
  45475. /**
  45476. * Instantiates a new PBRMaterial instance.
  45477. *
  45478. * @param name The material name
  45479. * @param scene The scene the material will be use in.
  45480. */
  45481. function PBRMaterial(name, scene) {
  45482. var _this = _super.call(this, name, scene) || this;
  45483. /**
  45484. * Intensity of the direct lights e.g. the four lights available in your scene.
  45485. * This impacts both the direct diffuse and specular highlights.
  45486. */
  45487. _this.directIntensity = 1.0;
  45488. /**
  45489. * Intensity of the emissive part of the material.
  45490. * This helps controlling the emissive effect without modifying the emissive color.
  45491. */
  45492. _this.emissiveIntensity = 1.0;
  45493. /**
  45494. * Intensity of the environment e.g. how much the environment will light the object
  45495. * either through harmonics for rough material or through the refelction for shiny ones.
  45496. */
  45497. _this.environmentIntensity = 1.0;
  45498. /**
  45499. * This is a special control allowing the reduction of the specular highlights coming from the
  45500. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45501. */
  45502. _this.specularIntensity = 1.0;
  45503. /**
  45504. * Debug Control allowing disabling the bump map on this material.
  45505. */
  45506. _this.disableBumpMap = false;
  45507. /**
  45508. * AKA Occlusion Texture Intensity in other nomenclature.
  45509. */
  45510. _this.ambientTextureStrength = 1.0;
  45511. /**
  45512. * The color of a material in ambient lighting.
  45513. */
  45514. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45515. /**
  45516. * AKA Diffuse Color in other nomenclature.
  45517. */
  45518. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45519. /**
  45520. * AKA Specular Color in other nomenclature.
  45521. */
  45522. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45523. /**
  45524. * The color reflected from the material.
  45525. */
  45526. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45527. /**
  45528. * The color emitted from the material.
  45529. */
  45530. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45531. /**
  45532. * AKA Glossiness in other nomenclature.
  45533. */
  45534. _this.microSurface = 1.0;
  45535. /**
  45536. * source material index of refraction (IOR)' / 'destination material IOR.
  45537. */
  45538. _this.indexOfRefraction = 0.66;
  45539. /**
  45540. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45541. */
  45542. _this.invertRefractionY = false;
  45543. /**
  45544. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45545. * Materials half opaque for instance using refraction could benefit from this control.
  45546. */
  45547. _this.linkRefractionWithTransparency = false;
  45548. _this.useLightmapAsShadowmap = false;
  45549. /**
  45550. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45551. */
  45552. _this.useAlphaFromAlbedoTexture = false;
  45553. /**
  45554. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45555. */
  45556. _this.forceAlphaTest = false;
  45557. /**
  45558. * Defines the alpha limits in alpha test mode.
  45559. */
  45560. _this.alphaCutOff = 0.4;
  45561. /**
  45562. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45563. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45564. */
  45565. _this.useSpecularOverAlpha = true;
  45566. /**
  45567. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45568. */
  45569. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45570. /**
  45571. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45572. */
  45573. _this.useRoughnessFromMetallicTextureAlpha = true;
  45574. /**
  45575. * Specifies if the metallic texture contains the roughness information in its green channel.
  45576. */
  45577. _this.useRoughnessFromMetallicTextureGreen = false;
  45578. /**
  45579. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45580. */
  45581. _this.useMetallnessFromMetallicTextureBlue = false;
  45582. /**
  45583. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45584. */
  45585. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45586. /**
  45587. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45588. */
  45589. _this.useAmbientInGrayScale = false;
  45590. /**
  45591. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45592. * The material will try to infer what glossiness each pixel should be.
  45593. */
  45594. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45595. /**
  45596. * BJS is using an harcoded light falloff based on a manually sets up range.
  45597. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45598. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45599. */
  45600. _this.usePhysicalLightFalloff = true;
  45601. /**
  45602. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45603. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45604. */
  45605. _this.useRadianceOverAlpha = true;
  45606. /**
  45607. * Allows using an object space normal map (instead of tangent space).
  45608. */
  45609. _this.useObjectSpaceNormalMap = false;
  45610. /**
  45611. * Allows using the bump map in parallax mode.
  45612. */
  45613. _this.useParallax = false;
  45614. /**
  45615. * Allows using the bump map in parallax occlusion mode.
  45616. */
  45617. _this.useParallaxOcclusion = false;
  45618. /**
  45619. * Controls the scale bias of the parallax mode.
  45620. */
  45621. _this.parallaxScaleBias = 0.05;
  45622. /**
  45623. * If sets to true, disables all the lights affecting the material.
  45624. */
  45625. _this.disableLighting = false;
  45626. /**
  45627. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45628. */
  45629. _this.forceIrradianceInFragment = false;
  45630. /**
  45631. * Number of Simultaneous lights allowed on the material.
  45632. */
  45633. _this.maxSimultaneousLights = 4;
  45634. /**
  45635. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45636. */
  45637. _this.invertNormalMapX = false;
  45638. /**
  45639. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45640. */
  45641. _this.invertNormalMapY = false;
  45642. /**
  45643. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45644. */
  45645. _this.twoSidedLighting = false;
  45646. /**
  45647. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45648. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45649. */
  45650. _this.useAlphaFresnel = false;
  45651. /**
  45652. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45653. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45654. */
  45655. _this.useLinearAlphaFresnel = false;
  45656. /**
  45657. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45658. * And/Or occlude the blended part.
  45659. */
  45660. _this.environmentBRDFTexture = null;
  45661. /**
  45662. * Force normal to face away from face.
  45663. */
  45664. _this.forceNormalForward = false;
  45665. /**
  45666. * Enables specular anti aliasing in the PBR shader.
  45667. * It will both interacts on the Geometry for analytical and IBL lighting.
  45668. * It also prefilter the roughness map based on the bump values.
  45669. */
  45670. _this.enableSpecularAntiAliasing = false;
  45671. /**
  45672. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45673. * makes the reflect vector face the model (under horizon).
  45674. */
  45675. _this.useHorizonOcclusion = true;
  45676. /**
  45677. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45678. * too much the area relying on ambient texture to define their ambient occlusion.
  45679. */
  45680. _this.useRadianceOcclusion = true;
  45681. /**
  45682. * If set to true, no lighting calculations will be applied.
  45683. */
  45684. _this.unlit = false;
  45685. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45686. return _this;
  45687. }
  45688. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45689. /**
  45690. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45691. */
  45692. get: function () {
  45693. return this._PBRMATERIAL_OPAQUE;
  45694. },
  45695. enumerable: true,
  45696. configurable: true
  45697. });
  45698. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45699. /**
  45700. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45701. */
  45702. get: function () {
  45703. return this._PBRMATERIAL_ALPHATEST;
  45704. },
  45705. enumerable: true,
  45706. configurable: true
  45707. });
  45708. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45709. /**
  45710. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45711. */
  45712. get: function () {
  45713. return this._PBRMATERIAL_ALPHABLEND;
  45714. },
  45715. enumerable: true,
  45716. configurable: true
  45717. });
  45718. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45719. /**
  45720. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45721. * They are also discarded below the alpha cutoff threshold to improve performances.
  45722. */
  45723. get: function () {
  45724. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45725. },
  45726. enumerable: true,
  45727. configurable: true
  45728. });
  45729. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45730. /**
  45731. * Gets the image processing configuration used either in this material.
  45732. */
  45733. get: function () {
  45734. return this._imageProcessingConfiguration;
  45735. },
  45736. /**
  45737. * Sets the Default image processing configuration used either in the this material.
  45738. *
  45739. * If sets to null, the scene one is in use.
  45740. */
  45741. set: function (value) {
  45742. this._attachImageProcessingConfiguration(value);
  45743. // Ensure the effect will be rebuilt.
  45744. this._markAllSubMeshesAsTexturesDirty();
  45745. },
  45746. enumerable: true,
  45747. configurable: true
  45748. });
  45749. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45750. /**
  45751. * Gets wether the color curves effect is enabled.
  45752. */
  45753. get: function () {
  45754. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45755. },
  45756. /**
  45757. * Sets wether the color curves effect is enabled.
  45758. */
  45759. set: function (value) {
  45760. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45761. },
  45762. enumerable: true,
  45763. configurable: true
  45764. });
  45765. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45766. /**
  45767. * Gets wether the color grading effect is enabled.
  45768. */
  45769. get: function () {
  45770. return this.imageProcessingConfiguration.colorGradingEnabled;
  45771. },
  45772. /**
  45773. * Gets wether the color grading effect is enabled.
  45774. */
  45775. set: function (value) {
  45776. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45777. },
  45778. enumerable: true,
  45779. configurable: true
  45780. });
  45781. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45782. /**
  45783. * Gets wether tonemapping is enabled or not.
  45784. */
  45785. get: function () {
  45786. return this._imageProcessingConfiguration.toneMappingEnabled;
  45787. },
  45788. /**
  45789. * Sets wether tonemapping is enabled or not
  45790. */
  45791. set: function (value) {
  45792. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45793. },
  45794. enumerable: true,
  45795. configurable: true
  45796. });
  45797. ;
  45798. ;
  45799. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45800. /**
  45801. * The camera exposure used on this material.
  45802. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45803. * This corresponds to a photographic exposure.
  45804. */
  45805. get: function () {
  45806. return this._imageProcessingConfiguration.exposure;
  45807. },
  45808. /**
  45809. * The camera exposure used on this material.
  45810. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45811. * This corresponds to a photographic exposure.
  45812. */
  45813. set: function (value) {
  45814. this._imageProcessingConfiguration.exposure = value;
  45815. },
  45816. enumerable: true,
  45817. configurable: true
  45818. });
  45819. ;
  45820. ;
  45821. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45822. /**
  45823. * Gets The camera contrast used on this material.
  45824. */
  45825. get: function () {
  45826. return this._imageProcessingConfiguration.contrast;
  45827. },
  45828. /**
  45829. * Sets The camera contrast used on this material.
  45830. */
  45831. set: function (value) {
  45832. this._imageProcessingConfiguration.contrast = value;
  45833. },
  45834. enumerable: true,
  45835. configurable: true
  45836. });
  45837. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45838. /**
  45839. * Gets the Color Grading 2D Lookup Texture.
  45840. */
  45841. get: function () {
  45842. return this._imageProcessingConfiguration.colorGradingTexture;
  45843. },
  45844. /**
  45845. * Sets the Color Grading 2D Lookup Texture.
  45846. */
  45847. set: function (value) {
  45848. this._imageProcessingConfiguration.colorGradingTexture = value;
  45849. },
  45850. enumerable: true,
  45851. configurable: true
  45852. });
  45853. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45854. /**
  45855. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45856. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45857. * 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;
  45858. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45859. */
  45860. get: function () {
  45861. return this._imageProcessingConfiguration.colorCurves;
  45862. },
  45863. /**
  45864. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45865. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45866. * 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;
  45867. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45868. */
  45869. set: function (value) {
  45870. this._imageProcessingConfiguration.colorCurves = value;
  45871. },
  45872. enumerable: true,
  45873. configurable: true
  45874. });
  45875. /**
  45876. * Returns the name of this material class.
  45877. */
  45878. PBRMaterial.prototype.getClassName = function () {
  45879. return "PBRMaterial";
  45880. };
  45881. /**
  45882. * Returns an array of the actively used textures.
  45883. * @returns - Array of BaseTextures
  45884. */
  45885. PBRMaterial.prototype.getActiveTextures = function () {
  45886. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45887. if (this._albedoTexture) {
  45888. activeTextures.push(this._albedoTexture);
  45889. }
  45890. if (this._ambientTexture) {
  45891. activeTextures.push(this._ambientTexture);
  45892. }
  45893. if (this._opacityTexture) {
  45894. activeTextures.push(this._opacityTexture);
  45895. }
  45896. if (this._reflectionTexture) {
  45897. activeTextures.push(this._reflectionTexture);
  45898. }
  45899. if (this._emissiveTexture) {
  45900. activeTextures.push(this._emissiveTexture);
  45901. }
  45902. if (this._reflectivityTexture) {
  45903. activeTextures.push(this._reflectivityTexture);
  45904. }
  45905. if (this._metallicTexture) {
  45906. activeTextures.push(this._metallicTexture);
  45907. }
  45908. if (this._microSurfaceTexture) {
  45909. activeTextures.push(this._microSurfaceTexture);
  45910. }
  45911. if (this._bumpTexture) {
  45912. activeTextures.push(this._bumpTexture);
  45913. }
  45914. if (this._lightmapTexture) {
  45915. activeTextures.push(this._lightmapTexture);
  45916. }
  45917. if (this._refractionTexture) {
  45918. activeTextures.push(this._refractionTexture);
  45919. }
  45920. return activeTextures;
  45921. };
  45922. /**
  45923. * Checks to see if a texture is used in the material.
  45924. * @param texture - Base texture to use.
  45925. * @returns - Boolean specifying if a texture is used in the material.
  45926. */
  45927. PBRMaterial.prototype.hasTexture = function (texture) {
  45928. if (_super.prototype.hasTexture.call(this, texture)) {
  45929. return true;
  45930. }
  45931. if (this._albedoTexture === texture) {
  45932. return true;
  45933. }
  45934. if (this._ambientTexture === texture) {
  45935. return true;
  45936. }
  45937. if (this._opacityTexture === texture) {
  45938. return true;
  45939. }
  45940. if (this._reflectionTexture === texture) {
  45941. return true;
  45942. }
  45943. if (this._reflectivityTexture === texture) {
  45944. return true;
  45945. }
  45946. if (this._metallicTexture === texture) {
  45947. return true;
  45948. }
  45949. if (this._microSurfaceTexture === texture) {
  45950. return true;
  45951. }
  45952. if (this._bumpTexture === texture) {
  45953. return true;
  45954. }
  45955. if (this._lightmapTexture === texture) {
  45956. return true;
  45957. }
  45958. if (this._refractionTexture === texture) {
  45959. return true;
  45960. }
  45961. return false;
  45962. };
  45963. /**
  45964. * Makes a duplicate of the current material.
  45965. * @param name - name to use for the new material.
  45966. */
  45967. PBRMaterial.prototype.clone = function (name) {
  45968. var _this = this;
  45969. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45970. clone.id = name;
  45971. clone.name = name;
  45972. return clone;
  45973. };
  45974. /**
  45975. * Serializes this PBR Material.
  45976. * @returns - An object with the serialized material.
  45977. */
  45978. PBRMaterial.prototype.serialize = function () {
  45979. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45980. serializationObject.customType = "BABYLON.PBRMaterial";
  45981. return serializationObject;
  45982. };
  45983. // Statics
  45984. /**
  45985. * Parses a PBR Material from a serialized object.
  45986. * @param source - Serialized object.
  45987. * @param scene - BJS scene instance.
  45988. * @param rootUrl - url for the scene object
  45989. * @returns - PBRMaterial
  45990. */
  45991. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45992. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45993. };
  45994. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45995. /**
  45996. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45997. */
  45998. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45999. /**
  46000. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46001. */
  46002. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46003. /**
  46004. * 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.
  46005. * They are also discarded below the alpha cutoff threshold to improve performances.
  46006. */
  46007. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46008. __decorate([
  46009. BABYLON.serialize(),
  46010. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46011. ], PBRMaterial.prototype, "directIntensity", void 0);
  46012. __decorate([
  46013. BABYLON.serialize(),
  46014. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46015. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46016. __decorate([
  46017. BABYLON.serialize(),
  46018. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46019. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46020. __decorate([
  46021. BABYLON.serialize(),
  46022. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46023. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46024. __decorate([
  46025. BABYLON.serialize(),
  46026. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46027. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46028. __decorate([
  46029. BABYLON.serializeAsTexture(),
  46030. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46031. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46032. __decorate([
  46033. BABYLON.serializeAsTexture(),
  46034. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46035. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46036. __decorate([
  46037. BABYLON.serialize(),
  46038. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46039. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46040. __decorate([
  46041. BABYLON.serializeAsTexture(),
  46042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46043. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46044. __decorate([
  46045. BABYLON.serializeAsTexture(),
  46046. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46047. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46048. __decorate([
  46049. BABYLON.serializeAsTexture(),
  46050. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46051. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46052. __decorate([
  46053. BABYLON.serializeAsTexture(),
  46054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46055. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46056. __decorate([
  46057. BABYLON.serializeAsTexture(),
  46058. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46059. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46060. __decorate([
  46061. BABYLON.serialize(),
  46062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46063. ], PBRMaterial.prototype, "metallic", void 0);
  46064. __decorate([
  46065. BABYLON.serialize(),
  46066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46067. ], PBRMaterial.prototype, "roughness", void 0);
  46068. __decorate([
  46069. BABYLON.serializeAsTexture(),
  46070. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46071. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46072. __decorate([
  46073. BABYLON.serializeAsTexture(),
  46074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46075. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46076. __decorate([
  46077. BABYLON.serializeAsTexture(),
  46078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46079. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46080. __decorate([
  46081. BABYLON.serializeAsTexture(),
  46082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46083. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46084. __decorate([
  46085. BABYLON.serializeAsColor3("ambient"),
  46086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46087. ], PBRMaterial.prototype, "ambientColor", void 0);
  46088. __decorate([
  46089. BABYLON.serializeAsColor3("albedo"),
  46090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46091. ], PBRMaterial.prototype, "albedoColor", void 0);
  46092. __decorate([
  46093. BABYLON.serializeAsColor3("reflectivity"),
  46094. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46095. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46096. __decorate([
  46097. BABYLON.serializeAsColor3("reflection"),
  46098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46099. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46100. __decorate([
  46101. BABYLON.serializeAsColor3("emissive"),
  46102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46103. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46104. __decorate([
  46105. BABYLON.serialize(),
  46106. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46107. ], PBRMaterial.prototype, "microSurface", void 0);
  46108. __decorate([
  46109. BABYLON.serialize(),
  46110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46111. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46112. __decorate([
  46113. BABYLON.serialize(),
  46114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46115. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46116. __decorate([
  46117. BABYLON.serialize(),
  46118. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46119. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46120. __decorate([
  46121. BABYLON.serialize(),
  46122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46123. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46124. __decorate([
  46125. BABYLON.serialize(),
  46126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46127. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46128. __decorate([
  46129. BABYLON.serialize(),
  46130. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46131. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46132. __decorate([
  46133. BABYLON.serialize(),
  46134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46135. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46136. __decorate([
  46137. BABYLON.serialize(),
  46138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46139. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46140. __decorate([
  46141. BABYLON.serialize(),
  46142. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46143. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46144. __decorate([
  46145. BABYLON.serialize(),
  46146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46147. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46148. __decorate([
  46149. BABYLON.serialize(),
  46150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46151. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46152. __decorate([
  46153. BABYLON.serialize(),
  46154. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46155. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46156. __decorate([
  46157. BABYLON.serialize(),
  46158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46159. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46160. __decorate([
  46161. BABYLON.serialize(),
  46162. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46163. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46164. __decorate([
  46165. BABYLON.serialize(),
  46166. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46167. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46168. __decorate([
  46169. BABYLON.serialize(),
  46170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46171. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46172. __decorate([
  46173. BABYLON.serialize(),
  46174. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46175. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46176. __decorate([
  46177. BABYLON.serialize(),
  46178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46179. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46180. __decorate([
  46181. BABYLON.serialize(),
  46182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46183. ], PBRMaterial.prototype, "useParallax", void 0);
  46184. __decorate([
  46185. BABYLON.serialize(),
  46186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46187. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46188. __decorate([
  46189. BABYLON.serialize(),
  46190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46191. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46192. __decorate([
  46193. BABYLON.serialize(),
  46194. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46195. ], PBRMaterial.prototype, "disableLighting", void 0);
  46196. __decorate([
  46197. BABYLON.serialize(),
  46198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46199. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46200. __decorate([
  46201. BABYLON.serialize(),
  46202. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46203. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46204. __decorate([
  46205. BABYLON.serialize(),
  46206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46207. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46208. __decorate([
  46209. BABYLON.serialize(),
  46210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46211. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46212. __decorate([
  46213. BABYLON.serialize(),
  46214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46215. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46216. __decorate([
  46217. BABYLON.serialize(),
  46218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46219. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46220. __decorate([
  46221. BABYLON.serialize(),
  46222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46223. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46224. __decorate([
  46225. BABYLON.serializeAsTexture(),
  46226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46227. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46228. __decorate([
  46229. BABYLON.serialize(),
  46230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46231. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46232. __decorate([
  46233. BABYLON.serialize(),
  46234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46235. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46236. __decorate([
  46237. BABYLON.serialize(),
  46238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46239. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46240. __decorate([
  46241. BABYLON.serialize(),
  46242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46243. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46244. __decorate([
  46245. BABYLON.serialize(),
  46246. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46247. ], PBRMaterial.prototype, "unlit", void 0);
  46248. return PBRMaterial;
  46249. }(BABYLON.PBRBaseMaterial));
  46250. BABYLON.PBRMaterial = PBRMaterial;
  46251. })(BABYLON || (BABYLON = {}));
  46252. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46253. var BABYLON;
  46254. (function (BABYLON) {
  46255. /**
  46256. * The PBR material of BJS following the metal roughness convention.
  46257. *
  46258. * This fits to the PBR convention in the GLTF definition:
  46259. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46260. */
  46261. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46262. __extends(PBRMetallicRoughnessMaterial, _super);
  46263. /**
  46264. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46265. *
  46266. * @param name The material name
  46267. * @param scene The scene the material will be use in.
  46268. */
  46269. function PBRMetallicRoughnessMaterial(name, scene) {
  46270. var _this = _super.call(this, name, scene) || this;
  46271. _this._useRoughnessFromMetallicTextureAlpha = false;
  46272. _this._useRoughnessFromMetallicTextureGreen = true;
  46273. _this._useMetallnessFromMetallicTextureBlue = true;
  46274. _this.metallic = 1.0;
  46275. _this.roughness = 1.0;
  46276. return _this;
  46277. }
  46278. /**
  46279. * Return the currrent class name of the material.
  46280. */
  46281. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46282. return "PBRMetallicRoughnessMaterial";
  46283. };
  46284. /**
  46285. * Return the active textures of the material.
  46286. */
  46287. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46288. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46289. if (this.baseTexture) {
  46290. activeTextures.push(this.baseTexture);
  46291. }
  46292. if (this.metallicRoughnessTexture) {
  46293. activeTextures.push(this.metallicRoughnessTexture);
  46294. }
  46295. return activeTextures;
  46296. };
  46297. /**
  46298. * Checks to see if a texture is used in the material.
  46299. * @param texture - Base texture to use.
  46300. * @returns - Boolean specifying if a texture is used in the material.
  46301. */
  46302. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46303. if (_super.prototype.hasTexture.call(this, texture)) {
  46304. return true;
  46305. }
  46306. if (this.baseTexture === texture) {
  46307. return true;
  46308. }
  46309. if (this.metallicRoughnessTexture === texture) {
  46310. return true;
  46311. }
  46312. return false;
  46313. };
  46314. /**
  46315. * Makes a duplicate of the current material.
  46316. * @param name - name to use for the new material.
  46317. */
  46318. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46319. var _this = this;
  46320. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46321. clone.id = name;
  46322. clone.name = name;
  46323. return clone;
  46324. };
  46325. /**
  46326. * Serialize the material to a parsable JSON object.
  46327. */
  46328. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46329. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46330. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46331. return serializationObject;
  46332. };
  46333. /**
  46334. * Parses a JSON object correponding to the serialize function.
  46335. */
  46336. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46337. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46338. };
  46339. __decorate([
  46340. BABYLON.serializeAsColor3(),
  46341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46342. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46343. __decorate([
  46344. BABYLON.serializeAsTexture(),
  46345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46346. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46347. __decorate([
  46348. BABYLON.serialize(),
  46349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46350. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46351. __decorate([
  46352. BABYLON.serialize(),
  46353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46354. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46355. __decorate([
  46356. BABYLON.serializeAsTexture(),
  46357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46358. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46359. return PBRMetallicRoughnessMaterial;
  46360. }(BABYLON.PBRBaseSimpleMaterial));
  46361. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46362. })(BABYLON || (BABYLON = {}));
  46363. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46364. var BABYLON;
  46365. (function (BABYLON) {
  46366. /**
  46367. * The PBR material of BJS following the specular glossiness convention.
  46368. *
  46369. * This fits to the PBR convention in the GLTF definition:
  46370. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46371. */
  46372. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46373. __extends(PBRSpecularGlossinessMaterial, _super);
  46374. /**
  46375. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46376. *
  46377. * @param name The material name
  46378. * @param scene The scene the material will be use in.
  46379. */
  46380. function PBRSpecularGlossinessMaterial(name, scene) {
  46381. var _this = _super.call(this, name, scene) || this;
  46382. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46383. return _this;
  46384. }
  46385. /**
  46386. * Return the currrent class name of the material.
  46387. */
  46388. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46389. return "PBRSpecularGlossinessMaterial";
  46390. };
  46391. /**
  46392. * Return the active textures of the material.
  46393. */
  46394. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46395. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46396. if (this.diffuseTexture) {
  46397. activeTextures.push(this.diffuseTexture);
  46398. }
  46399. if (this.specularGlossinessTexture) {
  46400. activeTextures.push(this.specularGlossinessTexture);
  46401. }
  46402. return activeTextures;
  46403. };
  46404. /**
  46405. * Checks to see if a texture is used in the material.
  46406. * @param texture - Base texture to use.
  46407. * @returns - Boolean specifying if a texture is used in the material.
  46408. */
  46409. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46410. if (_super.prototype.hasTexture.call(this, texture)) {
  46411. return true;
  46412. }
  46413. if (this.diffuseTexture === texture) {
  46414. return true;
  46415. }
  46416. if (this.specularGlossinessTexture === texture) {
  46417. return true;
  46418. }
  46419. return false;
  46420. };
  46421. /**
  46422. * Makes a duplicate of the current material.
  46423. * @param name - name to use for the new material.
  46424. */
  46425. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46426. var _this = this;
  46427. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46428. clone.id = name;
  46429. clone.name = name;
  46430. return clone;
  46431. };
  46432. /**
  46433. * Serialize the material to a parsable JSON object.
  46434. */
  46435. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46436. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46437. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46438. return serializationObject;
  46439. };
  46440. /**
  46441. * Parses a JSON object correponding to the serialize function.
  46442. */
  46443. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46444. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46445. };
  46446. __decorate([
  46447. BABYLON.serializeAsColor3("diffuse"),
  46448. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46449. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46450. __decorate([
  46451. BABYLON.serializeAsTexture(),
  46452. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46453. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46454. __decorate([
  46455. BABYLON.serializeAsColor3("specular"),
  46456. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46457. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46458. __decorate([
  46459. BABYLON.serialize(),
  46460. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46461. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46462. __decorate([
  46463. BABYLON.serializeAsTexture(),
  46464. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46465. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46466. return PBRSpecularGlossinessMaterial;
  46467. }(BABYLON.PBRBaseSimpleMaterial));
  46468. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46469. })(BABYLON || (BABYLON = {}));
  46470. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46471. var BABYLON;
  46472. (function (BABYLON) {
  46473. BABYLON.CameraInputTypes = {};
  46474. var CameraInputsManager = /** @class */ (function () {
  46475. function CameraInputsManager(camera) {
  46476. this.attached = {};
  46477. this.camera = camera;
  46478. this.checkInputs = function () { };
  46479. }
  46480. /**
  46481. * Add an input method to a camera.
  46482. * builtin inputs example: camera.inputs.addGamepad();
  46483. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46484. * @param input camera input method
  46485. */
  46486. CameraInputsManager.prototype.add = function (input) {
  46487. var type = input.getSimpleName();
  46488. if (this.attached[type]) {
  46489. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46490. return;
  46491. }
  46492. this.attached[type] = input;
  46493. input.camera = this.camera;
  46494. //for checkInputs, we are dynamically creating a function
  46495. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46496. if (input.checkInputs) {
  46497. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46498. }
  46499. if (this.attachedElement) {
  46500. input.attachControl(this.attachedElement);
  46501. }
  46502. };
  46503. /**
  46504. * Remove a specific input method from a camera
  46505. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46506. * @param inputToRemove camera input method
  46507. */
  46508. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46509. for (var cam in this.attached) {
  46510. var input = this.attached[cam];
  46511. if (input === inputToRemove) {
  46512. input.detachControl(this.attachedElement);
  46513. input.camera = null;
  46514. delete this.attached[cam];
  46515. this.rebuildInputCheck();
  46516. }
  46517. }
  46518. };
  46519. CameraInputsManager.prototype.removeByType = function (inputType) {
  46520. for (var cam in this.attached) {
  46521. var input = this.attached[cam];
  46522. if (input.getClassName() === inputType) {
  46523. input.detachControl(this.attachedElement);
  46524. input.camera = null;
  46525. delete this.attached[cam];
  46526. this.rebuildInputCheck();
  46527. }
  46528. }
  46529. };
  46530. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46531. var current = this.checkInputs;
  46532. return function () {
  46533. current();
  46534. fn();
  46535. };
  46536. };
  46537. CameraInputsManager.prototype.attachInput = function (input) {
  46538. if (this.attachedElement) {
  46539. input.attachControl(this.attachedElement, this.noPreventDefault);
  46540. }
  46541. };
  46542. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46543. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46544. if (this.attachedElement) {
  46545. return;
  46546. }
  46547. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46548. this.attachedElement = element;
  46549. this.noPreventDefault = noPreventDefault;
  46550. for (var cam in this.attached) {
  46551. this.attached[cam].attachControl(element, noPreventDefault);
  46552. }
  46553. };
  46554. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46555. if (disconnect === void 0) { disconnect = false; }
  46556. if (this.attachedElement !== element) {
  46557. return;
  46558. }
  46559. for (var cam in this.attached) {
  46560. this.attached[cam].detachControl(element);
  46561. if (disconnect) {
  46562. this.attached[cam].camera = null;
  46563. }
  46564. }
  46565. this.attachedElement = null;
  46566. };
  46567. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46568. this.checkInputs = function () { };
  46569. for (var cam in this.attached) {
  46570. var input = this.attached[cam];
  46571. if (input.checkInputs) {
  46572. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46573. }
  46574. }
  46575. };
  46576. /**
  46577. * Remove all attached input methods from a camera
  46578. */
  46579. CameraInputsManager.prototype.clear = function () {
  46580. if (this.attachedElement) {
  46581. this.detachElement(this.attachedElement, true);
  46582. }
  46583. this.attached = {};
  46584. this.attachedElement = null;
  46585. this.checkInputs = function () { };
  46586. };
  46587. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46588. var inputs = {};
  46589. for (var cam in this.attached) {
  46590. var input = this.attached[cam];
  46591. var res = BABYLON.SerializationHelper.Serialize(input);
  46592. inputs[input.getClassName()] = res;
  46593. }
  46594. serializedCamera.inputsmgr = inputs;
  46595. };
  46596. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46597. var parsedInputs = parsedCamera.inputsmgr;
  46598. if (parsedInputs) {
  46599. this.clear();
  46600. for (var n in parsedInputs) {
  46601. var construct = BABYLON.CameraInputTypes[n];
  46602. if (construct) {
  46603. var parsedinput = parsedInputs[n];
  46604. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46605. this.add(input);
  46606. }
  46607. }
  46608. }
  46609. else {
  46610. //2016-03-08 this part is for managing backward compatibility
  46611. for (var n in this.attached) {
  46612. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46613. if (construct) {
  46614. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46615. this.remove(this.attached[n]);
  46616. this.add(input);
  46617. }
  46618. }
  46619. }
  46620. };
  46621. return CameraInputsManager;
  46622. }());
  46623. BABYLON.CameraInputsManager = CameraInputsManager;
  46624. })(BABYLON || (BABYLON = {}));
  46625. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46626. var BABYLON;
  46627. (function (BABYLON) {
  46628. var TargetCamera = /** @class */ (function (_super) {
  46629. __extends(TargetCamera, _super);
  46630. function TargetCamera(name, position, scene) {
  46631. var _this = _super.call(this, name, position, scene) || this;
  46632. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46633. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46634. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46635. _this.speed = 2.0;
  46636. _this.noRotationConstraint = false;
  46637. _this.lockedTarget = null;
  46638. _this._currentTarget = BABYLON.Vector3.Zero();
  46639. _this._viewMatrix = BABYLON.Matrix.Zero();
  46640. _this._camMatrix = BABYLON.Matrix.Zero();
  46641. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46642. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46643. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46644. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46645. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46646. _this._lookAtTemp = BABYLON.Matrix.Zero();
  46647. _this._tempMatrix = BABYLON.Matrix.Zero();
  46648. return _this;
  46649. }
  46650. TargetCamera.prototype.getFrontPosition = function (distance) {
  46651. this.getWorldMatrix();
  46652. var direction = this.getTarget().subtract(this.position);
  46653. direction.normalize();
  46654. direction.scaleInPlace(distance);
  46655. return this.globalPosition.add(direction);
  46656. };
  46657. TargetCamera.prototype._getLockedTargetPosition = function () {
  46658. if (!this.lockedTarget) {
  46659. return null;
  46660. }
  46661. if (this.lockedTarget.absolutePosition) {
  46662. this.lockedTarget.computeWorldMatrix();
  46663. }
  46664. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46665. };
  46666. TargetCamera.prototype.storeState = function () {
  46667. this._storedPosition = this.position.clone();
  46668. this._storedRotation = this.rotation.clone();
  46669. if (this.rotationQuaternion) {
  46670. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46671. }
  46672. return _super.prototype.storeState.call(this);
  46673. };
  46674. /**
  46675. * Restored camera state. You must call storeState() first
  46676. */
  46677. TargetCamera.prototype._restoreStateValues = function () {
  46678. if (!_super.prototype._restoreStateValues.call(this)) {
  46679. return false;
  46680. }
  46681. this.position = this._storedPosition.clone();
  46682. this.rotation = this._storedRotation.clone();
  46683. if (this.rotationQuaternion) {
  46684. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46685. }
  46686. this.cameraDirection.copyFromFloats(0, 0, 0);
  46687. this.cameraRotation.copyFromFloats(0, 0);
  46688. return true;
  46689. };
  46690. // Cache
  46691. TargetCamera.prototype._initCache = function () {
  46692. _super.prototype._initCache.call(this);
  46693. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46694. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46695. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46696. };
  46697. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46698. if (!ignoreParentClass) {
  46699. _super.prototype._updateCache.call(this);
  46700. }
  46701. var lockedTargetPosition = this._getLockedTargetPosition();
  46702. if (!lockedTargetPosition) {
  46703. this._cache.lockedTarget = null;
  46704. }
  46705. else {
  46706. if (!this._cache.lockedTarget) {
  46707. this._cache.lockedTarget = lockedTargetPosition.clone();
  46708. }
  46709. else {
  46710. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46711. }
  46712. }
  46713. this._cache.rotation.copyFrom(this.rotation);
  46714. if (this.rotationQuaternion)
  46715. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46716. };
  46717. // Synchronized
  46718. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46719. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46720. return false;
  46721. }
  46722. var lockedTargetPosition = this._getLockedTargetPosition();
  46723. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46724. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46725. };
  46726. // Methods
  46727. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46728. var engine = this.getEngine();
  46729. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46730. };
  46731. // Target
  46732. TargetCamera.prototype.setTarget = function (target) {
  46733. this.upVector.normalize();
  46734. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46735. this._camMatrix.invert();
  46736. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46737. var vDir = target.subtract(this.position);
  46738. if (vDir.x >= 0.0) {
  46739. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46740. }
  46741. else {
  46742. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46743. }
  46744. this.rotation.z = 0;
  46745. if (isNaN(this.rotation.x)) {
  46746. this.rotation.x = 0;
  46747. }
  46748. if (isNaN(this.rotation.y)) {
  46749. this.rotation.y = 0;
  46750. }
  46751. if (isNaN(this.rotation.z)) {
  46752. this.rotation.z = 0;
  46753. }
  46754. if (this.rotationQuaternion) {
  46755. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46756. }
  46757. };
  46758. /**
  46759. * Return the current target position of the camera. This value is expressed in local space.
  46760. */
  46761. TargetCamera.prototype.getTarget = function () {
  46762. return this._currentTarget;
  46763. };
  46764. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46765. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46766. };
  46767. TargetCamera.prototype._updatePosition = function () {
  46768. if (this.parent) {
  46769. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46770. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46771. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46772. return;
  46773. }
  46774. this.position.addInPlace(this.cameraDirection);
  46775. };
  46776. TargetCamera.prototype._checkInputs = function () {
  46777. var needToMove = this._decideIfNeedsToMove();
  46778. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46779. // Move
  46780. if (needToMove) {
  46781. this._updatePosition();
  46782. }
  46783. // Rotate
  46784. if (needToRotate) {
  46785. this.rotation.x += this.cameraRotation.x;
  46786. this.rotation.y += this.cameraRotation.y;
  46787. //rotate, if quaternion is set and rotation was used
  46788. if (this.rotationQuaternion) {
  46789. var len = this.rotation.lengthSquared();
  46790. if (len) {
  46791. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46792. }
  46793. }
  46794. if (!this.noRotationConstraint) {
  46795. var limit = (Math.PI / 2) * 0.95;
  46796. if (this.rotation.x > limit)
  46797. this.rotation.x = limit;
  46798. if (this.rotation.x < -limit)
  46799. this.rotation.x = -limit;
  46800. }
  46801. }
  46802. // Inertia
  46803. if (needToMove) {
  46804. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46805. this.cameraDirection.x = 0;
  46806. }
  46807. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46808. this.cameraDirection.y = 0;
  46809. }
  46810. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46811. this.cameraDirection.z = 0;
  46812. }
  46813. this.cameraDirection.scaleInPlace(this.inertia);
  46814. }
  46815. if (needToRotate) {
  46816. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46817. this.cameraRotation.x = 0;
  46818. }
  46819. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46820. this.cameraRotation.y = 0;
  46821. }
  46822. this.cameraRotation.scaleInPlace(this.inertia);
  46823. }
  46824. _super.prototype._checkInputs.call(this);
  46825. };
  46826. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46827. if (this.rotationQuaternion) {
  46828. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46829. }
  46830. else {
  46831. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46832. }
  46833. //update the up vector!
  46834. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46835. };
  46836. TargetCamera.prototype._getViewMatrix = function () {
  46837. if (this.lockedTarget) {
  46838. this.setTarget(this._getLockedTargetPosition());
  46839. }
  46840. // Compute
  46841. this._updateCameraRotationMatrix();
  46842. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46843. // Computing target and final matrix
  46844. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46845. if (this.getScene().useRightHandedSystem) {
  46846. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46847. }
  46848. else {
  46849. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  46850. }
  46851. return this._viewMatrix;
  46852. };
  46853. /**
  46854. * @override
  46855. * Override Camera.createRigCamera
  46856. */
  46857. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46858. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46859. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46860. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46861. if (!this.rotationQuaternion) {
  46862. this.rotationQuaternion = new BABYLON.Quaternion();
  46863. }
  46864. rigCamera._cameraRigParams = {};
  46865. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46866. }
  46867. return rigCamera;
  46868. }
  46869. return null;
  46870. };
  46871. /**
  46872. * @override
  46873. * Override Camera._updateRigCameras
  46874. */
  46875. TargetCamera.prototype._updateRigCameras = function () {
  46876. var camLeft = this._rigCameras[0];
  46877. var camRight = this._rigCameras[1];
  46878. switch (this.cameraRigMode) {
  46879. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46880. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46881. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46882. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46883. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46884. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46885. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46886. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46887. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46888. camLeft.setTarget(this.getTarget());
  46889. camRight.setTarget(this.getTarget());
  46890. break;
  46891. case BABYLON.Camera.RIG_MODE_VR:
  46892. if (camLeft.rotationQuaternion) {
  46893. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46894. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46895. }
  46896. else {
  46897. camLeft.rotation.copyFrom(this.rotation);
  46898. camRight.rotation.copyFrom(this.rotation);
  46899. }
  46900. camLeft.position.copyFrom(this.position);
  46901. camRight.position.copyFrom(this.position);
  46902. break;
  46903. }
  46904. _super.prototype._updateRigCameras.call(this);
  46905. };
  46906. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46907. if (!this._rigCamTransformMatrix) {
  46908. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46909. }
  46910. var target = this.getTarget();
  46911. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46912. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46913. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46914. };
  46915. TargetCamera.prototype.getClassName = function () {
  46916. return "TargetCamera";
  46917. };
  46918. __decorate([
  46919. BABYLON.serializeAsVector3()
  46920. ], TargetCamera.prototype, "rotation", void 0);
  46921. __decorate([
  46922. BABYLON.serialize()
  46923. ], TargetCamera.prototype, "speed", void 0);
  46924. __decorate([
  46925. BABYLON.serializeAsMeshReference("lockedTargetId")
  46926. ], TargetCamera.prototype, "lockedTarget", void 0);
  46927. return TargetCamera;
  46928. }(BABYLON.Camera));
  46929. BABYLON.TargetCamera = TargetCamera;
  46930. })(BABYLON || (BABYLON = {}));
  46931. //# sourceMappingURL=babylon.targetCamera.js.map
  46932. var BABYLON;
  46933. (function (BABYLON) {
  46934. var FreeCameraMouseInput = /** @class */ (function () {
  46935. function FreeCameraMouseInput(touchEnabled) {
  46936. if (touchEnabled === void 0) { touchEnabled = true; }
  46937. this.touchEnabled = touchEnabled;
  46938. this.buttons = [0, 1, 2];
  46939. this.angularSensibility = 2000.0;
  46940. this.previousPosition = null;
  46941. }
  46942. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46943. var _this = this;
  46944. var engine = this.camera.getEngine();
  46945. if (!this._pointerInput) {
  46946. this._pointerInput = function (p, s) {
  46947. var evt = p.event;
  46948. if (engine.isInVRExclusivePointerMode) {
  46949. return;
  46950. }
  46951. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46952. return;
  46953. }
  46954. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46955. return;
  46956. }
  46957. var srcElement = (evt.srcElement || evt.target);
  46958. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46959. try {
  46960. srcElement.setPointerCapture(evt.pointerId);
  46961. }
  46962. catch (e) {
  46963. //Nothing to do with the error. Execution will continue.
  46964. }
  46965. _this.previousPosition = {
  46966. x: evt.clientX,
  46967. y: evt.clientY
  46968. };
  46969. if (!noPreventDefault) {
  46970. evt.preventDefault();
  46971. element.focus();
  46972. }
  46973. }
  46974. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46975. try {
  46976. srcElement.releasePointerCapture(evt.pointerId);
  46977. }
  46978. catch (e) {
  46979. //Nothing to do with the error.
  46980. }
  46981. _this.previousPosition = null;
  46982. if (!noPreventDefault) {
  46983. evt.preventDefault();
  46984. }
  46985. }
  46986. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46987. if (!_this.previousPosition || engine.isPointerLock) {
  46988. return;
  46989. }
  46990. var offsetX = evt.clientX - _this.previousPosition.x;
  46991. var offsetY = evt.clientY - _this.previousPosition.y;
  46992. if (_this.camera.getScene().useRightHandedSystem) {
  46993. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  46994. }
  46995. else {
  46996. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46997. }
  46998. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46999. _this.previousPosition = {
  47000. x: evt.clientX,
  47001. y: evt.clientY
  47002. };
  47003. if (!noPreventDefault) {
  47004. evt.preventDefault();
  47005. }
  47006. }
  47007. };
  47008. }
  47009. this._onMouseMove = function (evt) {
  47010. if (!engine.isPointerLock) {
  47011. return;
  47012. }
  47013. if (engine.isInVRExclusivePointerMode) {
  47014. return;
  47015. }
  47016. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47017. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47018. if (_this.camera.getScene().useRightHandedSystem) {
  47019. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  47020. }
  47021. else {
  47022. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47023. }
  47024. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47025. _this.previousPosition = null;
  47026. if (!noPreventDefault) {
  47027. evt.preventDefault();
  47028. }
  47029. };
  47030. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47031. element.addEventListener("mousemove", this._onMouseMove, false);
  47032. };
  47033. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47034. if (this._observer && element) {
  47035. this.camera.getScene().onPointerObservable.remove(this._observer);
  47036. if (this._onMouseMove) {
  47037. element.removeEventListener("mousemove", this._onMouseMove);
  47038. }
  47039. this._observer = null;
  47040. this._onMouseMove = null;
  47041. this.previousPosition = null;
  47042. }
  47043. };
  47044. FreeCameraMouseInput.prototype.getClassName = function () {
  47045. return "FreeCameraMouseInput";
  47046. };
  47047. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47048. return "mouse";
  47049. };
  47050. __decorate([
  47051. BABYLON.serialize()
  47052. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47053. __decorate([
  47054. BABYLON.serialize()
  47055. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47056. return FreeCameraMouseInput;
  47057. }());
  47058. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47059. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47060. })(BABYLON || (BABYLON = {}));
  47061. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47062. var BABYLON;
  47063. (function (BABYLON) {
  47064. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47065. function FreeCameraKeyboardMoveInput() {
  47066. this._keys = new Array();
  47067. this.keysUp = [38];
  47068. this.keysDown = [40];
  47069. this.keysLeft = [37];
  47070. this.keysRight = [39];
  47071. }
  47072. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47073. var _this = this;
  47074. if (this._onCanvasBlurObserver) {
  47075. return;
  47076. }
  47077. this._scene = this.camera.getScene();
  47078. this._engine = this._scene.getEngine();
  47079. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47080. _this._keys = [];
  47081. });
  47082. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47083. var evt = info.event;
  47084. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47085. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47086. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47087. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47088. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47089. var index = _this._keys.indexOf(evt.keyCode);
  47090. if (index === -1) {
  47091. _this._keys.push(evt.keyCode);
  47092. }
  47093. if (!noPreventDefault) {
  47094. evt.preventDefault();
  47095. }
  47096. }
  47097. }
  47098. else {
  47099. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47100. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47101. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47102. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47103. var index = _this._keys.indexOf(evt.keyCode);
  47104. if (index >= 0) {
  47105. _this._keys.splice(index, 1);
  47106. }
  47107. if (!noPreventDefault) {
  47108. evt.preventDefault();
  47109. }
  47110. }
  47111. }
  47112. });
  47113. };
  47114. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47115. if (this._scene) {
  47116. if (this._onKeyboardObserver) {
  47117. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47118. }
  47119. if (this._onCanvasBlurObserver) {
  47120. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47121. }
  47122. this._onKeyboardObserver = null;
  47123. this._onCanvasBlurObserver = null;
  47124. }
  47125. this._keys = [];
  47126. };
  47127. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47128. if (this._onKeyboardObserver) {
  47129. var camera = this.camera;
  47130. // Keyboard
  47131. for (var index = 0; index < this._keys.length; index++) {
  47132. var keyCode = this._keys[index];
  47133. var speed = camera._computeLocalCameraSpeed();
  47134. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47135. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47136. }
  47137. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47138. camera._localDirection.copyFromFloats(0, 0, speed);
  47139. }
  47140. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47141. camera._localDirection.copyFromFloats(speed, 0, 0);
  47142. }
  47143. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47144. camera._localDirection.copyFromFloats(0, 0, -speed);
  47145. }
  47146. if (camera.getScene().useRightHandedSystem) {
  47147. camera._localDirection.z *= -1;
  47148. }
  47149. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47150. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47151. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47152. }
  47153. }
  47154. };
  47155. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47156. return "FreeCameraKeyboardMoveInput";
  47157. };
  47158. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47159. this._keys = [];
  47160. };
  47161. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47162. return "keyboard";
  47163. };
  47164. __decorate([
  47165. BABYLON.serialize()
  47166. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47167. __decorate([
  47168. BABYLON.serialize()
  47169. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47170. __decorate([
  47171. BABYLON.serialize()
  47172. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47173. __decorate([
  47174. BABYLON.serialize()
  47175. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47176. return FreeCameraKeyboardMoveInput;
  47177. }());
  47178. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47179. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47180. })(BABYLON || (BABYLON = {}));
  47181. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47182. var BABYLON;
  47183. (function (BABYLON) {
  47184. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47185. __extends(FreeCameraInputsManager, _super);
  47186. function FreeCameraInputsManager(camera) {
  47187. return _super.call(this, camera) || this;
  47188. }
  47189. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47190. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47191. return this;
  47192. };
  47193. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47194. if (touchEnabled === void 0) { touchEnabled = true; }
  47195. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47196. return this;
  47197. };
  47198. FreeCameraInputsManager.prototype.addGamepad = function () {
  47199. this.add(new BABYLON.FreeCameraGamepadInput());
  47200. return this;
  47201. };
  47202. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47203. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47204. return this;
  47205. };
  47206. FreeCameraInputsManager.prototype.addTouch = function () {
  47207. this.add(new BABYLON.FreeCameraTouchInput());
  47208. return this;
  47209. };
  47210. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47211. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47212. return this;
  47213. };
  47214. return FreeCameraInputsManager;
  47215. }(BABYLON.CameraInputsManager));
  47216. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47217. })(BABYLON || (BABYLON = {}));
  47218. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47219. var BABYLON;
  47220. (function (BABYLON) {
  47221. var FreeCamera = /** @class */ (function (_super) {
  47222. __extends(FreeCamera, _super);
  47223. function FreeCamera(name, position, scene) {
  47224. var _this = _super.call(this, name, position, scene) || this;
  47225. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47226. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47227. _this.checkCollisions = false;
  47228. _this.applyGravity = false;
  47229. _this._needMoveForGravity = false;
  47230. _this._oldPosition = BABYLON.Vector3.Zero();
  47231. _this._diffPosition = BABYLON.Vector3.Zero();
  47232. _this._newPosition = BABYLON.Vector3.Zero();
  47233. // Collisions
  47234. _this._collisionMask = -1;
  47235. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47236. if (collidedMesh === void 0) { collidedMesh = null; }
  47237. //TODO move this to the collision coordinator!
  47238. if (_this.getScene().workerCollisions)
  47239. newPosition.multiplyInPlace(_this._collider._radius);
  47240. var updatePosition = function (newPos) {
  47241. _this._newPosition.copyFrom(newPos);
  47242. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47243. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47244. _this.position.addInPlace(_this._diffPosition);
  47245. if (_this.onCollide && collidedMesh) {
  47246. _this.onCollide(collidedMesh);
  47247. }
  47248. }
  47249. };
  47250. updatePosition(newPosition);
  47251. };
  47252. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47253. _this.inputs.addKeyboard().addMouse();
  47254. return _this;
  47255. }
  47256. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47257. //-- begin properties for backward compatibility for inputs
  47258. /**
  47259. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47260. * Higher values reduce sensitivity.
  47261. */
  47262. get: function () {
  47263. var mouse = this.inputs.attached["mouse"];
  47264. if (mouse)
  47265. return mouse.angularSensibility;
  47266. return 0;
  47267. },
  47268. /**
  47269. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47270. * Higher values reduce sensitivity.
  47271. */
  47272. set: function (value) {
  47273. var mouse = this.inputs.attached["mouse"];
  47274. if (mouse)
  47275. mouse.angularSensibility = value;
  47276. },
  47277. enumerable: true,
  47278. configurable: true
  47279. });
  47280. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47281. get: function () {
  47282. var keyboard = this.inputs.attached["keyboard"];
  47283. if (keyboard)
  47284. return keyboard.keysUp;
  47285. return [];
  47286. },
  47287. set: function (value) {
  47288. var keyboard = this.inputs.attached["keyboard"];
  47289. if (keyboard)
  47290. keyboard.keysUp = value;
  47291. },
  47292. enumerable: true,
  47293. configurable: true
  47294. });
  47295. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47296. get: function () {
  47297. var keyboard = this.inputs.attached["keyboard"];
  47298. if (keyboard)
  47299. return keyboard.keysDown;
  47300. return [];
  47301. },
  47302. set: function (value) {
  47303. var keyboard = this.inputs.attached["keyboard"];
  47304. if (keyboard)
  47305. keyboard.keysDown = value;
  47306. },
  47307. enumerable: true,
  47308. configurable: true
  47309. });
  47310. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47311. get: function () {
  47312. var keyboard = this.inputs.attached["keyboard"];
  47313. if (keyboard)
  47314. return keyboard.keysLeft;
  47315. return [];
  47316. },
  47317. set: function (value) {
  47318. var keyboard = this.inputs.attached["keyboard"];
  47319. if (keyboard)
  47320. keyboard.keysLeft = value;
  47321. },
  47322. enumerable: true,
  47323. configurable: true
  47324. });
  47325. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47326. get: function () {
  47327. var keyboard = this.inputs.attached["keyboard"];
  47328. if (keyboard)
  47329. return keyboard.keysRight;
  47330. return [];
  47331. },
  47332. set: function (value) {
  47333. var keyboard = this.inputs.attached["keyboard"];
  47334. if (keyboard)
  47335. keyboard.keysRight = value;
  47336. },
  47337. enumerable: true,
  47338. configurable: true
  47339. });
  47340. // Controls
  47341. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47342. this.inputs.attachElement(element, noPreventDefault);
  47343. };
  47344. FreeCamera.prototype.detachControl = function (element) {
  47345. this.inputs.detachElement(element);
  47346. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47347. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47348. };
  47349. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47350. get: function () {
  47351. return this._collisionMask;
  47352. },
  47353. set: function (mask) {
  47354. this._collisionMask = !isNaN(mask) ? mask : -1;
  47355. },
  47356. enumerable: true,
  47357. configurable: true
  47358. });
  47359. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47360. var globalPosition;
  47361. if (this.parent) {
  47362. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47363. }
  47364. else {
  47365. globalPosition = this.position;
  47366. }
  47367. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47368. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47369. if (!this._collider) {
  47370. this._collider = new BABYLON.Collider();
  47371. }
  47372. this._collider._radius = this.ellipsoid;
  47373. this._collider.collisionMask = this._collisionMask;
  47374. //no need for clone, as long as gravity is not on.
  47375. var actualDisplacement = displacement;
  47376. //add gravity to the direction to prevent the dual-collision checking
  47377. if (this.applyGravity) {
  47378. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47379. actualDisplacement = displacement.add(this.getScene().gravity);
  47380. }
  47381. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47382. };
  47383. FreeCamera.prototype._checkInputs = function () {
  47384. if (!this._localDirection) {
  47385. this._localDirection = BABYLON.Vector3.Zero();
  47386. this._transformedDirection = BABYLON.Vector3.Zero();
  47387. }
  47388. this.inputs.checkInputs();
  47389. _super.prototype._checkInputs.call(this);
  47390. };
  47391. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47392. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47393. };
  47394. FreeCamera.prototype._updatePosition = function () {
  47395. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47396. this._collideWithWorld(this.cameraDirection);
  47397. }
  47398. else {
  47399. _super.prototype._updatePosition.call(this);
  47400. }
  47401. };
  47402. FreeCamera.prototype.dispose = function () {
  47403. this.inputs.clear();
  47404. _super.prototype.dispose.call(this);
  47405. };
  47406. FreeCamera.prototype.getClassName = function () {
  47407. return "FreeCamera";
  47408. };
  47409. __decorate([
  47410. BABYLON.serializeAsVector3()
  47411. ], FreeCamera.prototype, "ellipsoid", void 0);
  47412. __decorate([
  47413. BABYLON.serializeAsVector3()
  47414. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47415. __decorate([
  47416. BABYLON.serialize()
  47417. ], FreeCamera.prototype, "checkCollisions", void 0);
  47418. __decorate([
  47419. BABYLON.serialize()
  47420. ], FreeCamera.prototype, "applyGravity", void 0);
  47421. return FreeCamera;
  47422. }(BABYLON.TargetCamera));
  47423. BABYLON.FreeCamera = FreeCamera;
  47424. })(BABYLON || (BABYLON = {}));
  47425. //# sourceMappingURL=babylon.freeCamera.js.map
  47426. var BABYLON;
  47427. (function (BABYLON) {
  47428. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47429. function ArcRotateCameraKeyboardMoveInput() {
  47430. this._keys = new Array();
  47431. this.keysUp = [38];
  47432. this.keysDown = [40];
  47433. this.keysLeft = [37];
  47434. this.keysRight = [39];
  47435. this.keysReset = [220];
  47436. this.panningSensibility = 50.0;
  47437. this.zoomingSensibility = 25.0;
  47438. this.useAltToZoom = true;
  47439. }
  47440. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47441. var _this = this;
  47442. if (this._onCanvasBlurObserver) {
  47443. return;
  47444. }
  47445. this._scene = this.camera.getScene();
  47446. this._engine = this._scene.getEngine();
  47447. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47448. _this._keys = [];
  47449. });
  47450. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47451. var evt = info.event;
  47452. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47453. _this._ctrlPressed = evt.ctrlKey;
  47454. _this._altPressed = evt.altKey;
  47455. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47456. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47457. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47458. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47459. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47460. var index = _this._keys.indexOf(evt.keyCode);
  47461. if (index === -1) {
  47462. _this._keys.push(evt.keyCode);
  47463. }
  47464. if (evt.preventDefault) {
  47465. if (!noPreventDefault) {
  47466. evt.preventDefault();
  47467. }
  47468. }
  47469. }
  47470. }
  47471. else {
  47472. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47473. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47474. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47475. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47476. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47477. var index = _this._keys.indexOf(evt.keyCode);
  47478. if (index >= 0) {
  47479. _this._keys.splice(index, 1);
  47480. }
  47481. if (evt.preventDefault) {
  47482. if (!noPreventDefault) {
  47483. evt.preventDefault();
  47484. }
  47485. }
  47486. }
  47487. }
  47488. });
  47489. };
  47490. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47491. if (this._scene) {
  47492. if (this._onKeyboardObserver) {
  47493. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47494. }
  47495. if (this._onCanvasBlurObserver) {
  47496. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47497. }
  47498. this._onKeyboardObserver = null;
  47499. this._onCanvasBlurObserver = null;
  47500. }
  47501. this._keys = [];
  47502. };
  47503. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47504. if (this._onKeyboardObserver) {
  47505. var camera = this.camera;
  47506. for (var index = 0; index < this._keys.length; index++) {
  47507. var keyCode = this._keys[index];
  47508. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47509. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47510. camera.inertialPanningX -= 1 / this.panningSensibility;
  47511. }
  47512. else {
  47513. camera.inertialAlphaOffset -= 0.01;
  47514. }
  47515. }
  47516. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47517. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47518. camera.inertialPanningY += 1 / this.panningSensibility;
  47519. }
  47520. else if (this._altPressed && this.useAltToZoom) {
  47521. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47522. }
  47523. else {
  47524. camera.inertialBetaOffset -= 0.01;
  47525. }
  47526. }
  47527. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47528. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47529. camera.inertialPanningX += 1 / this.panningSensibility;
  47530. }
  47531. else {
  47532. camera.inertialAlphaOffset += 0.01;
  47533. }
  47534. }
  47535. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47536. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47537. camera.inertialPanningY -= 1 / this.panningSensibility;
  47538. }
  47539. else if (this._altPressed && this.useAltToZoom) {
  47540. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47541. }
  47542. else {
  47543. camera.inertialBetaOffset += 0.01;
  47544. }
  47545. }
  47546. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47547. camera.restoreState();
  47548. }
  47549. }
  47550. }
  47551. };
  47552. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47553. return "ArcRotateCameraKeyboardMoveInput";
  47554. };
  47555. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47556. return "keyboard";
  47557. };
  47558. __decorate([
  47559. BABYLON.serialize()
  47560. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47561. __decorate([
  47562. BABYLON.serialize()
  47563. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47564. __decorate([
  47565. BABYLON.serialize()
  47566. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47567. __decorate([
  47568. BABYLON.serialize()
  47569. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47570. __decorate([
  47571. BABYLON.serialize()
  47572. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47573. __decorate([
  47574. BABYLON.serialize()
  47575. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47576. __decorate([
  47577. BABYLON.serialize()
  47578. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47579. __decorate([
  47580. BABYLON.serialize()
  47581. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47582. return ArcRotateCameraKeyboardMoveInput;
  47583. }());
  47584. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47585. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47586. })(BABYLON || (BABYLON = {}));
  47587. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47588. var BABYLON;
  47589. (function (BABYLON) {
  47590. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47591. function ArcRotateCameraMouseWheelInput() {
  47592. this.wheelPrecision = 3.0;
  47593. /**
  47594. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47595. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47596. */
  47597. this.wheelDeltaPercentage = 0;
  47598. }
  47599. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47600. var _this = this;
  47601. this._wheel = function (p, s) {
  47602. //sanity check - this should be a PointerWheel event.
  47603. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47604. return;
  47605. var event = p.event;
  47606. var delta = 0;
  47607. if (event.wheelDelta) {
  47608. if (_this.wheelDeltaPercentage) {
  47609. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47610. if (event.wheelDelta > 0) {
  47611. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47612. }
  47613. else {
  47614. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47615. }
  47616. }
  47617. else {
  47618. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47619. }
  47620. }
  47621. else if (event.detail) {
  47622. delta = -event.detail / _this.wheelPrecision;
  47623. }
  47624. if (delta)
  47625. _this.camera.inertialRadiusOffset += delta;
  47626. if (event.preventDefault) {
  47627. if (!noPreventDefault) {
  47628. event.preventDefault();
  47629. }
  47630. }
  47631. };
  47632. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47633. };
  47634. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47635. if (this._observer && element) {
  47636. this.camera.getScene().onPointerObservable.remove(this._observer);
  47637. this._observer = null;
  47638. this._wheel = null;
  47639. }
  47640. };
  47641. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47642. return "ArcRotateCameraMouseWheelInput";
  47643. };
  47644. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47645. return "mousewheel";
  47646. };
  47647. __decorate([
  47648. BABYLON.serialize()
  47649. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47650. __decorate([
  47651. BABYLON.serialize()
  47652. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47653. return ArcRotateCameraMouseWheelInput;
  47654. }());
  47655. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47656. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47657. })(BABYLON || (BABYLON = {}));
  47658. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47659. var BABYLON;
  47660. (function (BABYLON) {
  47661. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47662. function ArcRotateCameraPointersInput() {
  47663. this.buttons = [0, 1, 2];
  47664. this.angularSensibilityX = 1000.0;
  47665. this.angularSensibilityY = 1000.0;
  47666. this.pinchPrecision = 12.0;
  47667. /**
  47668. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47669. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47670. */
  47671. this.pinchDeltaPercentage = 0;
  47672. this.panningSensibility = 1000.0;
  47673. this.multiTouchPanning = true;
  47674. this.multiTouchPanAndZoom = true;
  47675. this._isPanClick = false;
  47676. this.pinchInwards = true;
  47677. }
  47678. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47679. var _this = this;
  47680. var engine = this.camera.getEngine();
  47681. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47682. var pointA = null;
  47683. var pointB = null;
  47684. var previousPinchSquaredDistance = 0;
  47685. var initialDistance = 0;
  47686. var twoFingerActivityCount = 0;
  47687. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47688. this._pointerInput = function (p, s) {
  47689. var evt = p.event;
  47690. var isTouch = p.event.pointerType === "touch";
  47691. if (engine.isInVRExclusivePointerMode) {
  47692. return;
  47693. }
  47694. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47695. return;
  47696. }
  47697. var srcElement = (evt.srcElement || evt.target);
  47698. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47699. try {
  47700. srcElement.setPointerCapture(evt.pointerId);
  47701. }
  47702. catch (e) {
  47703. //Nothing to do with the error. Execution will continue.
  47704. }
  47705. // Manage panning with pan button click
  47706. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47707. // manage pointers
  47708. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47709. if (pointA === null) {
  47710. pointA = cacheSoloPointer;
  47711. }
  47712. else if (pointB === null) {
  47713. pointB = cacheSoloPointer;
  47714. }
  47715. if (!noPreventDefault) {
  47716. evt.preventDefault();
  47717. element.focus();
  47718. }
  47719. }
  47720. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47721. _this.camera.restoreState();
  47722. }
  47723. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47724. try {
  47725. srcElement.releasePointerCapture(evt.pointerId);
  47726. }
  47727. catch (e) {
  47728. //Nothing to do with the error.
  47729. }
  47730. cacheSoloPointer = null;
  47731. previousPinchSquaredDistance = 0;
  47732. previousMultiTouchPanPosition.isPaning = false;
  47733. previousMultiTouchPanPosition.isPinching = false;
  47734. twoFingerActivityCount = 0;
  47735. initialDistance = 0;
  47736. if (!isTouch) {
  47737. pointB = null; // Mouse and pen are mono pointer
  47738. }
  47739. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47740. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47741. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47742. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47743. if (engine._badOS) {
  47744. pointA = pointB = null;
  47745. }
  47746. else {
  47747. //only remove the impacted pointer in case of multitouch allowing on most
  47748. //platforms switching from rotate to zoom and pan seamlessly.
  47749. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47750. pointA = pointB;
  47751. pointB = null;
  47752. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47753. }
  47754. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47755. pointB = null;
  47756. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47757. }
  47758. else {
  47759. pointA = pointB = null;
  47760. }
  47761. }
  47762. if (!noPreventDefault) {
  47763. evt.preventDefault();
  47764. }
  47765. }
  47766. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47767. if (!noPreventDefault) {
  47768. evt.preventDefault();
  47769. }
  47770. // One button down
  47771. if (pointA && pointB === null && cacheSoloPointer) {
  47772. if (_this.panningSensibility !== 0 &&
  47773. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47774. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47775. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47776. }
  47777. else {
  47778. var offsetX = evt.clientX - cacheSoloPointer.x;
  47779. var offsetY = evt.clientY - cacheSoloPointer.y;
  47780. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47781. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47782. }
  47783. cacheSoloPointer.x = evt.clientX;
  47784. cacheSoloPointer.y = evt.clientY;
  47785. }
  47786. // Two buttons down: pinch/pan
  47787. else if (pointA && pointB) {
  47788. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47789. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47790. ed.x = evt.clientX;
  47791. ed.y = evt.clientY;
  47792. var direction = _this.pinchInwards ? 1 : -1;
  47793. var distX = pointA.x - pointB.x;
  47794. var distY = pointA.y - pointB.y;
  47795. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47796. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47797. if (previousPinchSquaredDistance === 0) {
  47798. initialDistance = pinchDistance;
  47799. previousPinchSquaredDistance = pinchSquaredDistance;
  47800. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47801. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47802. return;
  47803. }
  47804. if (_this.multiTouchPanAndZoom) {
  47805. if (_this.pinchDeltaPercentage) {
  47806. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47807. }
  47808. else {
  47809. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47810. (_this.pinchPrecision *
  47811. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47812. direction);
  47813. }
  47814. if (_this.panningSensibility !== 0) {
  47815. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47816. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47817. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47818. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47819. previousMultiTouchPanPosition.x = pointersCenterX;
  47820. previousMultiTouchPanPosition.y = pointersCenterY;
  47821. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47822. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47823. }
  47824. }
  47825. else {
  47826. twoFingerActivityCount++;
  47827. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47828. if (_this.pinchDeltaPercentage) {
  47829. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47830. }
  47831. else {
  47832. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47833. (_this.pinchPrecision *
  47834. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47835. direction);
  47836. }
  47837. previousMultiTouchPanPosition.isPaning = false;
  47838. previousMultiTouchPanPosition.isPinching = true;
  47839. }
  47840. else {
  47841. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47842. if (!previousMultiTouchPanPosition.isPaning) {
  47843. previousMultiTouchPanPosition.isPaning = true;
  47844. previousMultiTouchPanPosition.isPinching = false;
  47845. previousMultiTouchPanPosition.x = ed.x;
  47846. previousMultiTouchPanPosition.y = ed.y;
  47847. return;
  47848. }
  47849. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47850. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47851. }
  47852. }
  47853. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47854. previousMultiTouchPanPosition.x = ed.x;
  47855. previousMultiTouchPanPosition.y = ed.y;
  47856. }
  47857. }
  47858. previousPinchSquaredDistance = pinchSquaredDistance;
  47859. }
  47860. }
  47861. };
  47862. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47863. this._onContextMenu = function (evt) {
  47864. evt.preventDefault();
  47865. };
  47866. if (!this.camera._useCtrlForPanning) {
  47867. element.addEventListener("contextmenu", this._onContextMenu, false);
  47868. }
  47869. this._onLostFocus = function () {
  47870. //this._keys = [];
  47871. pointA = pointB = null;
  47872. previousPinchSquaredDistance = 0;
  47873. previousMultiTouchPanPosition.isPaning = false;
  47874. previousMultiTouchPanPosition.isPinching = false;
  47875. twoFingerActivityCount = 0;
  47876. cacheSoloPointer = null;
  47877. initialDistance = 0;
  47878. };
  47879. this._onMouseMove = function (evt) {
  47880. if (!engine.isPointerLock) {
  47881. return;
  47882. }
  47883. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47884. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47885. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47886. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47887. if (!noPreventDefault) {
  47888. evt.preventDefault();
  47889. }
  47890. };
  47891. this._onGestureStart = function (e) {
  47892. if (window.MSGesture === undefined) {
  47893. return;
  47894. }
  47895. if (!_this._MSGestureHandler) {
  47896. _this._MSGestureHandler = new MSGesture();
  47897. _this._MSGestureHandler.target = element;
  47898. }
  47899. _this._MSGestureHandler.addPointer(e.pointerId);
  47900. };
  47901. this._onGesture = function (e) {
  47902. _this.camera.radius *= e.scale;
  47903. if (e.preventDefault) {
  47904. if (!noPreventDefault) {
  47905. e.stopPropagation();
  47906. e.preventDefault();
  47907. }
  47908. }
  47909. };
  47910. element.addEventListener("mousemove", this._onMouseMove, false);
  47911. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47912. element.addEventListener("MSGestureChange", this._onGesture, false);
  47913. BABYLON.Tools.RegisterTopRootEvents([
  47914. { name: "blur", handler: this._onLostFocus }
  47915. ]);
  47916. };
  47917. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47918. if (this._onLostFocus) {
  47919. BABYLON.Tools.UnregisterTopRootEvents([
  47920. { name: "blur", handler: this._onLostFocus }
  47921. ]);
  47922. }
  47923. if (element && this._observer) {
  47924. this.camera.getScene().onPointerObservable.remove(this._observer);
  47925. this._observer = null;
  47926. if (this._onContextMenu) {
  47927. element.removeEventListener("contextmenu", this._onContextMenu);
  47928. }
  47929. if (this._onMouseMove) {
  47930. element.removeEventListener("mousemove", this._onMouseMove);
  47931. }
  47932. if (this._onGestureStart) {
  47933. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47934. }
  47935. if (this._onGesture) {
  47936. element.removeEventListener("MSGestureChange", this._onGesture);
  47937. }
  47938. this._isPanClick = false;
  47939. this.pinchInwards = true;
  47940. this._onMouseMove = null;
  47941. this._onGestureStart = null;
  47942. this._onGesture = null;
  47943. this._MSGestureHandler = null;
  47944. this._onLostFocus = null;
  47945. this._onContextMenu = null;
  47946. }
  47947. };
  47948. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47949. return "ArcRotateCameraPointersInput";
  47950. };
  47951. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47952. return "pointers";
  47953. };
  47954. __decorate([
  47955. BABYLON.serialize()
  47956. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47957. __decorate([
  47958. BABYLON.serialize()
  47959. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47960. __decorate([
  47961. BABYLON.serialize()
  47962. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47963. __decorate([
  47964. BABYLON.serialize()
  47965. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47966. __decorate([
  47967. BABYLON.serialize()
  47968. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47969. __decorate([
  47970. BABYLON.serialize()
  47971. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47972. __decorate([
  47973. BABYLON.serialize()
  47974. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47975. __decorate([
  47976. BABYLON.serialize()
  47977. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47978. return ArcRotateCameraPointersInput;
  47979. }());
  47980. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47981. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47982. })(BABYLON || (BABYLON = {}));
  47983. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47984. var BABYLON;
  47985. (function (BABYLON) {
  47986. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47987. __extends(ArcRotateCameraInputsManager, _super);
  47988. function ArcRotateCameraInputsManager(camera) {
  47989. return _super.call(this, camera) || this;
  47990. }
  47991. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47992. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47993. return this;
  47994. };
  47995. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47996. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47997. return this;
  47998. };
  47999. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48000. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48001. return this;
  48002. };
  48003. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48004. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48005. return this;
  48006. };
  48007. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48008. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48009. return this;
  48010. };
  48011. return ArcRotateCameraInputsManager;
  48012. }(BABYLON.CameraInputsManager));
  48013. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48014. })(BABYLON || (BABYLON = {}));
  48015. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48016. var BABYLON;
  48017. (function (BABYLON) {
  48018. var ArcRotateCamera = /** @class */ (function (_super) {
  48019. __extends(ArcRotateCamera, _super);
  48020. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  48021. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48022. _this.inertialAlphaOffset = 0;
  48023. _this.inertialBetaOffset = 0;
  48024. _this.inertialRadiusOffset = 0;
  48025. _this.lowerAlphaLimit = null;
  48026. _this.upperAlphaLimit = null;
  48027. _this.lowerBetaLimit = 0.01;
  48028. _this.upperBetaLimit = Math.PI;
  48029. _this.lowerRadiusLimit = null;
  48030. _this.upperRadiusLimit = null;
  48031. _this.inertialPanningX = 0;
  48032. _this.inertialPanningY = 0;
  48033. _this.pinchToPanMaxDistance = 20;
  48034. _this.panningDistanceLimit = null;
  48035. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48036. _this.panningInertia = 0.9;
  48037. //-- end properties for backward compatibility for inputs
  48038. _this.zoomOnFactor = 1;
  48039. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48040. _this.allowUpsideDown = true;
  48041. _this._viewMatrix = new BABYLON.Matrix();
  48042. // Panning
  48043. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48044. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48045. _this.checkCollisions = false;
  48046. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48047. _this._previousPosition = BABYLON.Vector3.Zero();
  48048. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48049. _this._newPosition = BABYLON.Vector3.Zero();
  48050. _this._computationVector = BABYLON.Vector3.Zero();
  48051. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48052. if (collidedMesh === void 0) { collidedMesh = null; }
  48053. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48054. newPosition.multiplyInPlace(_this._collider._radius);
  48055. }
  48056. if (!collidedMesh) {
  48057. _this._previousPosition.copyFrom(_this.position);
  48058. }
  48059. else {
  48060. _this.setPosition(newPosition);
  48061. if (_this.onCollide) {
  48062. _this.onCollide(collidedMesh);
  48063. }
  48064. }
  48065. // Recompute because of constraints
  48066. var cosa = Math.cos(_this.alpha);
  48067. var sina = Math.sin(_this.alpha);
  48068. var cosb = Math.cos(_this.beta);
  48069. var sinb = Math.sin(_this.beta);
  48070. if (sinb === 0) {
  48071. sinb = 0.0001;
  48072. }
  48073. var target = _this._getTargetPosition();
  48074. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48075. target.addToRef(_this._computationVector, _this._newPosition);
  48076. _this.position.copyFrom(_this._newPosition);
  48077. var up = _this.upVector;
  48078. if (_this.allowUpsideDown && _this.beta < 0) {
  48079. up = up.clone();
  48080. up = up.negate();
  48081. }
  48082. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48083. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48084. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48085. _this._collisionTriggered = false;
  48086. };
  48087. _this._target = BABYLON.Vector3.Zero();
  48088. if (target) {
  48089. _this.setTarget(target);
  48090. }
  48091. _this.alpha = alpha;
  48092. _this.beta = beta;
  48093. _this.radius = radius;
  48094. _this.getViewMatrix();
  48095. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48096. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48097. return _this;
  48098. }
  48099. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48100. get: function () {
  48101. return this._target;
  48102. },
  48103. set: function (value) {
  48104. this.setTarget(value);
  48105. },
  48106. enumerable: true,
  48107. configurable: true
  48108. });
  48109. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48110. //-- begin properties for backward compatibility for inputs
  48111. get: function () {
  48112. var pointers = this.inputs.attached["pointers"];
  48113. if (pointers)
  48114. return pointers.angularSensibilityX;
  48115. return 0;
  48116. },
  48117. set: function (value) {
  48118. var pointers = this.inputs.attached["pointers"];
  48119. if (pointers) {
  48120. pointers.angularSensibilityX = value;
  48121. }
  48122. },
  48123. enumerable: true,
  48124. configurable: true
  48125. });
  48126. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48127. get: function () {
  48128. var pointers = this.inputs.attached["pointers"];
  48129. if (pointers)
  48130. return pointers.angularSensibilityY;
  48131. return 0;
  48132. },
  48133. set: function (value) {
  48134. var pointers = this.inputs.attached["pointers"];
  48135. if (pointers) {
  48136. pointers.angularSensibilityY = value;
  48137. }
  48138. },
  48139. enumerable: true,
  48140. configurable: true
  48141. });
  48142. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48143. get: function () {
  48144. var pointers = this.inputs.attached["pointers"];
  48145. if (pointers)
  48146. return pointers.pinchPrecision;
  48147. return 0;
  48148. },
  48149. set: function (value) {
  48150. var pointers = this.inputs.attached["pointers"];
  48151. if (pointers) {
  48152. pointers.pinchPrecision = value;
  48153. }
  48154. },
  48155. enumerable: true,
  48156. configurable: true
  48157. });
  48158. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48159. get: function () {
  48160. var pointers = this.inputs.attached["pointers"];
  48161. if (pointers)
  48162. return pointers.pinchDeltaPercentage;
  48163. return 0;
  48164. },
  48165. set: function (value) {
  48166. var pointers = this.inputs.attached["pointers"];
  48167. if (pointers) {
  48168. pointers.pinchDeltaPercentage = value;
  48169. }
  48170. },
  48171. enumerable: true,
  48172. configurable: true
  48173. });
  48174. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48175. get: function () {
  48176. var pointers = this.inputs.attached["pointers"];
  48177. if (pointers)
  48178. return pointers.panningSensibility;
  48179. return 0;
  48180. },
  48181. set: function (value) {
  48182. var pointers = this.inputs.attached["pointers"];
  48183. if (pointers) {
  48184. pointers.panningSensibility = value;
  48185. }
  48186. },
  48187. enumerable: true,
  48188. configurable: true
  48189. });
  48190. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48191. get: function () {
  48192. var keyboard = this.inputs.attached["keyboard"];
  48193. if (keyboard)
  48194. return keyboard.keysUp;
  48195. return [];
  48196. },
  48197. set: function (value) {
  48198. var keyboard = this.inputs.attached["keyboard"];
  48199. if (keyboard)
  48200. keyboard.keysUp = value;
  48201. },
  48202. enumerable: true,
  48203. configurable: true
  48204. });
  48205. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48206. get: function () {
  48207. var keyboard = this.inputs.attached["keyboard"];
  48208. if (keyboard)
  48209. return keyboard.keysDown;
  48210. return [];
  48211. },
  48212. set: function (value) {
  48213. var keyboard = this.inputs.attached["keyboard"];
  48214. if (keyboard)
  48215. keyboard.keysDown = value;
  48216. },
  48217. enumerable: true,
  48218. configurable: true
  48219. });
  48220. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48221. get: function () {
  48222. var keyboard = this.inputs.attached["keyboard"];
  48223. if (keyboard)
  48224. return keyboard.keysLeft;
  48225. return [];
  48226. },
  48227. set: function (value) {
  48228. var keyboard = this.inputs.attached["keyboard"];
  48229. if (keyboard)
  48230. keyboard.keysLeft = value;
  48231. },
  48232. enumerable: true,
  48233. configurable: true
  48234. });
  48235. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48236. get: function () {
  48237. var keyboard = this.inputs.attached["keyboard"];
  48238. if (keyboard)
  48239. return keyboard.keysRight;
  48240. return [];
  48241. },
  48242. set: function (value) {
  48243. var keyboard = this.inputs.attached["keyboard"];
  48244. if (keyboard)
  48245. keyboard.keysRight = value;
  48246. },
  48247. enumerable: true,
  48248. configurable: true
  48249. });
  48250. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48251. get: function () {
  48252. var mousewheel = this.inputs.attached["mousewheel"];
  48253. if (mousewheel)
  48254. return mousewheel.wheelPrecision;
  48255. return 0;
  48256. },
  48257. set: function (value) {
  48258. var mousewheel = this.inputs.attached["mousewheel"];
  48259. if (mousewheel)
  48260. mousewheel.wheelPrecision = value;
  48261. },
  48262. enumerable: true,
  48263. configurable: true
  48264. });
  48265. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48266. get: function () {
  48267. var mousewheel = this.inputs.attached["mousewheel"];
  48268. if (mousewheel)
  48269. return mousewheel.wheelDeltaPercentage;
  48270. return 0;
  48271. },
  48272. set: function (value) {
  48273. var mousewheel = this.inputs.attached["mousewheel"];
  48274. if (mousewheel)
  48275. mousewheel.wheelDeltaPercentage = value;
  48276. },
  48277. enumerable: true,
  48278. configurable: true
  48279. });
  48280. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48281. get: function () {
  48282. return this._bouncingBehavior;
  48283. },
  48284. enumerable: true,
  48285. configurable: true
  48286. });
  48287. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48288. get: function () {
  48289. return this._bouncingBehavior != null;
  48290. },
  48291. set: function (value) {
  48292. if (value === this.useBouncingBehavior) {
  48293. return;
  48294. }
  48295. if (value) {
  48296. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48297. this.addBehavior(this._bouncingBehavior);
  48298. }
  48299. else if (this._bouncingBehavior) {
  48300. this.removeBehavior(this._bouncingBehavior);
  48301. this._bouncingBehavior = null;
  48302. }
  48303. },
  48304. enumerable: true,
  48305. configurable: true
  48306. });
  48307. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48308. get: function () {
  48309. return this._framingBehavior;
  48310. },
  48311. enumerable: true,
  48312. configurable: true
  48313. });
  48314. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48315. get: function () {
  48316. return this._framingBehavior != null;
  48317. },
  48318. set: function (value) {
  48319. if (value === this.useFramingBehavior) {
  48320. return;
  48321. }
  48322. if (value) {
  48323. this._framingBehavior = new BABYLON.FramingBehavior();
  48324. this.addBehavior(this._framingBehavior);
  48325. }
  48326. else if (this._framingBehavior) {
  48327. this.removeBehavior(this._framingBehavior);
  48328. this._framingBehavior = null;
  48329. }
  48330. },
  48331. enumerable: true,
  48332. configurable: true
  48333. });
  48334. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48335. get: function () {
  48336. return this._autoRotationBehavior;
  48337. },
  48338. enumerable: true,
  48339. configurable: true
  48340. });
  48341. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48342. get: function () {
  48343. return this._autoRotationBehavior != null;
  48344. },
  48345. set: function (value) {
  48346. if (value === this.useAutoRotationBehavior) {
  48347. return;
  48348. }
  48349. if (value) {
  48350. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48351. this.addBehavior(this._autoRotationBehavior);
  48352. }
  48353. else if (this._autoRotationBehavior) {
  48354. this.removeBehavior(this._autoRotationBehavior);
  48355. this._autoRotationBehavior = null;
  48356. }
  48357. },
  48358. enumerable: true,
  48359. configurable: true
  48360. });
  48361. // Cache
  48362. ArcRotateCamera.prototype._initCache = function () {
  48363. _super.prototype._initCache.call(this);
  48364. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48365. this._cache.alpha = undefined;
  48366. this._cache.beta = undefined;
  48367. this._cache.radius = undefined;
  48368. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48369. };
  48370. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48371. if (!ignoreParentClass) {
  48372. _super.prototype._updateCache.call(this);
  48373. }
  48374. this._cache._target.copyFrom(this._getTargetPosition());
  48375. this._cache.alpha = this.alpha;
  48376. this._cache.beta = this.beta;
  48377. this._cache.radius = this.radius;
  48378. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48379. };
  48380. ArcRotateCamera.prototype._getTargetPosition = function () {
  48381. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48382. var pos = this._targetHost.getAbsolutePosition();
  48383. if (this._targetBoundingCenter) {
  48384. pos.addToRef(this._targetBoundingCenter, this._target);
  48385. }
  48386. else {
  48387. this._target.copyFrom(pos);
  48388. }
  48389. }
  48390. var lockedTargetPosition = this._getLockedTargetPosition();
  48391. if (lockedTargetPosition) {
  48392. return lockedTargetPosition;
  48393. }
  48394. return this._target;
  48395. };
  48396. ArcRotateCamera.prototype.storeState = function () {
  48397. this._storedAlpha = this.alpha;
  48398. this._storedBeta = this.beta;
  48399. this._storedRadius = this.radius;
  48400. this._storedTarget = this._getTargetPosition().clone();
  48401. return _super.prototype.storeState.call(this);
  48402. };
  48403. /**
  48404. * Restored camera state. You must call storeState() first
  48405. */
  48406. ArcRotateCamera.prototype._restoreStateValues = function () {
  48407. if (!_super.prototype._restoreStateValues.call(this)) {
  48408. return false;
  48409. }
  48410. this.alpha = this._storedAlpha;
  48411. this.beta = this._storedBeta;
  48412. this.radius = this._storedRadius;
  48413. this.setTarget(this._storedTarget.clone());
  48414. this.inertialAlphaOffset = 0;
  48415. this.inertialBetaOffset = 0;
  48416. this.inertialRadiusOffset = 0;
  48417. this.inertialPanningX = 0;
  48418. this.inertialPanningY = 0;
  48419. return true;
  48420. };
  48421. // Synchronized
  48422. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48423. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48424. return false;
  48425. return this._cache._target.equals(this._getTargetPosition())
  48426. && this._cache.alpha === this.alpha
  48427. && this._cache.beta === this.beta
  48428. && this._cache.radius === this.radius
  48429. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48430. };
  48431. // Methods
  48432. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48433. var _this = this;
  48434. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48435. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48436. this._useCtrlForPanning = useCtrlForPanning;
  48437. this._panningMouseButton = panningMouseButton;
  48438. this.inputs.attachElement(element, noPreventDefault);
  48439. this._reset = function () {
  48440. _this.inertialAlphaOffset = 0;
  48441. _this.inertialBetaOffset = 0;
  48442. _this.inertialRadiusOffset = 0;
  48443. _this.inertialPanningX = 0;
  48444. _this.inertialPanningY = 0;
  48445. };
  48446. };
  48447. ArcRotateCamera.prototype.detachControl = function (element) {
  48448. this.inputs.detachElement(element);
  48449. if (this._reset) {
  48450. this._reset();
  48451. }
  48452. };
  48453. ArcRotateCamera.prototype._checkInputs = function () {
  48454. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48455. if (this._collisionTriggered) {
  48456. return;
  48457. }
  48458. this.inputs.checkInputs();
  48459. // Inertia
  48460. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48461. if (this.getScene().useRightHandedSystem) {
  48462. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48463. }
  48464. else {
  48465. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  48466. }
  48467. this.beta += this.inertialBetaOffset;
  48468. this.radius -= this.inertialRadiusOffset;
  48469. this.inertialAlphaOffset *= this.inertia;
  48470. this.inertialBetaOffset *= this.inertia;
  48471. this.inertialRadiusOffset *= this.inertia;
  48472. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48473. this.inertialAlphaOffset = 0;
  48474. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48475. this.inertialBetaOffset = 0;
  48476. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48477. this.inertialRadiusOffset = 0;
  48478. }
  48479. // Panning inertia
  48480. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48481. if (!this._localDirection) {
  48482. this._localDirection = BABYLON.Vector3.Zero();
  48483. this._transformedDirection = BABYLON.Vector3.Zero();
  48484. }
  48485. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48486. this._localDirection.multiplyInPlace(this.panningAxis);
  48487. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48488. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48489. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48490. if (!this.panningAxis.y) {
  48491. this._transformedDirection.y = 0;
  48492. }
  48493. if (!this._targetHost) {
  48494. if (this.panningDistanceLimit) {
  48495. this._transformedDirection.addInPlace(this._target);
  48496. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48497. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48498. this._target.copyFrom(this._transformedDirection);
  48499. }
  48500. }
  48501. else {
  48502. this._target.addInPlace(this._transformedDirection);
  48503. }
  48504. }
  48505. this.inertialPanningX *= this.panningInertia;
  48506. this.inertialPanningY *= this.panningInertia;
  48507. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48508. this.inertialPanningX = 0;
  48509. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48510. this.inertialPanningY = 0;
  48511. }
  48512. // Limits
  48513. this._checkLimits();
  48514. _super.prototype._checkInputs.call(this);
  48515. };
  48516. ArcRotateCamera.prototype._checkLimits = function () {
  48517. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48518. if (this.allowUpsideDown && this.beta > Math.PI) {
  48519. this.beta = this.beta - (2 * Math.PI);
  48520. }
  48521. }
  48522. else {
  48523. if (this.beta < this.lowerBetaLimit) {
  48524. this.beta = this.lowerBetaLimit;
  48525. }
  48526. }
  48527. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48528. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48529. this.beta = this.beta + (2 * Math.PI);
  48530. }
  48531. }
  48532. else {
  48533. if (this.beta > this.upperBetaLimit) {
  48534. this.beta = this.upperBetaLimit;
  48535. }
  48536. }
  48537. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48538. this.alpha = this.lowerAlphaLimit;
  48539. }
  48540. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48541. this.alpha = this.upperAlphaLimit;
  48542. }
  48543. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48544. this.radius = this.lowerRadiusLimit;
  48545. }
  48546. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48547. this.radius = this.upperRadiusLimit;
  48548. }
  48549. };
  48550. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48551. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48552. this.radius = this._computationVector.length();
  48553. if (this.radius === 0) {
  48554. this.radius = 0.0001; // Just to avoid division by zero
  48555. }
  48556. // Alpha
  48557. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48558. if (this._computationVector.z < 0) {
  48559. this.alpha = 2 * Math.PI - this.alpha;
  48560. }
  48561. // Beta
  48562. this.beta = Math.acos(this._computationVector.y / this.radius);
  48563. this._checkLimits();
  48564. };
  48565. ArcRotateCamera.prototype.setPosition = function (position) {
  48566. if (this.position.equals(position)) {
  48567. return;
  48568. }
  48569. this.position.copyFrom(position);
  48570. this.rebuildAnglesAndRadius();
  48571. };
  48572. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48573. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48574. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48575. if (target.getBoundingInfo) {
  48576. if (toBoundingCenter) {
  48577. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48578. }
  48579. else {
  48580. this._targetBoundingCenter = null;
  48581. }
  48582. this._targetHost = target;
  48583. this._target = this._getTargetPosition();
  48584. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48585. }
  48586. else {
  48587. var newTarget = target;
  48588. var currentTarget = this._getTargetPosition();
  48589. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48590. return;
  48591. }
  48592. this._targetHost = null;
  48593. this._target = newTarget;
  48594. this._targetBoundingCenter = null;
  48595. this.onMeshTargetChangedObservable.notifyObservers(null);
  48596. }
  48597. this.rebuildAnglesAndRadius();
  48598. };
  48599. ArcRotateCamera.prototype._getViewMatrix = function () {
  48600. // Compute
  48601. var cosa = Math.cos(this.alpha);
  48602. var sina = Math.sin(this.alpha);
  48603. var cosb = Math.cos(this.beta);
  48604. var sinb = Math.sin(this.beta);
  48605. if (sinb === 0) {
  48606. sinb = 0.0001;
  48607. }
  48608. var target = this._getTargetPosition();
  48609. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48610. target.addToRef(this._computationVector, this._newPosition);
  48611. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48612. if (!this._collider) {
  48613. this._collider = new BABYLON.Collider();
  48614. }
  48615. this._collider._radius = this.collisionRadius;
  48616. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48617. this._collisionTriggered = true;
  48618. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48619. }
  48620. else {
  48621. this.position.copyFrom(this._newPosition);
  48622. var up = this.upVector;
  48623. if (this.allowUpsideDown && sinb < 0) {
  48624. up = up.clone();
  48625. up = up.negate();
  48626. }
  48627. if (this.getScene().useRightHandedSystem) {
  48628. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  48629. }
  48630. else {
  48631. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  48632. }
  48633. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48634. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48635. }
  48636. this._currentTarget = target;
  48637. return this._viewMatrix;
  48638. };
  48639. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48640. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48641. meshes = meshes || this.getScene().meshes;
  48642. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48643. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48644. this.radius = distance * this.zoomOnFactor;
  48645. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48646. };
  48647. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48648. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48649. var meshesOrMinMaxVector;
  48650. var distance;
  48651. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48652. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48653. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48654. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48655. }
  48656. else { //minMaxVector and distance
  48657. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48658. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48659. distance = minMaxVectorAndDistance.distance;
  48660. }
  48661. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48662. if (!doNotUpdateMaxZ) {
  48663. this.maxZ = distance * 2;
  48664. }
  48665. };
  48666. /**
  48667. * @override
  48668. * Override Camera.createRigCamera
  48669. */
  48670. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48671. var alphaShift = 0;
  48672. switch (this.cameraRigMode) {
  48673. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48674. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48675. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48676. case BABYLON.Camera.RIG_MODE_VR:
  48677. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48678. break;
  48679. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48680. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48681. break;
  48682. }
  48683. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48684. rigCam._cameraRigParams = {};
  48685. return rigCam;
  48686. };
  48687. /**
  48688. * @override
  48689. * Override Camera._updateRigCameras
  48690. */
  48691. ArcRotateCamera.prototype._updateRigCameras = function () {
  48692. var camLeft = this._rigCameras[0];
  48693. var camRight = this._rigCameras[1];
  48694. camLeft.beta = camRight.beta = this.beta;
  48695. camLeft.radius = camRight.radius = this.radius;
  48696. switch (this.cameraRigMode) {
  48697. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48698. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48699. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48700. case BABYLON.Camera.RIG_MODE_VR:
  48701. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48702. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48703. break;
  48704. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48705. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48706. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48707. break;
  48708. }
  48709. _super.prototype._updateRigCameras.call(this);
  48710. };
  48711. ArcRotateCamera.prototype.dispose = function () {
  48712. this.inputs.clear();
  48713. _super.prototype.dispose.call(this);
  48714. };
  48715. ArcRotateCamera.prototype.getClassName = function () {
  48716. return "ArcRotateCamera";
  48717. };
  48718. __decorate([
  48719. BABYLON.serialize()
  48720. ], ArcRotateCamera.prototype, "alpha", void 0);
  48721. __decorate([
  48722. BABYLON.serialize()
  48723. ], ArcRotateCamera.prototype, "beta", void 0);
  48724. __decorate([
  48725. BABYLON.serialize()
  48726. ], ArcRotateCamera.prototype, "radius", void 0);
  48727. __decorate([
  48728. BABYLON.serializeAsVector3("target")
  48729. ], ArcRotateCamera.prototype, "_target", void 0);
  48730. __decorate([
  48731. BABYLON.serialize()
  48732. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48733. __decorate([
  48734. BABYLON.serialize()
  48735. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48736. __decorate([
  48737. BABYLON.serialize()
  48738. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48739. __decorate([
  48740. BABYLON.serialize()
  48741. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48742. __decorate([
  48743. BABYLON.serialize()
  48744. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48745. __decorate([
  48746. BABYLON.serialize()
  48747. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48748. __decorate([
  48749. BABYLON.serialize()
  48750. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48751. __decorate([
  48752. BABYLON.serialize()
  48753. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48754. __decorate([
  48755. BABYLON.serialize()
  48756. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48757. __decorate([
  48758. BABYLON.serialize()
  48759. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48760. __decorate([
  48761. BABYLON.serialize()
  48762. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48763. __decorate([
  48764. BABYLON.serialize()
  48765. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48766. __decorate([
  48767. BABYLON.serialize()
  48768. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48769. __decorate([
  48770. BABYLON.serializeAsVector3()
  48771. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48772. __decorate([
  48773. BABYLON.serialize()
  48774. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48775. __decorate([
  48776. BABYLON.serialize()
  48777. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48778. __decorate([
  48779. BABYLON.serialize()
  48780. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48781. return ArcRotateCamera;
  48782. }(BABYLON.TargetCamera));
  48783. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48784. })(BABYLON || (BABYLON = {}));
  48785. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48786. var BABYLON;
  48787. (function (BABYLON) {
  48788. /**
  48789. * The HemisphericLight simulates the ambient environment light,
  48790. * so the passed direction is the light reflection direction, not the incoming direction.
  48791. */
  48792. var HemisphericLight = /** @class */ (function (_super) {
  48793. __extends(HemisphericLight, _super);
  48794. /**
  48795. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48796. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48797. * The HemisphericLight can't cast shadows.
  48798. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48799. * @param name The friendly name of the light
  48800. * @param direction The direction of the light reflection
  48801. * @param scene The scene the light belongs to
  48802. */
  48803. function HemisphericLight(name, direction, scene) {
  48804. var _this = _super.call(this, name, scene) || this;
  48805. /**
  48806. * The groundColor is the light in the opposite direction to the one specified during creation.
  48807. * 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.
  48808. */
  48809. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48810. _this.direction = direction || BABYLON.Vector3.Up();
  48811. return _this;
  48812. }
  48813. HemisphericLight.prototype._buildUniformLayout = function () {
  48814. this._uniformBuffer.addUniform("vLightData", 4);
  48815. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48816. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48817. this._uniformBuffer.addUniform("vLightGround", 3);
  48818. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48819. this._uniformBuffer.addUniform("depthValues", 2);
  48820. this._uniformBuffer.create();
  48821. };
  48822. /**
  48823. * Returns the string "HemisphericLight".
  48824. * @return The class name
  48825. */
  48826. HemisphericLight.prototype.getClassName = function () {
  48827. return "HemisphericLight";
  48828. };
  48829. /**
  48830. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48831. * Returns the updated direction.
  48832. * @param target The target the direction should point to
  48833. * @return The computed direction
  48834. */
  48835. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48836. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48837. return this.direction;
  48838. };
  48839. /**
  48840. * Returns the shadow generator associated to the light.
  48841. * @returns Always null for hemispheric lights because it does not support shadows.
  48842. */
  48843. HemisphericLight.prototype.getShadowGenerator = function () {
  48844. return null;
  48845. };
  48846. /**
  48847. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48848. * @param effect The effect to update
  48849. * @param lightIndex The index of the light in the effect to update
  48850. * @returns The hemispheric light
  48851. */
  48852. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48853. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48854. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48855. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48856. return this;
  48857. };
  48858. /**
  48859. * @ignore internal use only.
  48860. */
  48861. HemisphericLight.prototype._getWorldMatrix = function () {
  48862. if (!this._worldMatrix) {
  48863. this._worldMatrix = BABYLON.Matrix.Identity();
  48864. }
  48865. return this._worldMatrix;
  48866. };
  48867. /**
  48868. * Returns the integer 3.
  48869. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48870. */
  48871. HemisphericLight.prototype.getTypeID = function () {
  48872. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48873. };
  48874. __decorate([
  48875. BABYLON.serializeAsColor3()
  48876. ], HemisphericLight.prototype, "groundColor", void 0);
  48877. __decorate([
  48878. BABYLON.serializeAsVector3()
  48879. ], HemisphericLight.prototype, "direction", void 0);
  48880. return HemisphericLight;
  48881. }(BABYLON.Light));
  48882. BABYLON.HemisphericLight = HemisphericLight;
  48883. })(BABYLON || (BABYLON = {}));
  48884. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48885. var BABYLON;
  48886. (function (BABYLON) {
  48887. /**
  48888. * Base implementation IShadowLight
  48889. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48890. */
  48891. var ShadowLight = /** @class */ (function (_super) {
  48892. __extends(ShadowLight, _super);
  48893. function ShadowLight() {
  48894. var _this = _super !== null && _super.apply(this, arguments) || this;
  48895. _this._needProjectionMatrixCompute = true;
  48896. return _this;
  48897. }
  48898. ShadowLight.prototype._setPosition = function (value) {
  48899. this._position = value;
  48900. };
  48901. Object.defineProperty(ShadowLight.prototype, "position", {
  48902. /**
  48903. * Sets the position the shadow will be casted from. Also use as the light position for both
  48904. * point and spot lights.
  48905. */
  48906. get: function () {
  48907. return this._position;
  48908. },
  48909. /**
  48910. * Sets the position the shadow will be casted from. Also use as the light position for both
  48911. * point and spot lights.
  48912. */
  48913. set: function (value) {
  48914. this._setPosition(value);
  48915. },
  48916. enumerable: true,
  48917. configurable: true
  48918. });
  48919. ShadowLight.prototype._setDirection = function (value) {
  48920. this._direction = value;
  48921. };
  48922. Object.defineProperty(ShadowLight.prototype, "direction", {
  48923. /**
  48924. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48925. * Also use as the light direction on spot and directional lights.
  48926. */
  48927. get: function () {
  48928. return this._direction;
  48929. },
  48930. /**
  48931. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48932. * Also use as the light direction on spot and directional lights.
  48933. */
  48934. set: function (value) {
  48935. this._setDirection(value);
  48936. },
  48937. enumerable: true,
  48938. configurable: true
  48939. });
  48940. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48941. /**
  48942. * Gets the shadow projection clipping minimum z value.
  48943. */
  48944. get: function () {
  48945. return this._shadowMinZ;
  48946. },
  48947. /**
  48948. * Sets the shadow projection clipping minimum z value.
  48949. */
  48950. set: function (value) {
  48951. this._shadowMinZ = value;
  48952. this.forceProjectionMatrixCompute();
  48953. },
  48954. enumerable: true,
  48955. configurable: true
  48956. });
  48957. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48958. /**
  48959. * Sets the shadow projection clipping maximum z value.
  48960. */
  48961. get: function () {
  48962. return this._shadowMaxZ;
  48963. },
  48964. /**
  48965. * Gets the shadow projection clipping maximum z value.
  48966. */
  48967. set: function (value) {
  48968. this._shadowMaxZ = value;
  48969. this.forceProjectionMatrixCompute();
  48970. },
  48971. enumerable: true,
  48972. configurable: true
  48973. });
  48974. /**
  48975. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48976. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48977. */
  48978. ShadowLight.prototype.computeTransformedInformation = function () {
  48979. if (this.parent && this.parent.getWorldMatrix) {
  48980. if (!this.transformedPosition) {
  48981. this.transformedPosition = BABYLON.Vector3.Zero();
  48982. }
  48983. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48984. // In case the direction is present.
  48985. if (this.direction) {
  48986. if (!this.transformedDirection) {
  48987. this.transformedDirection = BABYLON.Vector3.Zero();
  48988. }
  48989. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48990. }
  48991. return true;
  48992. }
  48993. return false;
  48994. };
  48995. /**
  48996. * Return the depth scale used for the shadow map.
  48997. * @returns the depth scale.
  48998. */
  48999. ShadowLight.prototype.getDepthScale = function () {
  49000. return 50.0;
  49001. };
  49002. /**
  49003. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49004. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49005. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49006. */
  49007. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49008. return this.transformedDirection ? this.transformedDirection : this.direction;
  49009. };
  49010. /**
  49011. * Returns the ShadowLight absolute position in the World.
  49012. * @returns the position vector in world space
  49013. */
  49014. ShadowLight.prototype.getAbsolutePosition = function () {
  49015. return this.transformedPosition ? this.transformedPosition : this.position;
  49016. };
  49017. /**
  49018. * Sets the ShadowLight direction toward the passed target.
  49019. * @param target The point tot target in local space
  49020. * @returns the updated ShadowLight direction
  49021. */
  49022. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49023. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49024. return this.direction;
  49025. };
  49026. /**
  49027. * Returns the light rotation in euler definition.
  49028. * @returns the x y z rotation in local space.
  49029. */
  49030. ShadowLight.prototype.getRotation = function () {
  49031. this.direction.normalize();
  49032. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49033. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49034. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49035. };
  49036. /**
  49037. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49038. * @returns true if a cube texture needs to be use
  49039. */
  49040. ShadowLight.prototype.needCube = function () {
  49041. return false;
  49042. };
  49043. /**
  49044. * Detects if the projection matrix requires to be recomputed this frame.
  49045. * @returns true if it requires to be recomputed otherwise, false.
  49046. */
  49047. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49048. return this._needProjectionMatrixCompute;
  49049. };
  49050. /**
  49051. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49052. */
  49053. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49054. this._needProjectionMatrixCompute = true;
  49055. };
  49056. /**
  49057. * Get the world matrix of the sahdow lights.
  49058. * @ignore Internal Use Only
  49059. */
  49060. ShadowLight.prototype._getWorldMatrix = function () {
  49061. if (!this._worldMatrix) {
  49062. this._worldMatrix = BABYLON.Matrix.Identity();
  49063. }
  49064. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49065. return this._worldMatrix;
  49066. };
  49067. /**
  49068. * Gets the minZ used for shadow according to both the scene and the light.
  49069. * @param activeCamera The camera we are returning the min for
  49070. * @returns the depth min z
  49071. */
  49072. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49073. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49074. };
  49075. /**
  49076. * Gets the maxZ used for shadow according to both the scene and the light.
  49077. * @param activeCamera The camera we are returning the max for
  49078. * @returns the depth max z
  49079. */
  49080. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49081. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49082. };
  49083. /**
  49084. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49085. * @param matrix The materix to updated with the projection information
  49086. * @param viewMatrix The transform matrix of the light
  49087. * @param renderList The list of mesh to render in the map
  49088. * @returns The current light
  49089. */
  49090. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49091. if (this.customProjectionMatrixBuilder) {
  49092. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49093. }
  49094. else {
  49095. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49096. }
  49097. return this;
  49098. };
  49099. __decorate([
  49100. BABYLON.serializeAsVector3()
  49101. ], ShadowLight.prototype, "position", null);
  49102. __decorate([
  49103. BABYLON.serializeAsVector3()
  49104. ], ShadowLight.prototype, "direction", null);
  49105. __decorate([
  49106. BABYLON.serialize()
  49107. ], ShadowLight.prototype, "shadowMinZ", null);
  49108. __decorate([
  49109. BABYLON.serialize()
  49110. ], ShadowLight.prototype, "shadowMaxZ", null);
  49111. return ShadowLight;
  49112. }(BABYLON.Light));
  49113. BABYLON.ShadowLight = ShadowLight;
  49114. })(BABYLON || (BABYLON = {}));
  49115. //# sourceMappingURL=babylon.shadowLight.js.map
  49116. var BABYLON;
  49117. (function (BABYLON) {
  49118. /**
  49119. * A point light is a light defined by an unique point in world space.
  49120. * The light is emitted in every direction from this point.
  49121. * A good example of a point light is a standard light bulb.
  49122. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49123. */
  49124. var PointLight = /** @class */ (function (_super) {
  49125. __extends(PointLight, _super);
  49126. /**
  49127. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49128. * A PointLight emits the light in every direction.
  49129. * It can cast shadows.
  49130. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49131. * ```javascript
  49132. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49133. * ```
  49134. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49135. * @param name The light friendly name
  49136. * @param position The position of the point light in the scene
  49137. * @param scene The scene the lights belongs to
  49138. */
  49139. function PointLight(name, position, scene) {
  49140. var _this = _super.call(this, name, scene) || this;
  49141. _this._shadowAngle = Math.PI / 2;
  49142. _this.position = position;
  49143. return _this;
  49144. }
  49145. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49146. /**
  49147. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49148. * This specifies what angle the shadow will use to be created.
  49149. *
  49150. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49151. */
  49152. get: function () {
  49153. return this._shadowAngle;
  49154. },
  49155. /**
  49156. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49157. * This specifies what angle the shadow will use to be created.
  49158. *
  49159. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49160. */
  49161. set: function (value) {
  49162. this._shadowAngle = value;
  49163. this.forceProjectionMatrixCompute();
  49164. },
  49165. enumerable: true,
  49166. configurable: true
  49167. });
  49168. Object.defineProperty(PointLight.prototype, "direction", {
  49169. /**
  49170. * Gets the direction if it has been set.
  49171. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49172. */
  49173. get: function () {
  49174. return this._direction;
  49175. },
  49176. /**
  49177. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49178. */
  49179. set: function (value) {
  49180. var previousNeedCube = this.needCube();
  49181. this._direction = value;
  49182. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49183. this._shadowGenerator.recreateShadowMap();
  49184. }
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. /**
  49190. * Returns the string "PointLight"
  49191. * @returns the class name
  49192. */
  49193. PointLight.prototype.getClassName = function () {
  49194. return "PointLight";
  49195. };
  49196. /**
  49197. * Returns the integer 0.
  49198. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49199. */
  49200. PointLight.prototype.getTypeID = function () {
  49201. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49202. };
  49203. /**
  49204. * Specifies wether or not the shadowmap should be a cube texture.
  49205. * @returns true if the shadowmap needs to be a cube texture.
  49206. */
  49207. PointLight.prototype.needCube = function () {
  49208. return !this.direction;
  49209. };
  49210. /**
  49211. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49212. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49213. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49214. */
  49215. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49216. if (this.direction) {
  49217. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49218. }
  49219. else {
  49220. switch (faceIndex) {
  49221. case 0:
  49222. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49223. case 1:
  49224. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49225. case 2:
  49226. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49227. case 3:
  49228. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49229. case 4:
  49230. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49231. case 5:
  49232. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49233. }
  49234. }
  49235. return BABYLON.Vector3.Zero();
  49236. };
  49237. /**
  49238. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49239. * - fov = PI / 2
  49240. * - aspect ratio : 1.0
  49241. * - z-near and far equal to the active camera minZ and maxZ.
  49242. * Returns the PointLight.
  49243. */
  49244. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49245. var activeCamera = this.getScene().activeCamera;
  49246. if (!activeCamera) {
  49247. return;
  49248. }
  49249. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49250. };
  49251. PointLight.prototype._buildUniformLayout = function () {
  49252. this._uniformBuffer.addUniform("vLightData", 4);
  49253. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49254. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49255. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49256. this._uniformBuffer.addUniform("depthValues", 2);
  49257. this._uniformBuffer.create();
  49258. };
  49259. /**
  49260. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49261. * @param effect The effect to update
  49262. * @param lightIndex The index of the light in the effect to update
  49263. * @returns The point light
  49264. */
  49265. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49266. if (this.computeTransformedInformation()) {
  49267. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49268. return this;
  49269. }
  49270. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49271. return this;
  49272. };
  49273. __decorate([
  49274. BABYLON.serialize()
  49275. ], PointLight.prototype, "shadowAngle", null);
  49276. return PointLight;
  49277. }(BABYLON.ShadowLight));
  49278. BABYLON.PointLight = PointLight;
  49279. })(BABYLON || (BABYLON = {}));
  49280. //# sourceMappingURL=babylon.pointLight.js.map
  49281. var BABYLON;
  49282. (function (BABYLON) {
  49283. /**
  49284. * A directional light is defined by a direction (what a surprise!).
  49285. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49286. * 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.
  49287. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49288. */
  49289. var DirectionalLight = /** @class */ (function (_super) {
  49290. __extends(DirectionalLight, _super);
  49291. /**
  49292. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49293. * The directional light is emitted from everywhere in the given direction.
  49294. * It can cast shawdows.
  49295. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49296. * @param name The friendly name of the light
  49297. * @param direction The direction of the light
  49298. * @param scene The scene the light belongs to
  49299. */
  49300. function DirectionalLight(name, direction, scene) {
  49301. var _this = _super.call(this, name, scene) || this;
  49302. _this._shadowFrustumSize = 0;
  49303. _this._shadowOrthoScale = 0.1;
  49304. /**
  49305. * Automatically compute the projection matrix to best fit (including all the casters)
  49306. * on each frame.
  49307. */
  49308. _this.autoUpdateExtends = true;
  49309. // Cache
  49310. _this._orthoLeft = Number.MAX_VALUE;
  49311. _this._orthoRight = Number.MIN_VALUE;
  49312. _this._orthoTop = Number.MIN_VALUE;
  49313. _this._orthoBottom = Number.MAX_VALUE;
  49314. _this.position = direction.scale(-1.0);
  49315. _this.direction = direction;
  49316. return _this;
  49317. }
  49318. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49319. /**
  49320. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49321. */
  49322. get: function () {
  49323. return this._shadowFrustumSize;
  49324. },
  49325. /**
  49326. * Specifies a fix frustum size for the shadow generation.
  49327. */
  49328. set: function (value) {
  49329. this._shadowFrustumSize = value;
  49330. this.forceProjectionMatrixCompute();
  49331. },
  49332. enumerable: true,
  49333. configurable: true
  49334. });
  49335. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49336. /**
  49337. * Gets the shadow projection scale against the optimal computed one.
  49338. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49339. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49340. */
  49341. get: function () {
  49342. return this._shadowOrthoScale;
  49343. },
  49344. /**
  49345. * Sets the shadow projection scale against the optimal computed one.
  49346. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49347. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49348. */
  49349. set: function (value) {
  49350. this._shadowOrthoScale = value;
  49351. this.forceProjectionMatrixCompute();
  49352. },
  49353. enumerable: true,
  49354. configurable: true
  49355. });
  49356. /**
  49357. * Returns the string "DirectionalLight".
  49358. * @return The class name
  49359. */
  49360. DirectionalLight.prototype.getClassName = function () {
  49361. return "DirectionalLight";
  49362. };
  49363. /**
  49364. * Returns the integer 1.
  49365. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49366. */
  49367. DirectionalLight.prototype.getTypeID = function () {
  49368. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49369. };
  49370. /**
  49371. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49372. * Returns the DirectionalLight Shadow projection matrix.
  49373. */
  49374. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49375. if (this.shadowFrustumSize > 0) {
  49376. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49377. }
  49378. else {
  49379. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49380. }
  49381. };
  49382. /**
  49383. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49384. * Returns the DirectionalLight Shadow projection matrix.
  49385. */
  49386. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49387. var activeCamera = this.getScene().activeCamera;
  49388. if (!activeCamera) {
  49389. return;
  49390. }
  49391. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49392. };
  49393. /**
  49394. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49395. * Returns the DirectionalLight Shadow projection matrix.
  49396. */
  49397. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49398. var activeCamera = this.getScene().activeCamera;
  49399. if (!activeCamera) {
  49400. return;
  49401. }
  49402. // Check extends
  49403. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49404. var tempVector3 = BABYLON.Vector3.Zero();
  49405. this._orthoLeft = Number.MAX_VALUE;
  49406. this._orthoRight = Number.MIN_VALUE;
  49407. this._orthoTop = Number.MIN_VALUE;
  49408. this._orthoBottom = Number.MAX_VALUE;
  49409. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49410. var mesh = renderList[meshIndex];
  49411. if (!mesh) {
  49412. continue;
  49413. }
  49414. var boundingInfo = mesh.getBoundingInfo();
  49415. var boundingBox = boundingInfo.boundingBox;
  49416. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49417. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49418. if (tempVector3.x < this._orthoLeft)
  49419. this._orthoLeft = tempVector3.x;
  49420. if (tempVector3.y < this._orthoBottom)
  49421. this._orthoBottom = tempVector3.y;
  49422. if (tempVector3.x > this._orthoRight)
  49423. this._orthoRight = tempVector3.x;
  49424. if (tempVector3.y > this._orthoTop)
  49425. this._orthoTop = tempVector3.y;
  49426. }
  49427. }
  49428. }
  49429. var xOffset = this._orthoRight - this._orthoLeft;
  49430. var yOffset = this._orthoTop - this._orthoBottom;
  49431. 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);
  49432. };
  49433. DirectionalLight.prototype._buildUniformLayout = function () {
  49434. this._uniformBuffer.addUniform("vLightData", 4);
  49435. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49436. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49437. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49438. this._uniformBuffer.addUniform("depthValues", 2);
  49439. this._uniformBuffer.create();
  49440. };
  49441. /**
  49442. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49443. * @param effect The effect to update
  49444. * @param lightIndex The index of the light in the effect to update
  49445. * @returns The directional light
  49446. */
  49447. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49448. if (this.computeTransformedInformation()) {
  49449. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49450. return this;
  49451. }
  49452. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49453. return this;
  49454. };
  49455. /**
  49456. * Gets the minZ used for shadow according to both the scene and the light.
  49457. *
  49458. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49459. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49460. * @param activeCamera The camera we are returning the min for
  49461. * @returns the depth min z
  49462. */
  49463. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49464. return 1;
  49465. };
  49466. /**
  49467. * Gets the maxZ used for shadow according to both the scene and the light.
  49468. *
  49469. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49470. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49471. * @param activeCamera The camera we are returning the max for
  49472. * @returns the depth max z
  49473. */
  49474. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49475. return 1;
  49476. };
  49477. __decorate([
  49478. BABYLON.serialize()
  49479. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49480. __decorate([
  49481. BABYLON.serialize()
  49482. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49483. __decorate([
  49484. BABYLON.serialize()
  49485. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49486. return DirectionalLight;
  49487. }(BABYLON.ShadowLight));
  49488. BABYLON.DirectionalLight = DirectionalLight;
  49489. })(BABYLON || (BABYLON = {}));
  49490. //# sourceMappingURL=babylon.directionalLight.js.map
  49491. var BABYLON;
  49492. (function (BABYLON) {
  49493. /**
  49494. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49495. * These values define a cone of light starting from the position, emitting toward the direction.
  49496. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49497. * and the exponent defines the speed of the decay of the light with distance (reach).
  49498. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49499. */
  49500. var SpotLight = /** @class */ (function (_super) {
  49501. __extends(SpotLight, _super);
  49502. /**
  49503. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49504. * It can cast shadows.
  49505. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49506. * @param name The light friendly name
  49507. * @param position The position of the spot light in the scene
  49508. * @param direction The direction of the light in the scene
  49509. * @param angle The cone angle of the light in Radians
  49510. * @param exponent The light decay speed with the distance from the emission spot
  49511. * @param scene The scene the lights belongs to
  49512. */
  49513. function SpotLight(name, position, direction, angle, exponent, scene) {
  49514. var _this = _super.call(this, name, scene) || this;
  49515. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49516. _this._projectionTextureLightNear = 1e-6;
  49517. _this._projectionTextureLightFar = 1000.0;
  49518. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49519. _this._projectionTextureViewLightDirty = true;
  49520. _this._projectionTextureProjectionLightDirty = true;
  49521. _this._projectionTextureDirty = true;
  49522. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49523. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49524. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49525. _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);
  49526. _this.position = position;
  49527. _this.direction = direction;
  49528. _this.angle = angle;
  49529. _this.exponent = exponent;
  49530. return _this;
  49531. }
  49532. Object.defineProperty(SpotLight.prototype, "angle", {
  49533. /**
  49534. * Gets the cone angle of the spot light in Radians.
  49535. */
  49536. get: function () {
  49537. return this._angle;
  49538. },
  49539. /**
  49540. * Sets the cone angle of the spot light in Radians.
  49541. */
  49542. set: function (value) {
  49543. this._angle = value;
  49544. this._projectionTextureProjectionLightDirty = true;
  49545. this.forceProjectionMatrixCompute();
  49546. },
  49547. enumerable: true,
  49548. configurable: true
  49549. });
  49550. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49551. /**
  49552. * Allows scaling the angle of the light for shadow generation only.
  49553. */
  49554. get: function () {
  49555. return this._shadowAngleScale;
  49556. },
  49557. /**
  49558. * Allows scaling the angle of the light for shadow generation only.
  49559. */
  49560. set: function (value) {
  49561. this._shadowAngleScale = value;
  49562. this.forceProjectionMatrixCompute();
  49563. },
  49564. enumerable: true,
  49565. configurable: true
  49566. });
  49567. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49568. /**
  49569. * Allows reading the projecton texture
  49570. */
  49571. get: function () {
  49572. return this._projectionTextureMatrix;
  49573. },
  49574. enumerable: true,
  49575. configurable: true
  49576. });
  49577. ;
  49578. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49579. /**
  49580. * Gets the near clip of the Spotlight for texture projection.
  49581. */
  49582. get: function () {
  49583. return this._projectionTextureLightNear;
  49584. },
  49585. /**
  49586. * Sets the near clip of the Spotlight for texture projection.
  49587. */
  49588. set: function (value) {
  49589. this._projectionTextureLightNear = value;
  49590. this._projectionTextureProjectionLightDirty = true;
  49591. },
  49592. enumerable: true,
  49593. configurable: true
  49594. });
  49595. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49596. /**
  49597. * Gets the far clip of the Spotlight for texture projection.
  49598. */
  49599. get: function () {
  49600. return this._projectionTextureLightFar;
  49601. },
  49602. /**
  49603. * Sets the far clip of the Spotlight for texture projection.
  49604. */
  49605. set: function (value) {
  49606. this._projectionTextureLightFar = value;
  49607. this._projectionTextureProjectionLightDirty = true;
  49608. },
  49609. enumerable: true,
  49610. configurable: true
  49611. });
  49612. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49613. /**
  49614. * Gets the Up vector of the Spotlight for texture projection.
  49615. */
  49616. get: function () {
  49617. return this._projectionTextureUpDirection;
  49618. },
  49619. /**
  49620. * Sets the Up vector of the Spotlight for texture projection.
  49621. */
  49622. set: function (value) {
  49623. this._projectionTextureUpDirection = value;
  49624. this._projectionTextureProjectionLightDirty = true;
  49625. },
  49626. enumerable: true,
  49627. configurable: true
  49628. });
  49629. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49630. /**
  49631. * Gets the projection texture of the light.
  49632. */
  49633. get: function () {
  49634. return this._projectionTexture;
  49635. },
  49636. /**
  49637. * Sets the projection texture of the light.
  49638. */
  49639. set: function (value) {
  49640. this._projectionTexture = value;
  49641. this._projectionTextureDirty = true;
  49642. },
  49643. enumerable: true,
  49644. configurable: true
  49645. });
  49646. /**
  49647. * Returns the string "SpotLight".
  49648. * @returns the class name
  49649. */
  49650. SpotLight.prototype.getClassName = function () {
  49651. return "SpotLight";
  49652. };
  49653. /**
  49654. * Returns the integer 2.
  49655. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49656. */
  49657. SpotLight.prototype.getTypeID = function () {
  49658. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49659. };
  49660. /**
  49661. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49662. */
  49663. SpotLight.prototype._setDirection = function (value) {
  49664. _super.prototype._setDirection.call(this, value);
  49665. this._projectionTextureViewLightDirty = true;
  49666. };
  49667. /**
  49668. * Overrides the position setter to recompute the projection texture view light Matrix.
  49669. */
  49670. SpotLight.prototype._setPosition = function (value) {
  49671. _super.prototype._setPosition.call(this, value);
  49672. this._projectionTextureViewLightDirty = true;
  49673. };
  49674. /**
  49675. * 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.
  49676. * Returns the SpotLight.
  49677. */
  49678. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49679. var activeCamera = this.getScene().activeCamera;
  49680. if (!activeCamera) {
  49681. return;
  49682. }
  49683. this._shadowAngleScale = this._shadowAngleScale || 1;
  49684. var angle = this._shadowAngleScale * this._angle;
  49685. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49686. };
  49687. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49688. this._projectionTextureViewLightDirty = false;
  49689. this._projectionTextureDirty = true;
  49690. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49691. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49692. };
  49693. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49694. this._projectionTextureProjectionLightDirty = false;
  49695. this._projectionTextureDirty = true;
  49696. var light_far = this.projectionTextureLightFar;
  49697. var light_near = this.projectionTextureLightNear;
  49698. var P = light_far / (light_far - light_near);
  49699. var Q = -P * light_near;
  49700. var S = 1.0 / Math.tan(this._angle / 2.0);
  49701. var A = 1.0;
  49702. 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);
  49703. };
  49704. /**
  49705. * Main function for light texture projection matrix computing.
  49706. */
  49707. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49708. this._projectionTextureDirty = false;
  49709. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49710. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49711. };
  49712. SpotLight.prototype._buildUniformLayout = function () {
  49713. this._uniformBuffer.addUniform("vLightData", 4);
  49714. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49715. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49716. this._uniformBuffer.addUniform("vLightDirection", 3);
  49717. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49718. this._uniformBuffer.addUniform("depthValues", 2);
  49719. this._uniformBuffer.create();
  49720. };
  49721. /**
  49722. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49723. * @param effect The effect to update
  49724. * @param lightIndex The index of the light in the effect to update
  49725. * @returns The spot light
  49726. */
  49727. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49728. var normalizeDirection;
  49729. if (this.computeTransformedInformation()) {
  49730. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49731. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49732. }
  49733. else {
  49734. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49735. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49736. }
  49737. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49738. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49739. if (this._projectionTextureViewLightDirty) {
  49740. this._computeProjectionTextureViewLightMatrix();
  49741. }
  49742. if (this._projectionTextureProjectionLightDirty) {
  49743. this._computeProjectionTextureProjectionLightMatrix();
  49744. }
  49745. if (this._projectionTextureDirty) {
  49746. this._computeProjectionTextureMatrix();
  49747. }
  49748. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49749. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49750. }
  49751. return this;
  49752. };
  49753. /**
  49754. * Disposes the light and the associated resources.
  49755. */
  49756. SpotLight.prototype.dispose = function () {
  49757. _super.prototype.dispose.call(this);
  49758. if (this._projectionTexture) {
  49759. this._projectionTexture.dispose();
  49760. }
  49761. };
  49762. __decorate([
  49763. BABYLON.serialize()
  49764. ], SpotLight.prototype, "angle", null);
  49765. __decorate([
  49766. BABYLON.serialize()
  49767. ], SpotLight.prototype, "shadowAngleScale", null);
  49768. __decorate([
  49769. BABYLON.serialize()
  49770. ], SpotLight.prototype, "exponent", void 0);
  49771. __decorate([
  49772. BABYLON.serialize()
  49773. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49774. __decorate([
  49775. BABYLON.serialize()
  49776. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49777. __decorate([
  49778. BABYLON.serialize()
  49779. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49780. __decorate([
  49781. BABYLON.serializeAsTexture("projectedLightTexture")
  49782. ], SpotLight.prototype, "_projectionTexture", void 0);
  49783. return SpotLight;
  49784. }(BABYLON.ShadowLight));
  49785. BABYLON.SpotLight = SpotLight;
  49786. })(BABYLON || (BABYLON = {}));
  49787. //# sourceMappingURL=babylon.spotLight.js.map
  49788. var BABYLON;
  49789. (function (BABYLON) {
  49790. /**
  49791. * Class used to override all child animations of a given target
  49792. */
  49793. var AnimationPropertiesOverride = /** @class */ (function () {
  49794. function AnimationPropertiesOverride() {
  49795. /**
  49796. * Gets or sets a value indicating if animation blending must be used
  49797. */
  49798. this.enableBlending = false;
  49799. /**
  49800. * Gets or sets the blending speed to use when enableBlending is true
  49801. */
  49802. this.blendingSpeed = 0.01;
  49803. /**
  49804. * Gets or sets the default loop mode to use
  49805. */
  49806. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49807. }
  49808. return AnimationPropertiesOverride;
  49809. }());
  49810. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49811. })(BABYLON || (BABYLON = {}));
  49812. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49813. var BABYLON;
  49814. (function (BABYLON) {
  49815. /**
  49816. * Represents the range of an animation
  49817. */
  49818. var AnimationRange = /** @class */ (function () {
  49819. /**
  49820. * Initializes the range of an animation
  49821. * @param name The name of the animation range
  49822. * @param from The starting frame of the animation
  49823. * @param to The ending frame of the animation
  49824. */
  49825. function AnimationRange(
  49826. /**The name of the animation range**/
  49827. name,
  49828. /**The starting frame of the animation */
  49829. from,
  49830. /**The ending frame of the animation*/
  49831. to) {
  49832. this.name = name;
  49833. this.from = from;
  49834. this.to = to;
  49835. }
  49836. /**
  49837. * Makes a copy of the animation range
  49838. * @returns A copy of the animation range
  49839. */
  49840. AnimationRange.prototype.clone = function () {
  49841. return new AnimationRange(this.name, this.from, this.to);
  49842. };
  49843. return AnimationRange;
  49844. }());
  49845. BABYLON.AnimationRange = AnimationRange;
  49846. /**
  49847. * Composed of a frame, and an action function
  49848. */
  49849. var AnimationEvent = /** @class */ (function () {
  49850. /**
  49851. * Initializes the animation event
  49852. * @param frame The frame for which the event is triggered
  49853. * @param action The event to perform when triggered
  49854. * @param onlyOnce Specifies if the event should be triggered only once
  49855. */
  49856. function AnimationEvent(
  49857. /** The frame for which the event is triggered **/
  49858. frame,
  49859. /** The event to perform when triggered **/
  49860. action,
  49861. /** Specifies if the event should be triggered only once**/
  49862. onlyOnce) {
  49863. this.frame = frame;
  49864. this.action = action;
  49865. this.onlyOnce = onlyOnce;
  49866. /**
  49867. * Specifies if the animation event is done
  49868. */
  49869. this.isDone = false;
  49870. }
  49871. return AnimationEvent;
  49872. }());
  49873. BABYLON.AnimationEvent = AnimationEvent;
  49874. /**
  49875. * A cursor which tracks a point on a path
  49876. */
  49877. var PathCursor = /** @class */ (function () {
  49878. /**
  49879. * Initializes the path cursor
  49880. * @param path The path to track
  49881. */
  49882. function PathCursor(path) {
  49883. this.path = path;
  49884. /**
  49885. * Stores path cursor callbacks for when an onchange event is triggered
  49886. */
  49887. this._onchange = new Array();
  49888. /**
  49889. * The value of the path cursor
  49890. */
  49891. this.value = 0;
  49892. /**
  49893. * The animation array of the path cursor
  49894. */
  49895. this.animations = new Array();
  49896. }
  49897. /**
  49898. * Gets the cursor point on the path
  49899. * @returns A point on the path cursor at the cursor location
  49900. */
  49901. PathCursor.prototype.getPoint = function () {
  49902. var point = this.path.getPointAtLengthPosition(this.value);
  49903. return new BABYLON.Vector3(point.x, 0, point.y);
  49904. };
  49905. /**
  49906. * Moves the cursor ahead by the step amount
  49907. * @param step The amount to move the cursor forward
  49908. * @returns This path cursor
  49909. */
  49910. PathCursor.prototype.moveAhead = function (step) {
  49911. if (step === void 0) { step = 0.002; }
  49912. this.move(step);
  49913. return this;
  49914. };
  49915. /**
  49916. * Moves the cursor behind by the step amount
  49917. * @param step The amount to move the cursor back
  49918. * @returns This path cursor
  49919. */
  49920. PathCursor.prototype.moveBack = function (step) {
  49921. if (step === void 0) { step = 0.002; }
  49922. this.move(-step);
  49923. return this;
  49924. };
  49925. /**
  49926. * Moves the cursor by the step amount
  49927. * If the step amount is greater than one, an exception is thrown
  49928. * @param step The amount to move the cursor
  49929. * @returns This path cursor
  49930. */
  49931. PathCursor.prototype.move = function (step) {
  49932. if (Math.abs(step) > 1) {
  49933. throw "step size should be less than 1.";
  49934. }
  49935. this.value += step;
  49936. this.ensureLimits();
  49937. this.raiseOnChange();
  49938. return this;
  49939. };
  49940. /**
  49941. * Ensures that the value is limited between zero and one
  49942. * @returns This path cursor
  49943. */
  49944. PathCursor.prototype.ensureLimits = function () {
  49945. while (this.value > 1) {
  49946. this.value -= 1;
  49947. }
  49948. while (this.value < 0) {
  49949. this.value += 1;
  49950. }
  49951. return this;
  49952. };
  49953. /**
  49954. * Runs onchange callbacks on change (used by the animation engine)
  49955. * @returns This path cursor
  49956. */
  49957. PathCursor.prototype.raiseOnChange = function () {
  49958. var _this = this;
  49959. this._onchange.forEach(function (f) { return f(_this); });
  49960. return this;
  49961. };
  49962. /**
  49963. * Executes a function on change
  49964. * @param f A path cursor onchange callback
  49965. * @returns This path cursor
  49966. */
  49967. PathCursor.prototype.onchange = function (f) {
  49968. this._onchange.push(f);
  49969. return this;
  49970. };
  49971. return PathCursor;
  49972. }());
  49973. BABYLON.PathCursor = PathCursor;
  49974. /**
  49975. * Enum for the animation key frame interpolation type
  49976. */
  49977. var AnimationKeyInterpolation;
  49978. (function (AnimationKeyInterpolation) {
  49979. /**
  49980. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49981. */
  49982. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49983. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49984. /**
  49985. * Class used to store any kind of animation
  49986. */
  49987. var Animation = /** @class */ (function () {
  49988. /**
  49989. * Initializes the animation
  49990. * @param name Name of the animation
  49991. * @param targetProperty Property to animate
  49992. * @param framePerSecond The frames per second of the animation
  49993. * @param dataType The data type of the animation
  49994. * @param loopMode The loop mode of the animation
  49995. * @param enableBlendings Specifies if blending should be enabled
  49996. */
  49997. function Animation(
  49998. /**Name of the animation */
  49999. name,
  50000. /**Property to animate */
  50001. targetProperty,
  50002. /**The frames per second of the animation */
  50003. framePerSecond,
  50004. /**The data type of the animation */
  50005. dataType,
  50006. /**The loop mode of the animation */
  50007. loopMode,
  50008. /**Specifies if blending should be enabled */
  50009. enableBlending) {
  50010. this.name = name;
  50011. this.targetProperty = targetProperty;
  50012. this.framePerSecond = framePerSecond;
  50013. this.dataType = dataType;
  50014. this.loopMode = loopMode;
  50015. this.enableBlending = enableBlending;
  50016. /**
  50017. * @ignore Internal use only
  50018. */
  50019. this._runtimeAnimations = new Array();
  50020. /**
  50021. * The set of event that will be linked to this animation
  50022. */
  50023. this._events = new Array();
  50024. /**
  50025. * Stores the blending speed of the animation
  50026. */
  50027. this.blendingSpeed = 0.01;
  50028. /**
  50029. * Stores the animation ranges for the animation
  50030. */
  50031. this._ranges = {};
  50032. this.targetPropertyPath = targetProperty.split(".");
  50033. this.dataType = dataType;
  50034. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50035. }
  50036. /**
  50037. * @ignore Internal use
  50038. */
  50039. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50040. var dataType = undefined;
  50041. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50042. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50043. }
  50044. else if (from instanceof BABYLON.Quaternion) {
  50045. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50046. }
  50047. else if (from instanceof BABYLON.Vector3) {
  50048. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50049. }
  50050. else if (from instanceof BABYLON.Vector2) {
  50051. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50052. }
  50053. else if (from instanceof BABYLON.Color3) {
  50054. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50055. }
  50056. else if (from instanceof BABYLON.Size) {
  50057. dataType = Animation.ANIMATIONTYPE_SIZE;
  50058. }
  50059. if (dataType == undefined) {
  50060. return null;
  50061. }
  50062. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50063. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50064. animation.setKeys(keys);
  50065. if (easingFunction !== undefined) {
  50066. animation.setEasingFunction(easingFunction);
  50067. }
  50068. return animation;
  50069. };
  50070. /**
  50071. * Sets up an animation
  50072. * @param property The property to animate
  50073. * @param animationType The animation type to apply
  50074. * @param framePerSecond The frames per second of the animation
  50075. * @param easingFunction The easing function used in the animation
  50076. * @returns The created animation
  50077. */
  50078. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50079. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50080. animation.setEasingFunction(easingFunction);
  50081. return animation;
  50082. };
  50083. /**
  50084. * Create and start an animation on a node
  50085. * @param name defines the name of the global animation that will be run on all nodes
  50086. * @param node defines the root node where the animation will take place
  50087. * @param targetProperty defines property to animate
  50088. * @param framePerSecond defines the number of frame per second yo use
  50089. * @param totalFrame defines the number of frames in total
  50090. * @param from defines the initial value
  50091. * @param to defines the final value
  50092. * @param loopMode defines which loop mode you want to use (off by default)
  50093. * @param easingFunction defines the easing function to use (linear by default)
  50094. * @param onAnimationEnd defines the callback to call when animation end
  50095. * @returns the animatable created for this animation
  50096. */
  50097. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50098. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50099. if (!animation) {
  50100. return null;
  50101. }
  50102. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50103. };
  50104. /**
  50105. * Create and start an animation on a node and its descendants
  50106. * @param name defines the name of the global animation that will be run on all nodes
  50107. * @param node defines the root node where the animation will take place
  50108. * @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
  50109. * @param targetProperty defines property to animate
  50110. * @param framePerSecond defines the number of frame per second to use
  50111. * @param totalFrame defines the number of frames in total
  50112. * @param from defines the initial value
  50113. * @param to defines the final value
  50114. * @param loopMode defines which loop mode you want to use (off by default)
  50115. * @param easingFunction defines the easing function to use (linear by default)
  50116. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50117. * @returns the list of animatables created for all nodes
  50118. * @example https://www.babylonjs-playground.com/#MH0VLI
  50119. */
  50120. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50121. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50122. if (!animation) {
  50123. return null;
  50124. }
  50125. var scene = node.getScene();
  50126. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50127. };
  50128. /**
  50129. * Creates a new animation, merges it with the existing animations and starts it
  50130. * @param name Name of the animation
  50131. * @param node Node which contains the scene that begins the animations
  50132. * @param targetProperty Specifies which property to animate
  50133. * @param framePerSecond The frames per second of the animation
  50134. * @param totalFrame The total number of frames
  50135. * @param from The frame at the beginning of the animation
  50136. * @param to The frame at the end of the animation
  50137. * @param loopMode Specifies the loop mode of the animation
  50138. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50139. * @param onAnimationEnd Callback to run once the animation is complete
  50140. * @returns Nullable animation
  50141. */
  50142. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50143. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50144. if (!animation) {
  50145. return null;
  50146. }
  50147. node.animations.push(animation);
  50148. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50149. };
  50150. /**
  50151. * Transition property of the Camera to the target Value
  50152. * @param property The property to transition
  50153. * @param targetValue The target Value of the property
  50154. * @param host The object where the property to animate belongs
  50155. * @param scene Scene used to run the animation
  50156. * @param frameRate Framerate (in frame/s) to use
  50157. * @param transition The transition type we want to use
  50158. * @param duration The duration of the animation, in milliseconds
  50159. * @param onAnimationEnd Callback trigger at the end of the animation
  50160. * @returns Nullable animation
  50161. */
  50162. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50163. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50164. if (duration <= 0) {
  50165. host[property] = targetValue;
  50166. if (onAnimationEnd) {
  50167. onAnimationEnd();
  50168. }
  50169. return null;
  50170. }
  50171. var endFrame = frameRate * (duration / 1000);
  50172. transition.setKeys([{
  50173. frame: 0,
  50174. value: host[property].clone ? host[property].clone() : host[property]
  50175. },
  50176. {
  50177. frame: endFrame,
  50178. value: targetValue
  50179. }]);
  50180. if (!host.animations) {
  50181. host.animations = [];
  50182. }
  50183. host.animations.push(transition);
  50184. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50185. animation.onAnimationEnd = onAnimationEnd;
  50186. return animation;
  50187. };
  50188. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50189. /**
  50190. * Return the array of runtime animations currently using this animation
  50191. */
  50192. get: function () {
  50193. return this._runtimeAnimations;
  50194. },
  50195. enumerable: true,
  50196. configurable: true
  50197. });
  50198. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50199. /**
  50200. * Specifies if any of the runtime animations are currently running
  50201. */
  50202. get: function () {
  50203. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50204. var runtimeAnimation = _a[_i];
  50205. if (!runtimeAnimation.isStopped) {
  50206. return true;
  50207. }
  50208. }
  50209. return false;
  50210. },
  50211. enumerable: true,
  50212. configurable: true
  50213. });
  50214. // Methods
  50215. /**
  50216. * Converts the animation to a string
  50217. * @param fullDetails support for multiple levels of logging within scene loading
  50218. * @returns String form of the animation
  50219. */
  50220. Animation.prototype.toString = function (fullDetails) {
  50221. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50222. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50223. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50224. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50225. if (fullDetails) {
  50226. ret += ", Ranges: {";
  50227. var first = true;
  50228. for (var name in this._ranges) {
  50229. if (first) {
  50230. ret += ", ";
  50231. first = false;
  50232. }
  50233. ret += name;
  50234. }
  50235. ret += "}";
  50236. }
  50237. return ret;
  50238. };
  50239. /**
  50240. * Add an event to this animation
  50241. * @param event Event to add
  50242. */
  50243. Animation.prototype.addEvent = function (event) {
  50244. this._events.push(event);
  50245. };
  50246. /**
  50247. * Remove all events found at the given frame
  50248. * @param frame The frame to remove events from
  50249. */
  50250. Animation.prototype.removeEvents = function (frame) {
  50251. for (var index = 0; index < this._events.length; index++) {
  50252. if (this._events[index].frame === frame) {
  50253. this._events.splice(index, 1);
  50254. index--;
  50255. }
  50256. }
  50257. };
  50258. /**
  50259. * Retrieves all the events from the animation
  50260. * @returns Events from the animation
  50261. */
  50262. Animation.prototype.getEvents = function () {
  50263. return this._events;
  50264. };
  50265. /**
  50266. * Creates an animation range
  50267. * @param name Name of the animation range
  50268. * @param from Starting frame of the animation range
  50269. * @param to Ending frame of the animation
  50270. */
  50271. Animation.prototype.createRange = function (name, from, to) {
  50272. // check name not already in use; could happen for bones after serialized
  50273. if (!this._ranges[name]) {
  50274. this._ranges[name] = new AnimationRange(name, from, to);
  50275. }
  50276. };
  50277. /**
  50278. * Deletes an animation range by name
  50279. * @param name Name of the animation range to delete
  50280. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50281. */
  50282. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50283. if (deleteFrames === void 0) { deleteFrames = true; }
  50284. var range = this._ranges[name];
  50285. if (!range) {
  50286. return;
  50287. }
  50288. if (deleteFrames) {
  50289. var from = range.from;
  50290. var to = range.to;
  50291. // this loop MUST go high to low for multiple splices to work
  50292. for (var key = this._keys.length - 1; key >= 0; key--) {
  50293. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50294. this._keys.splice(key, 1);
  50295. }
  50296. }
  50297. }
  50298. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50299. };
  50300. /**
  50301. * Gets the animation range by name, or null if not defined
  50302. * @param name Name of the animation range
  50303. * @returns Nullable animation range
  50304. */
  50305. Animation.prototype.getRange = function (name) {
  50306. return this._ranges[name];
  50307. };
  50308. /**
  50309. * Gets the key frames from the animation
  50310. * @returns The key frames of the animation
  50311. */
  50312. Animation.prototype.getKeys = function () {
  50313. return this._keys;
  50314. };
  50315. /**
  50316. * Gets the highest frame rate of the animation
  50317. * @returns Highest frame rate of the animation
  50318. */
  50319. Animation.prototype.getHighestFrame = function () {
  50320. var ret = 0;
  50321. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50322. if (ret < this._keys[key].frame) {
  50323. ret = this._keys[key].frame;
  50324. }
  50325. }
  50326. return ret;
  50327. };
  50328. /**
  50329. * Gets the easing function of the animation
  50330. * @returns Easing function of the animation
  50331. */
  50332. Animation.prototype.getEasingFunction = function () {
  50333. return this._easingFunction;
  50334. };
  50335. /**
  50336. * Sets the easing function of the animation
  50337. * @param easingFunction A custom mathematical formula for animation
  50338. */
  50339. Animation.prototype.setEasingFunction = function (easingFunction) {
  50340. this._easingFunction = easingFunction;
  50341. };
  50342. /**
  50343. * Interpolates a scalar linearly
  50344. * @param startValue Start value of the animation curve
  50345. * @param endValue End value of the animation curve
  50346. * @param gradient Scalar amount to interpolate
  50347. * @returns Interpolated scalar value
  50348. */
  50349. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50350. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50351. };
  50352. /**
  50353. * Interpolates a scalar cubically
  50354. * @param startValue Start value of the animation curve
  50355. * @param outTangent End tangent of the animation
  50356. * @param endValue End value of the animation curve
  50357. * @param inTangent Start tangent of the animation curve
  50358. * @param gradient Scalar amount to interpolate
  50359. * @returns Interpolated scalar value
  50360. */
  50361. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50362. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50363. };
  50364. /**
  50365. * Interpolates a quaternion using a spherical linear interpolation
  50366. * @param startValue Start value of the animation curve
  50367. * @param endValue End value of the animation curve
  50368. * @param gradient Scalar amount to interpolate
  50369. * @returns Interpolated quaternion value
  50370. */
  50371. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50372. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50373. };
  50374. /**
  50375. * Interpolates a quaternion cubically
  50376. * @param startValue Start value of the animation curve
  50377. * @param outTangent End tangent of the animation curve
  50378. * @param endValue End value of the animation curve
  50379. * @param inTangent Start tangent of the animation curve
  50380. * @param gradient Scalar amount to interpolate
  50381. * @returns Interpolated quaternion value
  50382. */
  50383. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50384. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50385. };
  50386. /**
  50387. * Interpolates a Vector3 linearl
  50388. * @param startValue Start value of the animation curve
  50389. * @param endValue End value of the animation curve
  50390. * @param gradient Scalar amount to interpolate
  50391. * @returns Interpolated scalar value
  50392. */
  50393. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50394. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50395. };
  50396. /**
  50397. * Interpolates a Vector3 cubically
  50398. * @param startValue Start value of the animation curve
  50399. * @param outTangent End tangent of the animation
  50400. * @param endValue End value of the animation curve
  50401. * @param inTangent Start tangent of the animation curve
  50402. * @param gradient Scalar amount to interpolate
  50403. * @returns InterpolatedVector3 value
  50404. */
  50405. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50406. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50407. };
  50408. /**
  50409. * Interpolates a Vector2 linearly
  50410. * @param startValue Start value of the animation curve
  50411. * @param endValue End value of the animation curve
  50412. * @param gradient Scalar amount to interpolate
  50413. * @returns Interpolated Vector2 value
  50414. */
  50415. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50416. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50417. };
  50418. /**
  50419. * Interpolates a Vector2 cubically
  50420. * @param startValue Start value of the animation curve
  50421. * @param outTangent End tangent of the animation
  50422. * @param endValue End value of the animation curve
  50423. * @param inTangent Start tangent of the animation curve
  50424. * @param gradient Scalar amount to interpolate
  50425. * @returns Interpolated Vector2 value
  50426. */
  50427. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50428. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50429. };
  50430. /**
  50431. * Interpolates a size linearly
  50432. * @param startValue Start value of the animation curve
  50433. * @param endValue End value of the animation curve
  50434. * @param gradient Scalar amount to interpolate
  50435. * @returns Interpolated Size value
  50436. */
  50437. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50438. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50439. };
  50440. /**
  50441. * Interpolates a Color3 linearly
  50442. * @param startValue Start value of the animation curve
  50443. * @param endValue End value of the animation curve
  50444. * @param gradient Scalar amount to interpolate
  50445. * @returns Interpolated Color3 value
  50446. */
  50447. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50448. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50449. };
  50450. /**
  50451. * @ignore Internal use only
  50452. */
  50453. Animation.prototype._getKeyValue = function (value) {
  50454. if (typeof value === "function") {
  50455. return value();
  50456. }
  50457. return value;
  50458. };
  50459. /**
  50460. * @ignore Internal use only
  50461. */
  50462. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50463. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50464. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50465. }
  50466. var keys = this.getKeys();
  50467. // Try to get a hash to find the right key
  50468. 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));
  50469. if (keys[startKeyIndex].frame >= currentFrame) {
  50470. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50471. startKeyIndex--;
  50472. }
  50473. }
  50474. for (var key = startKeyIndex; key < keys.length; key++) {
  50475. var endKey = keys[key + 1];
  50476. if (endKey.frame >= currentFrame) {
  50477. var startKey = keys[key];
  50478. var startValue = this._getKeyValue(startKey.value);
  50479. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50480. return startValue;
  50481. }
  50482. var endValue = this._getKeyValue(endKey.value);
  50483. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50484. var frameDelta = endKey.frame - startKey.frame;
  50485. // gradient : percent of currentFrame between the frame inf and the frame sup
  50486. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50487. // check for easingFunction and correction of gradient
  50488. var easingFunction = this.getEasingFunction();
  50489. if (easingFunction != null) {
  50490. gradient = easingFunction.ease(gradient);
  50491. }
  50492. switch (this.dataType) {
  50493. // Float
  50494. case Animation.ANIMATIONTYPE_FLOAT:
  50495. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50496. switch (loopMode) {
  50497. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50498. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50499. return floatValue;
  50500. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50501. return offsetValue * repeatCount + floatValue;
  50502. }
  50503. break;
  50504. // Quaternion
  50505. case Animation.ANIMATIONTYPE_QUATERNION:
  50506. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50507. switch (loopMode) {
  50508. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50509. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50510. return quatValue;
  50511. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50512. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50513. }
  50514. return quatValue;
  50515. // Vector3
  50516. case Animation.ANIMATIONTYPE_VECTOR3:
  50517. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50518. switch (loopMode) {
  50519. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50520. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50521. return vec3Value;
  50522. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50523. return vec3Value.add(offsetValue.scale(repeatCount));
  50524. }
  50525. // Vector2
  50526. case Animation.ANIMATIONTYPE_VECTOR2:
  50527. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50528. switch (loopMode) {
  50529. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50530. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50531. return vec2Value;
  50532. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50533. return vec2Value.add(offsetValue.scale(repeatCount));
  50534. }
  50535. // Size
  50536. case Animation.ANIMATIONTYPE_SIZE:
  50537. switch (loopMode) {
  50538. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50539. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50540. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50541. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50542. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50543. }
  50544. // Color3
  50545. case Animation.ANIMATIONTYPE_COLOR3:
  50546. switch (loopMode) {
  50547. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50548. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50549. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50550. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50551. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50552. }
  50553. // Matrix
  50554. case Animation.ANIMATIONTYPE_MATRIX:
  50555. switch (loopMode) {
  50556. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50557. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50558. if (Animation.AllowMatricesInterpolation) {
  50559. workValue = this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50560. return workValue;
  50561. }
  50562. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50563. return startValue;
  50564. }
  50565. default:
  50566. break;
  50567. }
  50568. break;
  50569. }
  50570. }
  50571. return this._getKeyValue(keys[keys.length - 1].value);
  50572. };
  50573. /**
  50574. * Defines the function to use to interpolate matrices
  50575. * @param startValue defines the start matrix
  50576. * @param endValue defines the end matrix
  50577. * @param gradient defines the gradient between both matrices
  50578. * @param result defines an optional target matrix where to store the interpolation
  50579. * @returns the interpolated matrix
  50580. */
  50581. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50582. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50583. if (result) {
  50584. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50585. return result;
  50586. }
  50587. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50588. }
  50589. if (result) {
  50590. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50591. return result;
  50592. }
  50593. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50594. };
  50595. /**
  50596. * Makes a copy of the animation
  50597. * @returns Cloned animation
  50598. */
  50599. Animation.prototype.clone = function () {
  50600. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50601. clone.enableBlending = this.enableBlending;
  50602. clone.blendingSpeed = this.blendingSpeed;
  50603. if (this._keys) {
  50604. clone.setKeys(this._keys);
  50605. }
  50606. if (this._ranges) {
  50607. clone._ranges = {};
  50608. for (var name in this._ranges) {
  50609. var range = this._ranges[name];
  50610. if (!range) {
  50611. continue;
  50612. }
  50613. clone._ranges[name] = range.clone();
  50614. }
  50615. }
  50616. return clone;
  50617. };
  50618. /**
  50619. * Sets the key frames of the animation
  50620. * @param values The animation key frames to set
  50621. */
  50622. Animation.prototype.setKeys = function (values) {
  50623. this._keys = values.slice(0);
  50624. };
  50625. /**
  50626. * Serializes the animation to an object
  50627. * @returns Serialized object
  50628. */
  50629. Animation.prototype.serialize = function () {
  50630. var serializationObject = {};
  50631. serializationObject.name = this.name;
  50632. serializationObject.property = this.targetProperty;
  50633. serializationObject.framePerSecond = this.framePerSecond;
  50634. serializationObject.dataType = this.dataType;
  50635. serializationObject.loopBehavior = this.loopMode;
  50636. serializationObject.enableBlending = this.enableBlending;
  50637. serializationObject.blendingSpeed = this.blendingSpeed;
  50638. var dataType = this.dataType;
  50639. serializationObject.keys = [];
  50640. var keys = this.getKeys();
  50641. for (var index = 0; index < keys.length; index++) {
  50642. var animationKey = keys[index];
  50643. var key = {};
  50644. key.frame = animationKey.frame;
  50645. switch (dataType) {
  50646. case Animation.ANIMATIONTYPE_FLOAT:
  50647. key.values = [animationKey.value];
  50648. break;
  50649. case Animation.ANIMATIONTYPE_QUATERNION:
  50650. case Animation.ANIMATIONTYPE_MATRIX:
  50651. case Animation.ANIMATIONTYPE_VECTOR3:
  50652. case Animation.ANIMATIONTYPE_COLOR3:
  50653. key.values = animationKey.value.asArray();
  50654. break;
  50655. }
  50656. serializationObject.keys.push(key);
  50657. }
  50658. serializationObject.ranges = [];
  50659. for (var name in this._ranges) {
  50660. var source = this._ranges[name];
  50661. if (!source) {
  50662. continue;
  50663. }
  50664. var range = {};
  50665. range.name = name;
  50666. range.from = source.from;
  50667. range.to = source.to;
  50668. serializationObject.ranges.push(range);
  50669. }
  50670. return serializationObject;
  50671. };
  50672. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50673. /**
  50674. * Get the float animation type
  50675. */
  50676. get: function () {
  50677. return Animation._ANIMATIONTYPE_FLOAT;
  50678. },
  50679. enumerable: true,
  50680. configurable: true
  50681. });
  50682. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50683. /**
  50684. * Get the Vector3 animation type
  50685. */
  50686. get: function () {
  50687. return Animation._ANIMATIONTYPE_VECTOR3;
  50688. },
  50689. enumerable: true,
  50690. configurable: true
  50691. });
  50692. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50693. /**
  50694. * Get the Vectpr2 animation type
  50695. */
  50696. get: function () {
  50697. return Animation._ANIMATIONTYPE_VECTOR2;
  50698. },
  50699. enumerable: true,
  50700. configurable: true
  50701. });
  50702. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50703. /**
  50704. * Get the Size animation type
  50705. */
  50706. get: function () {
  50707. return Animation._ANIMATIONTYPE_SIZE;
  50708. },
  50709. enumerable: true,
  50710. configurable: true
  50711. });
  50712. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50713. /**
  50714. * Get the Quaternion animation type
  50715. */
  50716. get: function () {
  50717. return Animation._ANIMATIONTYPE_QUATERNION;
  50718. },
  50719. enumerable: true,
  50720. configurable: true
  50721. });
  50722. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50723. /**
  50724. * Get the Matrix animation type
  50725. */
  50726. get: function () {
  50727. return Animation._ANIMATIONTYPE_MATRIX;
  50728. },
  50729. enumerable: true,
  50730. configurable: true
  50731. });
  50732. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50733. /**
  50734. * Get the Color3 animation type
  50735. */
  50736. get: function () {
  50737. return Animation._ANIMATIONTYPE_COLOR3;
  50738. },
  50739. enumerable: true,
  50740. configurable: true
  50741. });
  50742. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50743. /**
  50744. * Get the Relative Loop Mode
  50745. */
  50746. get: function () {
  50747. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50748. },
  50749. enumerable: true,
  50750. configurable: true
  50751. });
  50752. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50753. /**
  50754. * Get the Cycle Loop Mode
  50755. */
  50756. get: function () {
  50757. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50758. },
  50759. enumerable: true,
  50760. configurable: true
  50761. });
  50762. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50763. /**
  50764. * Get the Constant Loop Mode
  50765. */
  50766. get: function () {
  50767. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50768. },
  50769. enumerable: true,
  50770. configurable: true
  50771. });
  50772. /**
  50773. * Parses an animation object and creates an animation
  50774. * @param parsedAnimation Parsed animation object
  50775. * @returns Animation object
  50776. */
  50777. Animation.Parse = function (parsedAnimation) {
  50778. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50779. var dataType = parsedAnimation.dataType;
  50780. var keys = [];
  50781. var data;
  50782. var index;
  50783. if (parsedAnimation.enableBlending) {
  50784. animation.enableBlending = parsedAnimation.enableBlending;
  50785. }
  50786. if (parsedAnimation.blendingSpeed) {
  50787. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50788. }
  50789. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50790. var key = parsedAnimation.keys[index];
  50791. var inTangent;
  50792. var outTangent;
  50793. switch (dataType) {
  50794. case Animation.ANIMATIONTYPE_FLOAT:
  50795. data = key.values[0];
  50796. if (key.values.length >= 1) {
  50797. inTangent = key.values[1];
  50798. }
  50799. if (key.values.length >= 2) {
  50800. outTangent = key.values[2];
  50801. }
  50802. break;
  50803. case Animation.ANIMATIONTYPE_QUATERNION:
  50804. data = BABYLON.Quaternion.FromArray(key.values);
  50805. if (key.values.length >= 8) {
  50806. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50807. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50808. inTangent = _inTangent;
  50809. }
  50810. }
  50811. if (key.values.length >= 12) {
  50812. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50813. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50814. outTangent = _outTangent;
  50815. }
  50816. }
  50817. break;
  50818. case Animation.ANIMATIONTYPE_MATRIX:
  50819. data = BABYLON.Matrix.FromArray(key.values);
  50820. break;
  50821. case Animation.ANIMATIONTYPE_COLOR3:
  50822. data = BABYLON.Color3.FromArray(key.values);
  50823. break;
  50824. case Animation.ANIMATIONTYPE_VECTOR3:
  50825. default:
  50826. data = BABYLON.Vector3.FromArray(key.values);
  50827. break;
  50828. }
  50829. var keyData = {};
  50830. keyData.frame = key.frame;
  50831. keyData.value = data;
  50832. if (inTangent != undefined) {
  50833. keyData.inTangent = inTangent;
  50834. }
  50835. if (outTangent != undefined) {
  50836. keyData.outTangent = outTangent;
  50837. }
  50838. keys.push(keyData);
  50839. }
  50840. animation.setKeys(keys);
  50841. if (parsedAnimation.ranges) {
  50842. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50843. data = parsedAnimation.ranges[index];
  50844. animation.createRange(data.name, data.from, data.to);
  50845. }
  50846. }
  50847. return animation;
  50848. };
  50849. /**
  50850. * Appends the serialized animations from the source animations
  50851. * @param source Source containing the animations
  50852. * @param destination Target to store the animations
  50853. */
  50854. Animation.AppendSerializedAnimations = function (source, destination) {
  50855. if (source.animations) {
  50856. destination.animations = [];
  50857. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50858. var animation = source.animations[animationIndex];
  50859. destination.animations.push(animation.serialize());
  50860. }
  50861. }
  50862. };
  50863. /**
  50864. * Use matrix interpolation instead of using direct key value when animating matrices
  50865. */
  50866. Animation.AllowMatricesInterpolation = false;
  50867. /**
  50868. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50869. */
  50870. Animation.AllowMatrixDecomposeForInterpolation = true;
  50871. // Statics
  50872. /**
  50873. * Float animation type
  50874. */
  50875. Animation._ANIMATIONTYPE_FLOAT = 0;
  50876. /**
  50877. * Vector3 animation type
  50878. */
  50879. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50880. /**
  50881. * Quaternion animation type
  50882. */
  50883. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50884. /**
  50885. * Matrix animation type
  50886. */
  50887. Animation._ANIMATIONTYPE_MATRIX = 3;
  50888. /**
  50889. * Color3 animation type
  50890. */
  50891. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50892. /**
  50893. * Vector2 animation type
  50894. */
  50895. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50896. /**
  50897. * Size animation type
  50898. */
  50899. Animation._ANIMATIONTYPE_SIZE = 6;
  50900. /**
  50901. * Relative Loop Mode
  50902. */
  50903. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50904. /**
  50905. * Cycle Loop Mode
  50906. */
  50907. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50908. /**
  50909. * Constant Loop Mode
  50910. */
  50911. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50912. return Animation;
  50913. }());
  50914. BABYLON.Animation = Animation;
  50915. })(BABYLON || (BABYLON = {}));
  50916. //# sourceMappingURL=babylon.animation.js.map
  50917. var BABYLON;
  50918. (function (BABYLON) {
  50919. /**
  50920. * This class defines the direct association between an animation and a target
  50921. */
  50922. var TargetedAnimation = /** @class */ (function () {
  50923. function TargetedAnimation() {
  50924. }
  50925. return TargetedAnimation;
  50926. }());
  50927. BABYLON.TargetedAnimation = TargetedAnimation;
  50928. /**
  50929. * Use this class to create coordinated animations on multiple targets
  50930. */
  50931. var AnimationGroup = /** @class */ (function () {
  50932. function AnimationGroup(name, scene) {
  50933. if (scene === void 0) { scene = null; }
  50934. this.name = name;
  50935. this._targetedAnimations = new Array();
  50936. this._animatables = new Array();
  50937. this._from = Number.MAX_VALUE;
  50938. this._to = -Number.MAX_VALUE;
  50939. this._speedRatio = 1;
  50940. this.onAnimationEndObservable = new BABYLON.Observable();
  50941. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50942. this._scene.animationGroups.push(this);
  50943. }
  50944. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50945. /**
  50946. * Define if the animations are started
  50947. */
  50948. get: function () {
  50949. return this._isStarted;
  50950. },
  50951. enumerable: true,
  50952. configurable: true
  50953. });
  50954. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50955. /**
  50956. * Gets or sets the speed ratio to use for all animations
  50957. */
  50958. get: function () {
  50959. return this._speedRatio;
  50960. },
  50961. /**
  50962. * Gets or sets the speed ratio to use for all animations
  50963. */
  50964. set: function (value) {
  50965. if (this._speedRatio === value) {
  50966. return;
  50967. }
  50968. this._speedRatio = value;
  50969. for (var index = 0; index < this._animatables.length; index++) {
  50970. var animatable = this._animatables[index];
  50971. animatable.speedRatio = this._speedRatio;
  50972. }
  50973. },
  50974. enumerable: true,
  50975. configurable: true
  50976. });
  50977. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50978. /**
  50979. * Gets the targeted animations for this animation group
  50980. */
  50981. get: function () {
  50982. return this._targetedAnimations;
  50983. },
  50984. enumerable: true,
  50985. configurable: true
  50986. });
  50987. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50988. /**
  50989. * returning the list of animatables controlled by this animation group.
  50990. */
  50991. get: function () {
  50992. return this._animatables;
  50993. },
  50994. enumerable: true,
  50995. configurable: true
  50996. });
  50997. /**
  50998. * Add an animation (with its target) in the group
  50999. * @param animation defines the animation we want to add
  51000. * @param target defines the target of the animation
  51001. * @returns the {BABYLON.TargetedAnimation} object
  51002. */
  51003. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51004. var targetedAnimation = {
  51005. animation: animation,
  51006. target: target
  51007. };
  51008. var keys = animation.getKeys();
  51009. if (this._from > keys[0].frame) {
  51010. this._from = keys[0].frame;
  51011. }
  51012. if (this._to < keys[keys.length - 1].frame) {
  51013. this._to = keys[keys.length - 1].frame;
  51014. }
  51015. this._targetedAnimations.push(targetedAnimation);
  51016. return targetedAnimation;
  51017. };
  51018. /**
  51019. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51020. * It can add constant keys at begin or end
  51021. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51022. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51023. */
  51024. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51025. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51026. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51027. beginFrame = Math.max(beginFrame, this._from);
  51028. endFrame = Math.min(endFrame, this._to);
  51029. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51030. var targetedAnimation = this._targetedAnimations[index];
  51031. var keys = targetedAnimation.animation.getKeys();
  51032. var startKey = keys[0];
  51033. var endKey = keys[keys.length - 1];
  51034. if (startKey.frame > beginFrame) {
  51035. var newKey = {
  51036. frame: beginFrame,
  51037. value: startKey.value,
  51038. inTangent: startKey.inTangent,
  51039. outTangent: startKey.outTangent,
  51040. interpolation: startKey.interpolation
  51041. };
  51042. keys.splice(0, 0, newKey);
  51043. }
  51044. if (endKey.frame < endFrame) {
  51045. var newKey = {
  51046. frame: endFrame,
  51047. value: endKey.value,
  51048. inTangent: endKey.outTangent,
  51049. outTangent: endKey.outTangent,
  51050. interpolation: endKey.interpolation
  51051. };
  51052. keys.push(newKey);
  51053. }
  51054. }
  51055. return this;
  51056. };
  51057. /**
  51058. * Start all animations on given targets
  51059. * @param loop defines if animations must loop
  51060. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51061. * @param from defines the from key (optional)
  51062. * @param to defines the to key (optional)
  51063. * @returns the current animation group
  51064. */
  51065. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51066. var _this = this;
  51067. if (loop === void 0) { loop = false; }
  51068. if (speedRatio === void 0) { speedRatio = 1; }
  51069. if (this._isStarted || this._targetedAnimations.length === 0) {
  51070. return this;
  51071. }
  51072. var _loop_1 = function (targetedAnimation) {
  51073. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51074. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51075. }));
  51076. };
  51077. var this_1 = this;
  51078. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51079. var targetedAnimation = _a[_i];
  51080. _loop_1(targetedAnimation);
  51081. }
  51082. this._speedRatio = speedRatio;
  51083. this._isStarted = true;
  51084. return this;
  51085. };
  51086. /**
  51087. * Pause all animations
  51088. */
  51089. AnimationGroup.prototype.pause = function () {
  51090. if (!this._isStarted) {
  51091. return this;
  51092. }
  51093. for (var index = 0; index < this._animatables.length; index++) {
  51094. var animatable = this._animatables[index];
  51095. animatable.pause();
  51096. }
  51097. return this;
  51098. };
  51099. /**
  51100. * Play all animations to initial state
  51101. * This function will start() the animations if they were not started or will restart() them if they were paused
  51102. * @param loop defines if animations must loop
  51103. */
  51104. AnimationGroup.prototype.play = function (loop) {
  51105. if (this.isStarted) {
  51106. if (loop !== undefined) {
  51107. for (var index = 0; index < this._animatables.length; index++) {
  51108. var animatable = this._animatables[index];
  51109. animatable.loopAnimation = loop;
  51110. }
  51111. }
  51112. this.restart();
  51113. }
  51114. else {
  51115. this.start(loop, this._speedRatio);
  51116. }
  51117. return this;
  51118. };
  51119. /**
  51120. * Reset all animations to initial state
  51121. */
  51122. AnimationGroup.prototype.reset = function () {
  51123. if (!this._isStarted) {
  51124. return this;
  51125. }
  51126. for (var index = 0; index < this._animatables.length; index++) {
  51127. var animatable = this._animatables[index];
  51128. animatable.reset();
  51129. }
  51130. return this;
  51131. };
  51132. /**
  51133. * Restart animations from key 0
  51134. */
  51135. AnimationGroup.prototype.restart = function () {
  51136. if (!this._isStarted) {
  51137. return this;
  51138. }
  51139. for (var index = 0; index < this._animatables.length; index++) {
  51140. var animatable = this._animatables[index];
  51141. animatable.restart();
  51142. }
  51143. return this;
  51144. };
  51145. /**
  51146. * Stop all animations
  51147. */
  51148. AnimationGroup.prototype.stop = function () {
  51149. if (!this._isStarted) {
  51150. return this;
  51151. }
  51152. for (var index = 0; index < this._animatables.length; index++) {
  51153. var animatable = this._animatables[index];
  51154. animatable.stop();
  51155. }
  51156. this._isStarted = false;
  51157. return this;
  51158. };
  51159. /**
  51160. * Set animation weight for all animatables
  51161. * @param weight defines the weight to use
  51162. * @return the animationGroup
  51163. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51164. */
  51165. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51166. for (var index = 0; index < this._animatables.length; index++) {
  51167. var animatable = this._animatables[index];
  51168. animatable.weight = weight;
  51169. }
  51170. return this;
  51171. };
  51172. /**
  51173. * Synchronize and normalize all animatables with a source animatable
  51174. * @param root defines the root animatable to synchronize with
  51175. * @return the animationGroup
  51176. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51177. */
  51178. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51179. for (var index = 0; index < this._animatables.length; index++) {
  51180. var animatable = this._animatables[index];
  51181. animatable.syncWith(root);
  51182. }
  51183. return this;
  51184. };
  51185. /**
  51186. * Goes to a specific frame in this animation group
  51187. * @param frame the frame number to go to
  51188. * @return the animationGroup
  51189. */
  51190. AnimationGroup.prototype.goToFrame = function (frame) {
  51191. if (!this._isStarted) {
  51192. return this;
  51193. }
  51194. for (var index = 0; index < this._animatables.length; index++) {
  51195. var animatable = this._animatables[index];
  51196. animatable.goToFrame(frame);
  51197. }
  51198. return this;
  51199. };
  51200. /**
  51201. * Dispose all associated resources
  51202. */
  51203. AnimationGroup.prototype.dispose = function () {
  51204. this._targetedAnimations = [];
  51205. this._animatables = [];
  51206. var index = this._scene.animationGroups.indexOf(this);
  51207. if (index > -1) {
  51208. this._scene.animationGroups.splice(index, 1);
  51209. }
  51210. };
  51211. return AnimationGroup;
  51212. }());
  51213. BABYLON.AnimationGroup = AnimationGroup;
  51214. })(BABYLON || (BABYLON = {}));
  51215. //# sourceMappingURL=babylon.animationGroup.js.map
  51216. var BABYLON;
  51217. (function (BABYLON) {
  51218. /**
  51219. * Defines a runtime animation
  51220. */
  51221. var RuntimeAnimation = /** @class */ (function () {
  51222. /**
  51223. * Create a new RuntimeAnimation object
  51224. * @param target defines the target of the animation
  51225. * @param animation defines the source animation object
  51226. * @param scene defines the hosting scene
  51227. * @param host defines the initiating Animatable
  51228. */
  51229. function RuntimeAnimation(target, animation, scene, host) {
  51230. /**
  51231. * The current frame of the runtime animation
  51232. */
  51233. this._currentFrame = 0;
  51234. /**
  51235. * The offsets cache of the runtime animation
  51236. */
  51237. this._offsetsCache = {};
  51238. /**
  51239. * The high limits cache of the runtime animation
  51240. */
  51241. this._highLimitsCache = {};
  51242. /**
  51243. * Specifies if the runtime animation has been stopped
  51244. */
  51245. this._stopped = false;
  51246. /**
  51247. * The blending factor of the runtime animation
  51248. */
  51249. this._blendingFactor = 0;
  51250. /**
  51251. * The target path of the runtime animation
  51252. */
  51253. this._targetPath = "";
  51254. /**
  51255. * The weight of the runtime animation
  51256. */
  51257. this._weight = 1.0;
  51258. /**
  51259. * The ratio offset of the runtime animation
  51260. */
  51261. this._ratioOffset = 0;
  51262. /**
  51263. * The previous delay of the runtime animation
  51264. */
  51265. this._previousDelay = 0;
  51266. /**
  51267. * The previous ratio of the runtime animation
  51268. */
  51269. this._previousRatio = 0;
  51270. this._animation = animation;
  51271. this._target = target;
  51272. this._scene = scene;
  51273. this._host = host;
  51274. animation._runtimeAnimations.push(this);
  51275. }
  51276. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51277. /**
  51278. * Gets the current frame of the runtime animation
  51279. */
  51280. get: function () {
  51281. return this._currentFrame;
  51282. },
  51283. enumerable: true,
  51284. configurable: true
  51285. });
  51286. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51287. /**
  51288. * Gets the weight of the runtime animation
  51289. */
  51290. get: function () {
  51291. return this._weight;
  51292. },
  51293. enumerable: true,
  51294. configurable: true
  51295. });
  51296. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51297. /**
  51298. * Gets the original value of the runtime animation
  51299. */
  51300. get: function () {
  51301. return this._originalValue;
  51302. },
  51303. enumerable: true,
  51304. configurable: true
  51305. });
  51306. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51307. /**
  51308. * Gets the current value of the runtime animation
  51309. */
  51310. get: function () {
  51311. return this._currentValue;
  51312. },
  51313. enumerable: true,
  51314. configurable: true
  51315. });
  51316. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51317. /**
  51318. * Gets the target path of the runtime animation
  51319. */
  51320. get: function () {
  51321. return this._targetPath;
  51322. },
  51323. enumerable: true,
  51324. configurable: true
  51325. });
  51326. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51327. /**
  51328. * Gets the actual target of the runtime animation
  51329. */
  51330. get: function () {
  51331. return this._activeTarget;
  51332. },
  51333. enumerable: true,
  51334. configurable: true
  51335. });
  51336. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51337. /**
  51338. * Gets the animation from the runtime animation
  51339. */
  51340. get: function () {
  51341. return this._animation;
  51342. },
  51343. enumerable: true,
  51344. configurable: true
  51345. });
  51346. /**
  51347. * Resets the runtime animation to the beginning
  51348. */
  51349. RuntimeAnimation.prototype.reset = function () {
  51350. this._offsetsCache = {};
  51351. this._highLimitsCache = {};
  51352. this._currentFrame = 0;
  51353. this._blendingFactor = 0;
  51354. this._originalValue = null;
  51355. };
  51356. /**
  51357. * Specifies if the runtime animation is stopped
  51358. * @returns Boolean specifying if the runtime animation is stopped
  51359. */
  51360. RuntimeAnimation.prototype.isStopped = function () {
  51361. return this._stopped;
  51362. };
  51363. /**
  51364. * Disposes of the runtime animation
  51365. */
  51366. RuntimeAnimation.prototype.dispose = function () {
  51367. var index = this._animation.runtimeAnimations.indexOf(this);
  51368. if (index > -1) {
  51369. this._animation.runtimeAnimations.splice(index, 1);
  51370. }
  51371. };
  51372. /**
  51373. * Interpolates the animation from the current frame
  51374. * @param currentFrame The frame to interpolate the animation to
  51375. * @param repeatCount The number of times that the animation should loop
  51376. * @param loopMode The type of looping mode to use
  51377. * @param offsetValue Animation offset value
  51378. * @param highLimitValue The high limit value
  51379. * @returns The interpolated value
  51380. */
  51381. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51382. this._currentFrame = currentFrame;
  51383. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51384. };
  51385. /**
  51386. * Affect the interpolated value to the target
  51387. * @param currentValue defines the value computed by the animation
  51388. * @param weight defines the weight to apply to this value
  51389. */
  51390. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51391. if (weight === void 0) { weight = 1.0; }
  51392. if (this._target instanceof Array) {
  51393. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51394. var target = _a[_i];
  51395. this._setValue(target, currentValue, weight);
  51396. }
  51397. }
  51398. else {
  51399. this._setValue(this._target, currentValue, weight);
  51400. }
  51401. };
  51402. /**
  51403. * Sets the value of the runtime animation
  51404. * @param target The target property of the runtime animation
  51405. * @param currentValue The current value to use for the runtime animation
  51406. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51407. */
  51408. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51409. if (weight === void 0) { weight = 1.0; }
  51410. // Set value
  51411. var path;
  51412. var destination;
  51413. var targetPropertyPath = this._animation.targetPropertyPath;
  51414. if (targetPropertyPath.length > 1) {
  51415. var property = target[targetPropertyPath[0]];
  51416. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51417. property = property[targetPropertyPath[index]];
  51418. }
  51419. path = targetPropertyPath[targetPropertyPath.length - 1];
  51420. destination = property;
  51421. }
  51422. else {
  51423. path = targetPropertyPath[0];
  51424. destination = target;
  51425. }
  51426. this._targetPath = path;
  51427. this._activeTarget = destination;
  51428. this._weight = weight;
  51429. // Blending
  51430. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51431. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51432. if (enableBlending && this._blendingFactor <= 1.0) {
  51433. if (!this._originalBlendValue) {
  51434. var originalValue = destination[path];
  51435. if (originalValue.clone) {
  51436. this._originalBlendValue = originalValue.clone();
  51437. }
  51438. else {
  51439. this._originalBlendValue = originalValue;
  51440. }
  51441. }
  51442. }
  51443. if (weight !== -1.0) {
  51444. if (!this._originalValue) {
  51445. var originalValue = void 0;
  51446. if (destination.getRestPose) { // For bones
  51447. originalValue = destination.getRestPose();
  51448. }
  51449. else {
  51450. originalValue = destination[path];
  51451. }
  51452. if (originalValue.clone) {
  51453. this._originalValue = originalValue.clone();
  51454. }
  51455. else {
  51456. this._originalValue = originalValue;
  51457. }
  51458. }
  51459. }
  51460. if (enableBlending && this._blendingFactor <= 1.0) {
  51461. if (this._originalBlendValue.m) { // Matrix
  51462. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51463. if (this._currentValue) {
  51464. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51465. }
  51466. else {
  51467. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51468. }
  51469. }
  51470. else {
  51471. if (this._currentValue) {
  51472. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51473. }
  51474. else {
  51475. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51476. }
  51477. }
  51478. }
  51479. else {
  51480. var constructor = this._originalBlendValue.constructor;
  51481. if (constructor.Lerp) { // Lerp supported
  51482. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51483. }
  51484. else if (constructor.Slerp) { // Slerp supported
  51485. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51486. }
  51487. else if (this._originalBlendValue.toFixed) { // Number
  51488. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51489. }
  51490. else { // Blending not supported
  51491. this._currentValue = currentValue;
  51492. }
  51493. }
  51494. this._blendingFactor += blendingSpeed;
  51495. }
  51496. else {
  51497. this._currentValue = currentValue;
  51498. }
  51499. if (weight !== -1.0) {
  51500. this._scene._registerTargetForLateAnimationBinding(this);
  51501. }
  51502. else {
  51503. destination[path] = this._currentValue;
  51504. }
  51505. if (target.markAsDirty) {
  51506. target.markAsDirty(this._animation.targetProperty);
  51507. }
  51508. };
  51509. /**
  51510. * Gets the loop pmode of the runtime animation
  51511. * @returns Loop Mode
  51512. */
  51513. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51514. if (this._target && this._target.animationPropertiesOverride) {
  51515. return this._target.animationPropertiesOverride.loopMode;
  51516. }
  51517. return this._animation.loopMode;
  51518. };
  51519. /**
  51520. * Move the current animation to a given frame
  51521. * @param frame defines the frame to move to
  51522. */
  51523. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51524. var keys = this._animation.getKeys();
  51525. if (frame < keys[0].frame) {
  51526. frame = keys[0].frame;
  51527. }
  51528. else if (frame > keys[keys.length - 1].frame) {
  51529. frame = keys[keys.length - 1].frame;
  51530. }
  51531. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51532. this.setValue(currentValue, -1);
  51533. };
  51534. /**
  51535. * @ignore Internal use only
  51536. */
  51537. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51538. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51539. this._ratioOffset = this._previousRatio - newRatio;
  51540. };
  51541. /**
  51542. * Execute the current animation
  51543. * @param delay defines the delay to add to the current frame
  51544. * @param from defines the lower bound of the animation range
  51545. * @param to defines the upper bound of the animation range
  51546. * @param loop defines if the current animation must loop
  51547. * @param speedRatio defines the current speed ratio
  51548. * @param weight defines the weight of the animation (default is -1 so no weight)
  51549. * @returns a boolean indicating if the animation has ended
  51550. */
  51551. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51552. if (weight === void 0) { weight = -1.0; }
  51553. var targetPropertyPath = this._animation.targetPropertyPath;
  51554. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51555. this._stopped = true;
  51556. return false;
  51557. }
  51558. var returnValue = true;
  51559. var keys = this._animation.getKeys();
  51560. // Adding a start key at frame 0 if missing
  51561. if (keys[0].frame !== 0) {
  51562. var newKey = { frame: 0, value: keys[0].value };
  51563. keys.splice(0, 0, newKey);
  51564. }
  51565. // Check limits
  51566. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51567. from = keys[0].frame;
  51568. }
  51569. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51570. to = keys[keys.length - 1].frame;
  51571. }
  51572. //to and from cannot be the same key
  51573. if (from === to) {
  51574. if (from > keys[0].frame) {
  51575. from--;
  51576. }
  51577. else if (to < keys[keys.length - 1].frame) {
  51578. to++;
  51579. }
  51580. }
  51581. // Compute ratio
  51582. var range = to - from;
  51583. var offsetValue;
  51584. // ratio represents the frame delta between from and to
  51585. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51586. var highLimitValue = 0;
  51587. this._previousDelay = delay;
  51588. this._previousRatio = ratio;
  51589. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51590. returnValue = false;
  51591. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51592. }
  51593. else {
  51594. // Get max value if required
  51595. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51596. var keyOffset = to.toString() + from.toString();
  51597. if (!this._offsetsCache[keyOffset]) {
  51598. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51599. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51600. switch (this._animation.dataType) {
  51601. // Float
  51602. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51603. this._offsetsCache[keyOffset] = toValue - fromValue;
  51604. break;
  51605. // Quaternion
  51606. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51607. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51608. break;
  51609. // Vector3
  51610. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51611. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51612. // Vector2
  51613. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51614. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51615. // Size
  51616. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51617. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51618. // Color3
  51619. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51620. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51621. default:
  51622. break;
  51623. }
  51624. this._highLimitsCache[keyOffset] = toValue;
  51625. }
  51626. highLimitValue = this._highLimitsCache[keyOffset];
  51627. offsetValue = this._offsetsCache[keyOffset];
  51628. }
  51629. }
  51630. if (offsetValue === undefined) {
  51631. switch (this._animation.dataType) {
  51632. // Float
  51633. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51634. offsetValue = 0;
  51635. break;
  51636. // Quaternion
  51637. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51638. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51639. break;
  51640. // Vector3
  51641. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51642. offsetValue = BABYLON.Vector3.Zero();
  51643. break;
  51644. // Vector2
  51645. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51646. offsetValue = BABYLON.Vector2.Zero();
  51647. break;
  51648. // Size
  51649. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51650. offsetValue = BABYLON.Size.Zero();
  51651. break;
  51652. // Color3
  51653. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51654. offsetValue = BABYLON.Color3.Black();
  51655. }
  51656. }
  51657. // Compute value
  51658. var repeatCount = (ratio / range) >> 0;
  51659. var currentFrame = returnValue ? from + ratio % range : to;
  51660. // Need to normalize?
  51661. if (this._host && this._host.syncRoot) {
  51662. var syncRoot = this._host.syncRoot;
  51663. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51664. currentFrame = from + (to - from) * hostNormalizedFrame;
  51665. }
  51666. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51667. // Set value
  51668. this.setValue(currentValue, weight);
  51669. // Check events
  51670. var events = this._animation.getEvents();
  51671. for (var index = 0; index < events.length; index++) {
  51672. // Make sure current frame has passed event frame and that event frame is within the current range
  51673. // Also, handle both forward and reverse animations
  51674. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51675. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51676. var event = events[index];
  51677. if (!event.isDone) {
  51678. // If event should be done only once, remove it.
  51679. if (event.onlyOnce) {
  51680. events.splice(index, 1);
  51681. index--;
  51682. }
  51683. event.isDone = true;
  51684. event.action();
  51685. } // Don't do anything if the event has already be done.
  51686. }
  51687. else if (events[index].isDone && !events[index].onlyOnce) {
  51688. // reset event, the animation is looping
  51689. events[index].isDone = false;
  51690. }
  51691. }
  51692. if (!returnValue) {
  51693. this._stopped = true;
  51694. }
  51695. return returnValue;
  51696. };
  51697. return RuntimeAnimation;
  51698. }());
  51699. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51700. })(BABYLON || (BABYLON = {}));
  51701. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51702. var BABYLON;
  51703. (function (BABYLON) {
  51704. var Animatable = /** @class */ (function () {
  51705. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51706. if (fromFrame === void 0) { fromFrame = 0; }
  51707. if (toFrame === void 0) { toFrame = 100; }
  51708. if (loopAnimation === void 0) { loopAnimation = false; }
  51709. if (speedRatio === void 0) { speedRatio = 1.0; }
  51710. this.target = target;
  51711. this.fromFrame = fromFrame;
  51712. this.toFrame = toFrame;
  51713. this.loopAnimation = loopAnimation;
  51714. this.onAnimationEnd = onAnimationEnd;
  51715. this._localDelayOffset = null;
  51716. this._pausedDelay = null;
  51717. this._runtimeAnimations = new Array();
  51718. this._paused = false;
  51719. this._speedRatio = 1;
  51720. this._weight = -1.0;
  51721. this.animationStarted = false;
  51722. this._scene = scene;
  51723. if (animations) {
  51724. this.appendAnimations(target, animations);
  51725. }
  51726. this._speedRatio = speedRatio;
  51727. scene._activeAnimatables.push(this);
  51728. }
  51729. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51730. /**
  51731. * Gets the root Animatable used to synchronize and normalize animations
  51732. */
  51733. get: function () {
  51734. return this._syncRoot;
  51735. },
  51736. enumerable: true,
  51737. configurable: true
  51738. });
  51739. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51740. /**
  51741. * Gets the current frame of the first RuntimeAnimation
  51742. * Used to synchronize Animatables
  51743. */
  51744. get: function () {
  51745. if (this._runtimeAnimations.length === 0) {
  51746. return 0;
  51747. }
  51748. return this._runtimeAnimations[0].currentFrame;
  51749. },
  51750. enumerable: true,
  51751. configurable: true
  51752. });
  51753. Object.defineProperty(Animatable.prototype, "weight", {
  51754. /**
  51755. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51756. */
  51757. get: function () {
  51758. return this._weight;
  51759. },
  51760. set: function (value) {
  51761. if (value === -1) { // -1 is ok and means no weight
  51762. this._weight = -1;
  51763. return;
  51764. }
  51765. // Else weight must be in [0, 1] range
  51766. this._weight = Math.min(Math.max(value, 0), 1.0);
  51767. },
  51768. enumerable: true,
  51769. configurable: true
  51770. });
  51771. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51772. /**
  51773. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51774. */
  51775. get: function () {
  51776. return this._speedRatio;
  51777. },
  51778. set: function (value) {
  51779. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51780. var animation = this._runtimeAnimations[index];
  51781. animation._prepareForSpeedRatioChange(value);
  51782. }
  51783. this._speedRatio = value;
  51784. },
  51785. enumerable: true,
  51786. configurable: true
  51787. });
  51788. // Methods
  51789. /**
  51790. * Synchronize and normalize current Animatable with a source Animatable
  51791. * This is useful when using animation weights and when animations are not of the same length
  51792. * @param root defines the root Animatable to synchronize with
  51793. * @returns the current Animatable
  51794. */
  51795. Animatable.prototype.syncWith = function (root) {
  51796. this._syncRoot = root;
  51797. if (root) {
  51798. // Make sure this animatable will animate after the root
  51799. var index = this._scene._activeAnimatables.indexOf(this);
  51800. if (index > -1) {
  51801. this._scene._activeAnimatables.splice(index, 1);
  51802. this._scene._activeAnimatables.push(this);
  51803. }
  51804. }
  51805. return this;
  51806. };
  51807. Animatable.prototype.getAnimations = function () {
  51808. return this._runtimeAnimations;
  51809. };
  51810. Animatable.prototype.appendAnimations = function (target, animations) {
  51811. for (var index = 0; index < animations.length; index++) {
  51812. var animation = animations[index];
  51813. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51814. }
  51815. };
  51816. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51817. var runtimeAnimations = this._runtimeAnimations;
  51818. for (var index = 0; index < runtimeAnimations.length; index++) {
  51819. if (runtimeAnimations[index].animation.targetProperty === property) {
  51820. return runtimeAnimations[index].animation;
  51821. }
  51822. }
  51823. return null;
  51824. };
  51825. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51826. var runtimeAnimations = this._runtimeAnimations;
  51827. for (var index = 0; index < runtimeAnimations.length; index++) {
  51828. if (runtimeAnimations[index].animation.targetProperty === property) {
  51829. return runtimeAnimations[index];
  51830. }
  51831. }
  51832. return null;
  51833. };
  51834. Animatable.prototype.reset = function () {
  51835. var runtimeAnimations = this._runtimeAnimations;
  51836. for (var index = 0; index < runtimeAnimations.length; index++) {
  51837. runtimeAnimations[index].reset();
  51838. }
  51839. // Reset to original value
  51840. for (index = 0; index < runtimeAnimations.length; index++) {
  51841. var animation = runtimeAnimations[index];
  51842. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  51843. }
  51844. this._localDelayOffset = null;
  51845. this._pausedDelay = null;
  51846. };
  51847. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51848. var runtimeAnimations = this._runtimeAnimations;
  51849. for (var index = 0; index < runtimeAnimations.length; index++) {
  51850. runtimeAnimations[index].animation.enableBlending = true;
  51851. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51852. }
  51853. };
  51854. Animatable.prototype.disableBlending = function () {
  51855. var runtimeAnimations = this._runtimeAnimations;
  51856. for (var index = 0; index < runtimeAnimations.length; index++) {
  51857. runtimeAnimations[index].animation.enableBlending = false;
  51858. }
  51859. };
  51860. Animatable.prototype.goToFrame = function (frame) {
  51861. var runtimeAnimations = this._runtimeAnimations;
  51862. if (runtimeAnimations[0]) {
  51863. var fps = runtimeAnimations[0].animation.framePerSecond;
  51864. var currentFrame = runtimeAnimations[0].currentFrame;
  51865. var adjustTime = frame - currentFrame;
  51866. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51867. if (this._localDelayOffset === null) {
  51868. this._localDelayOffset = 0;
  51869. }
  51870. this._localDelayOffset -= delay;
  51871. }
  51872. for (var index = 0; index < runtimeAnimations.length; index++) {
  51873. runtimeAnimations[index].goToFrame(frame);
  51874. }
  51875. };
  51876. Animatable.prototype.pause = function () {
  51877. if (this._paused) {
  51878. return;
  51879. }
  51880. this._paused = true;
  51881. };
  51882. Animatable.prototype.restart = function () {
  51883. this._paused = false;
  51884. };
  51885. Animatable.prototype.stop = function (animationName) {
  51886. if (animationName) {
  51887. var idx = this._scene._activeAnimatables.indexOf(this);
  51888. if (idx > -1) {
  51889. var runtimeAnimations = this._runtimeAnimations;
  51890. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51891. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51892. continue;
  51893. }
  51894. runtimeAnimations[index].dispose();
  51895. runtimeAnimations.splice(index, 1);
  51896. }
  51897. if (runtimeAnimations.length == 0) {
  51898. this._scene._activeAnimatables.splice(idx, 1);
  51899. if (this.onAnimationEnd) {
  51900. this.onAnimationEnd();
  51901. }
  51902. }
  51903. }
  51904. }
  51905. else {
  51906. var index = this._scene._activeAnimatables.indexOf(this);
  51907. if (index > -1) {
  51908. this._scene._activeAnimatables.splice(index, 1);
  51909. var runtimeAnimations = this._runtimeAnimations;
  51910. for (var index = 0; index < runtimeAnimations.length; index++) {
  51911. runtimeAnimations[index].dispose();
  51912. }
  51913. if (this.onAnimationEnd) {
  51914. this.onAnimationEnd();
  51915. }
  51916. }
  51917. }
  51918. };
  51919. Animatable.prototype._animate = function (delay) {
  51920. if (this._paused) {
  51921. this.animationStarted = false;
  51922. if (this._pausedDelay === null) {
  51923. this._pausedDelay = delay;
  51924. }
  51925. return true;
  51926. }
  51927. if (this._localDelayOffset === null) {
  51928. this._localDelayOffset = delay;
  51929. this._pausedDelay = null;
  51930. }
  51931. else if (this._pausedDelay !== null) {
  51932. this._localDelayOffset += delay - this._pausedDelay;
  51933. this._pausedDelay = null;
  51934. }
  51935. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51936. return true;
  51937. }
  51938. // Animating
  51939. var running = false;
  51940. var runtimeAnimations = this._runtimeAnimations;
  51941. var index;
  51942. for (index = 0; index < runtimeAnimations.length; index++) {
  51943. var animation = runtimeAnimations[index];
  51944. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51945. running = running || isRunning;
  51946. }
  51947. this.animationStarted = running;
  51948. if (!running) {
  51949. // Remove from active animatables
  51950. index = this._scene._activeAnimatables.indexOf(this);
  51951. this._scene._activeAnimatables.splice(index, 1);
  51952. // Dispose all runtime animations
  51953. for (index = 0; index < runtimeAnimations.length; index++) {
  51954. runtimeAnimations[index].dispose();
  51955. }
  51956. }
  51957. if (!running && this.onAnimationEnd) {
  51958. this.onAnimationEnd();
  51959. this.onAnimationEnd = null;
  51960. }
  51961. return running;
  51962. };
  51963. return Animatable;
  51964. }());
  51965. BABYLON.Animatable = Animatable;
  51966. })(BABYLON || (BABYLON = {}));
  51967. //# sourceMappingURL=babylon.animatable.js.map
  51968. var BABYLON;
  51969. (function (BABYLON) {
  51970. var EasingFunction = /** @class */ (function () {
  51971. function EasingFunction() {
  51972. // Properties
  51973. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51974. }
  51975. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51976. get: function () {
  51977. return EasingFunction._EASINGMODE_EASEIN;
  51978. },
  51979. enumerable: true,
  51980. configurable: true
  51981. });
  51982. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51983. get: function () {
  51984. return EasingFunction._EASINGMODE_EASEOUT;
  51985. },
  51986. enumerable: true,
  51987. configurable: true
  51988. });
  51989. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51990. get: function () {
  51991. return EasingFunction._EASINGMODE_EASEINOUT;
  51992. },
  51993. enumerable: true,
  51994. configurable: true
  51995. });
  51996. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51997. var n = Math.min(Math.max(easingMode, 0), 2);
  51998. this._easingMode = n;
  51999. };
  52000. EasingFunction.prototype.getEasingMode = function () {
  52001. return this._easingMode;
  52002. };
  52003. EasingFunction.prototype.easeInCore = function (gradient) {
  52004. throw new Error('You must implement this method');
  52005. };
  52006. EasingFunction.prototype.ease = function (gradient) {
  52007. switch (this._easingMode) {
  52008. case EasingFunction.EASINGMODE_EASEIN:
  52009. return this.easeInCore(gradient);
  52010. case EasingFunction.EASINGMODE_EASEOUT:
  52011. return (1 - this.easeInCore(1 - gradient));
  52012. }
  52013. if (gradient >= 0.5) {
  52014. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52015. }
  52016. return (this.easeInCore(gradient * 2) * 0.5);
  52017. };
  52018. //Statics
  52019. EasingFunction._EASINGMODE_EASEIN = 0;
  52020. EasingFunction._EASINGMODE_EASEOUT = 1;
  52021. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52022. return EasingFunction;
  52023. }());
  52024. BABYLON.EasingFunction = EasingFunction;
  52025. var CircleEase = /** @class */ (function (_super) {
  52026. __extends(CircleEase, _super);
  52027. function CircleEase() {
  52028. return _super !== null && _super.apply(this, arguments) || this;
  52029. }
  52030. CircleEase.prototype.easeInCore = function (gradient) {
  52031. gradient = Math.max(0, Math.min(1, gradient));
  52032. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52033. };
  52034. return CircleEase;
  52035. }(EasingFunction));
  52036. BABYLON.CircleEase = CircleEase;
  52037. var BackEase = /** @class */ (function (_super) {
  52038. __extends(BackEase, _super);
  52039. function BackEase(amplitude) {
  52040. if (amplitude === void 0) { amplitude = 1; }
  52041. var _this = _super.call(this) || this;
  52042. _this.amplitude = amplitude;
  52043. return _this;
  52044. }
  52045. BackEase.prototype.easeInCore = function (gradient) {
  52046. var num = Math.max(0, this.amplitude);
  52047. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52048. };
  52049. return BackEase;
  52050. }(EasingFunction));
  52051. BABYLON.BackEase = BackEase;
  52052. var BounceEase = /** @class */ (function (_super) {
  52053. __extends(BounceEase, _super);
  52054. function BounceEase(bounces, bounciness) {
  52055. if (bounces === void 0) { bounces = 3; }
  52056. if (bounciness === void 0) { bounciness = 2; }
  52057. var _this = _super.call(this) || this;
  52058. _this.bounces = bounces;
  52059. _this.bounciness = bounciness;
  52060. return _this;
  52061. }
  52062. BounceEase.prototype.easeInCore = function (gradient) {
  52063. var y = Math.max(0.0, this.bounces);
  52064. var bounciness = this.bounciness;
  52065. if (bounciness <= 1.0) {
  52066. bounciness = 1.001;
  52067. }
  52068. var num9 = Math.pow(bounciness, y);
  52069. var num5 = 1.0 - bounciness;
  52070. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52071. var num15 = gradient * num4;
  52072. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52073. var num3 = Math.floor(num65);
  52074. var num13 = num3 + 1.0;
  52075. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52076. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52077. var num7 = (num8 + num12) * 0.5;
  52078. var num6 = gradient - num7;
  52079. var num2 = num7 - num8;
  52080. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52081. };
  52082. return BounceEase;
  52083. }(EasingFunction));
  52084. BABYLON.BounceEase = BounceEase;
  52085. var CubicEase = /** @class */ (function (_super) {
  52086. __extends(CubicEase, _super);
  52087. function CubicEase() {
  52088. return _super !== null && _super.apply(this, arguments) || this;
  52089. }
  52090. CubicEase.prototype.easeInCore = function (gradient) {
  52091. return (gradient * gradient * gradient);
  52092. };
  52093. return CubicEase;
  52094. }(EasingFunction));
  52095. BABYLON.CubicEase = CubicEase;
  52096. var ElasticEase = /** @class */ (function (_super) {
  52097. __extends(ElasticEase, _super);
  52098. function ElasticEase(oscillations, springiness) {
  52099. if (oscillations === void 0) { oscillations = 3; }
  52100. if (springiness === void 0) { springiness = 3; }
  52101. var _this = _super.call(this) || this;
  52102. _this.oscillations = oscillations;
  52103. _this.springiness = springiness;
  52104. return _this;
  52105. }
  52106. ElasticEase.prototype.easeInCore = function (gradient) {
  52107. var num2;
  52108. var num3 = Math.max(0.0, this.oscillations);
  52109. var num = Math.max(0.0, this.springiness);
  52110. if (num == 0) {
  52111. num2 = gradient;
  52112. }
  52113. else {
  52114. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52115. }
  52116. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52117. };
  52118. return ElasticEase;
  52119. }(EasingFunction));
  52120. BABYLON.ElasticEase = ElasticEase;
  52121. var ExponentialEase = /** @class */ (function (_super) {
  52122. __extends(ExponentialEase, _super);
  52123. function ExponentialEase(exponent) {
  52124. if (exponent === void 0) { exponent = 2; }
  52125. var _this = _super.call(this) || this;
  52126. _this.exponent = exponent;
  52127. return _this;
  52128. }
  52129. ExponentialEase.prototype.easeInCore = function (gradient) {
  52130. if (this.exponent <= 0) {
  52131. return gradient;
  52132. }
  52133. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52134. };
  52135. return ExponentialEase;
  52136. }(EasingFunction));
  52137. BABYLON.ExponentialEase = ExponentialEase;
  52138. var PowerEase = /** @class */ (function (_super) {
  52139. __extends(PowerEase, _super);
  52140. function PowerEase(power) {
  52141. if (power === void 0) { power = 2; }
  52142. var _this = _super.call(this) || this;
  52143. _this.power = power;
  52144. return _this;
  52145. }
  52146. PowerEase.prototype.easeInCore = function (gradient) {
  52147. var y = Math.max(0.0, this.power);
  52148. return Math.pow(gradient, y);
  52149. };
  52150. return PowerEase;
  52151. }(EasingFunction));
  52152. BABYLON.PowerEase = PowerEase;
  52153. var QuadraticEase = /** @class */ (function (_super) {
  52154. __extends(QuadraticEase, _super);
  52155. function QuadraticEase() {
  52156. return _super !== null && _super.apply(this, arguments) || this;
  52157. }
  52158. QuadraticEase.prototype.easeInCore = function (gradient) {
  52159. return (gradient * gradient);
  52160. };
  52161. return QuadraticEase;
  52162. }(EasingFunction));
  52163. BABYLON.QuadraticEase = QuadraticEase;
  52164. var QuarticEase = /** @class */ (function (_super) {
  52165. __extends(QuarticEase, _super);
  52166. function QuarticEase() {
  52167. return _super !== null && _super.apply(this, arguments) || this;
  52168. }
  52169. QuarticEase.prototype.easeInCore = function (gradient) {
  52170. return (gradient * gradient * gradient * gradient);
  52171. };
  52172. return QuarticEase;
  52173. }(EasingFunction));
  52174. BABYLON.QuarticEase = QuarticEase;
  52175. var QuinticEase = /** @class */ (function (_super) {
  52176. __extends(QuinticEase, _super);
  52177. function QuinticEase() {
  52178. return _super !== null && _super.apply(this, arguments) || this;
  52179. }
  52180. QuinticEase.prototype.easeInCore = function (gradient) {
  52181. return (gradient * gradient * gradient * gradient * gradient);
  52182. };
  52183. return QuinticEase;
  52184. }(EasingFunction));
  52185. BABYLON.QuinticEase = QuinticEase;
  52186. var SineEase = /** @class */ (function (_super) {
  52187. __extends(SineEase, _super);
  52188. function SineEase() {
  52189. return _super !== null && _super.apply(this, arguments) || this;
  52190. }
  52191. SineEase.prototype.easeInCore = function (gradient) {
  52192. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52193. };
  52194. return SineEase;
  52195. }(EasingFunction));
  52196. BABYLON.SineEase = SineEase;
  52197. var BezierCurveEase = /** @class */ (function (_super) {
  52198. __extends(BezierCurveEase, _super);
  52199. function BezierCurveEase(x1, y1, x2, y2) {
  52200. if (x1 === void 0) { x1 = 0; }
  52201. if (y1 === void 0) { y1 = 0; }
  52202. if (x2 === void 0) { x2 = 1; }
  52203. if (y2 === void 0) { y2 = 1; }
  52204. var _this = _super.call(this) || this;
  52205. _this.x1 = x1;
  52206. _this.y1 = y1;
  52207. _this.x2 = x2;
  52208. _this.y2 = y2;
  52209. return _this;
  52210. }
  52211. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52212. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52213. };
  52214. return BezierCurveEase;
  52215. }(EasingFunction));
  52216. BABYLON.BezierCurveEase = BezierCurveEase;
  52217. })(BABYLON || (BABYLON = {}));
  52218. //# sourceMappingURL=babylon.easing.js.map
  52219. var BABYLON;
  52220. (function (BABYLON) {
  52221. /**
  52222. * A Condition applied to an Action
  52223. */
  52224. var Condition = /** @class */ (function () {
  52225. /**
  52226. * Creates a new Condition
  52227. * @param actionManager the manager of the action the condition is applied to
  52228. */
  52229. function Condition(actionManager) {
  52230. this._actionManager = actionManager;
  52231. }
  52232. /**
  52233. * Check if the current condition is valid
  52234. * @returns a boolean
  52235. */
  52236. Condition.prototype.isValid = function () {
  52237. return true;
  52238. };
  52239. /**
  52240. * Internal only
  52241. * @ignore
  52242. */
  52243. Condition.prototype._getProperty = function (propertyPath) {
  52244. return this._actionManager._getProperty(propertyPath);
  52245. };
  52246. /**
  52247. * Internal only
  52248. * @ignore
  52249. */
  52250. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52251. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52252. };
  52253. /**
  52254. * Serialize placeholder for child classes
  52255. * @returns the serialized object
  52256. */
  52257. Condition.prototype.serialize = function () {
  52258. };
  52259. /**
  52260. * Internal only
  52261. * @ignore
  52262. */
  52263. Condition.prototype._serialize = function (serializedCondition) {
  52264. return {
  52265. type: 2,
  52266. children: [],
  52267. name: serializedCondition.name,
  52268. properties: serializedCondition.properties
  52269. };
  52270. };
  52271. return Condition;
  52272. }());
  52273. BABYLON.Condition = Condition;
  52274. /**
  52275. * Defines specific conditional operators as extensions of Condition
  52276. */
  52277. var ValueCondition = /** @class */ (function (_super) {
  52278. __extends(ValueCondition, _super);
  52279. /**
  52280. * Creates a new ValueCondition
  52281. * @param actionManager manager for the action the condition applies to
  52282. * @param target for the action
  52283. * @param propertyPath path to specify the property of the target the conditional operator uses
  52284. * @param value the value compared by the conditional operator against the current value of the property
  52285. * @param operator the conditional operator, default ValueCondition.IsEqual
  52286. */
  52287. function ValueCondition(actionManager, target,
  52288. /** path to specify the property of the target the conditional operator uses */
  52289. propertyPath,
  52290. /** the value compared by the conditional operator against the current value of the property */
  52291. value,
  52292. /** the conditional operator, default ValueCondition.IsEqual */
  52293. operator) {
  52294. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52295. var _this = _super.call(this, actionManager) || this;
  52296. _this.propertyPath = propertyPath;
  52297. _this.value = value;
  52298. _this.operator = operator;
  52299. _this._target = target;
  52300. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52301. _this._property = _this._getProperty(_this.propertyPath);
  52302. return _this;
  52303. }
  52304. Object.defineProperty(ValueCondition, "IsEqual", {
  52305. /**
  52306. * returns the number for IsEqual
  52307. */
  52308. get: function () {
  52309. return ValueCondition._IsEqual;
  52310. },
  52311. enumerable: true,
  52312. configurable: true
  52313. });
  52314. Object.defineProperty(ValueCondition, "IsDifferent", {
  52315. /**
  52316. * Returns the number for IsDifferent
  52317. */
  52318. get: function () {
  52319. return ValueCondition._IsDifferent;
  52320. },
  52321. enumerable: true,
  52322. configurable: true
  52323. });
  52324. Object.defineProperty(ValueCondition, "IsGreater", {
  52325. /**
  52326. * Returns the number for IsGreater
  52327. */
  52328. get: function () {
  52329. return ValueCondition._IsGreater;
  52330. },
  52331. enumerable: true,
  52332. configurable: true
  52333. });
  52334. Object.defineProperty(ValueCondition, "IsLesser", {
  52335. /**
  52336. * Returns the number for IsLesser
  52337. */
  52338. get: function () {
  52339. return ValueCondition._IsLesser;
  52340. },
  52341. enumerable: true,
  52342. configurable: true
  52343. });
  52344. /**
  52345. * Compares the given value with the property value for the specified conditional operator
  52346. * @returns the result of the comparison
  52347. */
  52348. ValueCondition.prototype.isValid = function () {
  52349. switch (this.operator) {
  52350. case ValueCondition.IsGreater:
  52351. return this._effectiveTarget[this._property] > this.value;
  52352. case ValueCondition.IsLesser:
  52353. return this._effectiveTarget[this._property] < this.value;
  52354. case ValueCondition.IsEqual:
  52355. case ValueCondition.IsDifferent:
  52356. var check;
  52357. if (this.value.equals) {
  52358. check = this.value.equals(this._effectiveTarget[this._property]);
  52359. }
  52360. else {
  52361. check = this.value === this._effectiveTarget[this._property];
  52362. }
  52363. return this.operator === ValueCondition.IsEqual ? check : !check;
  52364. }
  52365. return false;
  52366. };
  52367. /**
  52368. * Serialize the ValueCondition into a JSON compatible object
  52369. * @returns serialization object
  52370. */
  52371. ValueCondition.prototype.serialize = function () {
  52372. return this._serialize({
  52373. name: "ValueCondition",
  52374. properties: [
  52375. BABYLON.Action._GetTargetProperty(this._target),
  52376. { name: "propertyPath", value: this.propertyPath },
  52377. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52378. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52379. ]
  52380. });
  52381. };
  52382. /**
  52383. * Gets the name of the conditional operator for the ValueCondition
  52384. * @param operator the conditional operator
  52385. * @returns the name
  52386. */
  52387. ValueCondition.GetOperatorName = function (operator) {
  52388. switch (operator) {
  52389. case ValueCondition._IsEqual: return "IsEqual";
  52390. case ValueCondition._IsDifferent: return "IsDifferent";
  52391. case ValueCondition._IsGreater: return "IsGreater";
  52392. case ValueCondition._IsLesser: return "IsLesser";
  52393. default: return "";
  52394. }
  52395. };
  52396. /**
  52397. * Internal only
  52398. * @ignore
  52399. */
  52400. ValueCondition._IsEqual = 0;
  52401. /**
  52402. * Internal only
  52403. * @ignore
  52404. */
  52405. ValueCondition._IsDifferent = 1;
  52406. /**
  52407. * Internal only
  52408. * @ignore
  52409. */
  52410. ValueCondition._IsGreater = 2;
  52411. /**
  52412. * Internal only
  52413. * @ignore
  52414. */
  52415. ValueCondition._IsLesser = 3;
  52416. return ValueCondition;
  52417. }(Condition));
  52418. BABYLON.ValueCondition = ValueCondition;
  52419. /**
  52420. * Defines a predicate condition as an extension of Condition
  52421. */
  52422. var PredicateCondition = /** @class */ (function (_super) {
  52423. __extends(PredicateCondition, _super);
  52424. /**
  52425. * Creates a new PredicateCondition
  52426. * @param actionManager manager for the action the condition applies to
  52427. * @param predicate defines the predicate function used to validate the condition
  52428. */
  52429. function PredicateCondition(actionManager,
  52430. /** defines the predicate function used to validate the condition */
  52431. predicate) {
  52432. var _this = _super.call(this, actionManager) || this;
  52433. _this.predicate = predicate;
  52434. return _this;
  52435. }
  52436. /**
  52437. * @returns the validity of the predicate condition
  52438. */
  52439. PredicateCondition.prototype.isValid = function () {
  52440. return this.predicate();
  52441. };
  52442. return PredicateCondition;
  52443. }(Condition));
  52444. BABYLON.PredicateCondition = PredicateCondition;
  52445. /**
  52446. * Defines a state condition as an extension of Condition
  52447. */
  52448. var StateCondition = /** @class */ (function (_super) {
  52449. __extends(StateCondition, _super);
  52450. /**
  52451. * Creates a new StateCondition
  52452. * @param actionManager manager for the action the condition applies to
  52453. * @param target of the condition
  52454. * @param value to compare with target state
  52455. */
  52456. function StateCondition(actionManager, target, value) {
  52457. var _this = _super.call(this, actionManager) || this;
  52458. _this.value = value;
  52459. _this._target = target;
  52460. return _this;
  52461. }
  52462. /**
  52463. * @returns the validity of the state
  52464. */
  52465. StateCondition.prototype.isValid = function () {
  52466. return this._target.state === this.value;
  52467. };
  52468. /**
  52469. * Serialize the StateCondition into a JSON compatible object
  52470. * @returns serialization object
  52471. */
  52472. StateCondition.prototype.serialize = function () {
  52473. return this._serialize({
  52474. name: "StateCondition",
  52475. properties: [
  52476. BABYLON.Action._GetTargetProperty(this._target),
  52477. { name: "value", value: this.value }
  52478. ]
  52479. });
  52480. };
  52481. return StateCondition;
  52482. }(Condition));
  52483. BABYLON.StateCondition = StateCondition;
  52484. })(BABYLON || (BABYLON = {}));
  52485. //# sourceMappingURL=babylon.condition.js.map
  52486. var BABYLON;
  52487. (function (BABYLON) {
  52488. /**
  52489. * The action to be carried out following a trigger
  52490. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52491. */
  52492. var Action = /** @class */ (function () {
  52493. /**
  52494. * Creates a new Action
  52495. * @param triggerOptions the trigger, with or without parameters, for the action
  52496. * @param condition an optional determinant of action
  52497. */
  52498. function Action(triggerOptions, condition) {
  52499. this.triggerOptions = triggerOptions;
  52500. /**
  52501. * An event triggered prior to action being executed.
  52502. */
  52503. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52504. if (triggerOptions.parameter) {
  52505. this.trigger = triggerOptions.trigger;
  52506. this._triggerParameter = triggerOptions.parameter;
  52507. }
  52508. else {
  52509. this.trigger = triggerOptions;
  52510. }
  52511. this._nextActiveAction = this;
  52512. this._condition = condition;
  52513. }
  52514. /**
  52515. * Internal only
  52516. * @ignore
  52517. */
  52518. Action.prototype._prepare = function () {
  52519. };
  52520. /**
  52521. * Gets the trigger parameters
  52522. * @returns the trigger parameters
  52523. */
  52524. Action.prototype.getTriggerParameter = function () {
  52525. return this._triggerParameter;
  52526. };
  52527. /**
  52528. * Internal only - executes current action event
  52529. * @ignore
  52530. */
  52531. Action.prototype._executeCurrent = function (evt) {
  52532. if (this._nextActiveAction._condition) {
  52533. var condition = this._nextActiveAction._condition;
  52534. var currentRenderId = this._actionManager.getScene().getRenderId();
  52535. // We cache the current evaluation for the current frame
  52536. if (condition._evaluationId === currentRenderId) {
  52537. if (!condition._currentResult) {
  52538. return;
  52539. }
  52540. }
  52541. else {
  52542. condition._evaluationId = currentRenderId;
  52543. if (!condition.isValid()) {
  52544. condition._currentResult = false;
  52545. return;
  52546. }
  52547. condition._currentResult = true;
  52548. }
  52549. }
  52550. this.onBeforeExecuteObservable.notifyObservers(this);
  52551. this._nextActiveAction.execute(evt);
  52552. this.skipToNextActiveAction();
  52553. };
  52554. /**
  52555. * Execute placeholder for child classes
  52556. * @param evt optional action event
  52557. */
  52558. Action.prototype.execute = function (evt) {
  52559. };
  52560. /**
  52561. * Skips to next active action
  52562. */
  52563. Action.prototype.skipToNextActiveAction = function () {
  52564. if (this._nextActiveAction._child) {
  52565. if (!this._nextActiveAction._child._actionManager) {
  52566. this._nextActiveAction._child._actionManager = this._actionManager;
  52567. }
  52568. this._nextActiveAction = this._nextActiveAction._child;
  52569. }
  52570. else {
  52571. this._nextActiveAction = this;
  52572. }
  52573. };
  52574. /**
  52575. * Adds action to chain of actions, may be a DoNothingAction
  52576. * @param index The index of the attribute.
  52577. * @returns The action passed in
  52578. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52579. */
  52580. Action.prototype.then = function (action) {
  52581. this._child = action;
  52582. action._actionManager = this._actionManager;
  52583. action._prepare();
  52584. return action;
  52585. };
  52586. /**
  52587. * Internal only
  52588. * @ignore
  52589. */
  52590. Action.prototype._getProperty = function (propertyPath) {
  52591. return this._actionManager._getProperty(propertyPath);
  52592. };
  52593. /**
  52594. * Internal only
  52595. * @ignore
  52596. */
  52597. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52598. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52599. };
  52600. /**
  52601. * Serialize placeholder for child classes
  52602. * @param parent of child
  52603. * @returns the serialized object
  52604. */
  52605. Action.prototype.serialize = function (parent) {
  52606. };
  52607. /**
  52608. * Internal only called by serialize
  52609. * @ignore
  52610. */
  52611. Action.prototype._serialize = function (serializedAction, parent) {
  52612. var serializationObject = {
  52613. type: 1,
  52614. children: [],
  52615. name: serializedAction.name,
  52616. properties: serializedAction.properties || []
  52617. };
  52618. // Serialize child
  52619. if (this._child) {
  52620. this._child.serialize(serializationObject);
  52621. }
  52622. // Check if "this" has a condition
  52623. if (this._condition) {
  52624. var serializedCondition = this._condition.serialize();
  52625. serializedCondition.children.push(serializationObject);
  52626. if (parent) {
  52627. parent.children.push(serializedCondition);
  52628. }
  52629. return serializedCondition;
  52630. }
  52631. if (parent) {
  52632. parent.children.push(serializationObject);
  52633. }
  52634. return serializationObject;
  52635. };
  52636. /**
  52637. * Internal only
  52638. * @ignore
  52639. */
  52640. Action._SerializeValueAsString = function (value) {
  52641. if (typeof value === "number") {
  52642. return value.toString();
  52643. }
  52644. if (typeof value === "boolean") {
  52645. return value ? "true" : "false";
  52646. }
  52647. if (value instanceof BABYLON.Vector2) {
  52648. return value.x + ", " + value.y;
  52649. }
  52650. if (value instanceof BABYLON.Vector3) {
  52651. return value.x + ", " + value.y + ", " + value.z;
  52652. }
  52653. if (value instanceof BABYLON.Color3) {
  52654. return value.r + ", " + value.g + ", " + value.b;
  52655. }
  52656. if (value instanceof BABYLON.Color4) {
  52657. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52658. }
  52659. return value; // string
  52660. };
  52661. /**
  52662. * Internal only
  52663. * @ignore
  52664. */
  52665. Action._GetTargetProperty = function (target) {
  52666. return {
  52667. name: "target",
  52668. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52669. : target instanceof BABYLON.Light ? "LightProperties"
  52670. : target instanceof BABYLON.Camera ? "CameraProperties"
  52671. : "SceneProperties",
  52672. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52673. };
  52674. };
  52675. return Action;
  52676. }());
  52677. BABYLON.Action = Action;
  52678. })(BABYLON || (BABYLON = {}));
  52679. //# sourceMappingURL=babylon.action.js.map
  52680. var BABYLON;
  52681. (function (BABYLON) {
  52682. /**
  52683. * ActionEvent is the event being sent when an action is triggered.
  52684. */
  52685. var ActionEvent = /** @class */ (function () {
  52686. /**
  52687. * @param source The mesh or sprite that triggered the action.
  52688. * @param pointerX The X mouse cursor position at the time of the event
  52689. * @param pointerY The Y mouse cursor position at the time of the event
  52690. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52691. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52692. */
  52693. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  52694. this.source = source;
  52695. this.pointerX = pointerX;
  52696. this.pointerY = pointerY;
  52697. this.meshUnderPointer = meshUnderPointer;
  52698. this.sourceEvent = sourceEvent;
  52699. this.additionalData = additionalData;
  52700. }
  52701. /**
  52702. * Helper function to auto-create an ActionEvent from a source mesh.
  52703. * @param source The source mesh that triggered the event
  52704. * @param evt {Event} The original (browser) event
  52705. */
  52706. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52707. var scene = source.getScene();
  52708. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52709. };
  52710. /**
  52711. * Helper function to auto-create an ActionEvent from a source mesh.
  52712. * @param source The source sprite that triggered the event
  52713. * @param scene Scene associated with the sprite
  52714. * @param evt {Event} The original (browser) event
  52715. */
  52716. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52717. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52718. };
  52719. /**
  52720. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52721. * @param scene the scene where the event occurred
  52722. * @param evt {Event} The original (browser) event
  52723. */
  52724. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52725. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52726. };
  52727. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52728. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52729. };
  52730. return ActionEvent;
  52731. }());
  52732. BABYLON.ActionEvent = ActionEvent;
  52733. /**
  52734. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52735. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52736. */
  52737. var ActionManager = /** @class */ (function () {
  52738. function ActionManager(scene) {
  52739. // Members
  52740. this.actions = new Array();
  52741. this.hoverCursor = '';
  52742. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52743. scene._actionManagers.push(this);
  52744. }
  52745. Object.defineProperty(ActionManager, "NothingTrigger", {
  52746. get: function () {
  52747. return ActionManager._NothingTrigger;
  52748. },
  52749. enumerable: true,
  52750. configurable: true
  52751. });
  52752. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52753. get: function () {
  52754. return ActionManager._OnPickTrigger;
  52755. },
  52756. enumerable: true,
  52757. configurable: true
  52758. });
  52759. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52760. get: function () {
  52761. return ActionManager._OnLeftPickTrigger;
  52762. },
  52763. enumerable: true,
  52764. configurable: true
  52765. });
  52766. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52767. get: function () {
  52768. return ActionManager._OnRightPickTrigger;
  52769. },
  52770. enumerable: true,
  52771. configurable: true
  52772. });
  52773. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52774. get: function () {
  52775. return ActionManager._OnCenterPickTrigger;
  52776. },
  52777. enumerable: true,
  52778. configurable: true
  52779. });
  52780. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52781. get: function () {
  52782. return ActionManager._OnPickDownTrigger;
  52783. },
  52784. enumerable: true,
  52785. configurable: true
  52786. });
  52787. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52788. get: function () {
  52789. return ActionManager._OnDoublePickTrigger;
  52790. },
  52791. enumerable: true,
  52792. configurable: true
  52793. });
  52794. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52795. get: function () {
  52796. return ActionManager._OnPickUpTrigger;
  52797. },
  52798. enumerable: true,
  52799. configurable: true
  52800. });
  52801. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52802. /// This trigger will only be raised if you also declared a OnPickDown
  52803. get: function () {
  52804. return ActionManager._OnPickOutTrigger;
  52805. },
  52806. enumerable: true,
  52807. configurable: true
  52808. });
  52809. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52810. get: function () {
  52811. return ActionManager._OnLongPressTrigger;
  52812. },
  52813. enumerable: true,
  52814. configurable: true
  52815. });
  52816. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52817. get: function () {
  52818. return ActionManager._OnPointerOverTrigger;
  52819. },
  52820. enumerable: true,
  52821. configurable: true
  52822. });
  52823. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52824. get: function () {
  52825. return ActionManager._OnPointerOutTrigger;
  52826. },
  52827. enumerable: true,
  52828. configurable: true
  52829. });
  52830. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52831. get: function () {
  52832. return ActionManager._OnEveryFrameTrigger;
  52833. },
  52834. enumerable: true,
  52835. configurable: true
  52836. });
  52837. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52838. get: function () {
  52839. return ActionManager._OnIntersectionEnterTrigger;
  52840. },
  52841. enumerable: true,
  52842. configurable: true
  52843. });
  52844. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52845. get: function () {
  52846. return ActionManager._OnIntersectionExitTrigger;
  52847. },
  52848. enumerable: true,
  52849. configurable: true
  52850. });
  52851. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52852. get: function () {
  52853. return ActionManager._OnKeyDownTrigger;
  52854. },
  52855. enumerable: true,
  52856. configurable: true
  52857. });
  52858. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52859. get: function () {
  52860. return ActionManager._OnKeyUpTrigger;
  52861. },
  52862. enumerable: true,
  52863. configurable: true
  52864. });
  52865. // Methods
  52866. ActionManager.prototype.dispose = function () {
  52867. var index = this._scene._actionManagers.indexOf(this);
  52868. for (var i = 0; i < this.actions.length; i++) {
  52869. var action = this.actions[i];
  52870. ActionManager.Triggers[action.trigger]--;
  52871. if (ActionManager.Triggers[action.trigger] === 0) {
  52872. delete ActionManager.Triggers[action.trigger];
  52873. }
  52874. }
  52875. if (index > -1) {
  52876. this._scene._actionManagers.splice(index, 1);
  52877. }
  52878. };
  52879. ActionManager.prototype.getScene = function () {
  52880. return this._scene;
  52881. };
  52882. /**
  52883. * Does this action manager handles actions of any of the given triggers
  52884. * @param {number[]} triggers - the triggers to be tested
  52885. * @return {boolean} whether one (or more) of the triggers is handeled
  52886. */
  52887. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52888. for (var index = 0; index < this.actions.length; index++) {
  52889. var action = this.actions[index];
  52890. if (triggers.indexOf(action.trigger) > -1) {
  52891. return true;
  52892. }
  52893. }
  52894. return false;
  52895. };
  52896. /**
  52897. * Does this action manager handles actions of a given trigger
  52898. * @param trigger defines the trigger to be tested
  52899. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52900. * @return whether the trigger is handled
  52901. */
  52902. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52903. for (var index = 0; index < this.actions.length; index++) {
  52904. var action = this.actions[index];
  52905. if (action.trigger === trigger) {
  52906. if (parameterPredicate) {
  52907. if (parameterPredicate(action.getTriggerParameter())) {
  52908. return true;
  52909. }
  52910. }
  52911. else {
  52912. return true;
  52913. }
  52914. }
  52915. }
  52916. return false;
  52917. };
  52918. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52919. /**
  52920. * Does this action manager has pointer triggers
  52921. * @return {boolean} whether or not it has pointer triggers
  52922. */
  52923. get: function () {
  52924. for (var index = 0; index < this.actions.length; index++) {
  52925. var action = this.actions[index];
  52926. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52927. return true;
  52928. }
  52929. }
  52930. return false;
  52931. },
  52932. enumerable: true,
  52933. configurable: true
  52934. });
  52935. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52936. /**
  52937. * Does this action manager has pick triggers
  52938. * @return {boolean} whether or not it has pick triggers
  52939. */
  52940. get: function () {
  52941. for (var index = 0; index < this.actions.length; index++) {
  52942. var action = this.actions[index];
  52943. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52944. return true;
  52945. }
  52946. }
  52947. return false;
  52948. },
  52949. enumerable: true,
  52950. configurable: true
  52951. });
  52952. Object.defineProperty(ActionManager, "HasTriggers", {
  52953. /**
  52954. * Does exist one action manager with at least one trigger
  52955. * @return {boolean} whether or not it exists one action manager with one trigger
  52956. **/
  52957. get: function () {
  52958. for (var t in ActionManager.Triggers) {
  52959. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52960. return true;
  52961. }
  52962. }
  52963. return false;
  52964. },
  52965. enumerable: true,
  52966. configurable: true
  52967. });
  52968. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52969. /**
  52970. * Does exist one action manager with at least one pick trigger
  52971. * @return {boolean} whether or not it exists one action manager with one pick trigger
  52972. **/
  52973. get: function () {
  52974. for (var t in ActionManager.Triggers) {
  52975. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52976. var t_int = parseInt(t);
  52977. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52978. return true;
  52979. }
  52980. }
  52981. }
  52982. return false;
  52983. },
  52984. enumerable: true,
  52985. configurable: true
  52986. });
  52987. /**
  52988. * Does exist one action manager that handles actions of a given trigger
  52989. * @param {number} trigger - the trigger to be tested
  52990. * @return {boolean} whether the trigger is handeled by at least one action manager
  52991. **/
  52992. ActionManager.HasSpecificTrigger = function (trigger) {
  52993. for (var t in ActionManager.Triggers) {
  52994. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52995. var t_int = parseInt(t);
  52996. if (t_int === trigger) {
  52997. return true;
  52998. }
  52999. }
  53000. }
  53001. return false;
  53002. };
  53003. /**
  53004. * Registers an action to this action manager
  53005. * @param {BABYLON.Action} action - the action to be registered
  53006. * @return {BABYLON.Action} the action amended (prepared) after registration
  53007. */
  53008. ActionManager.prototype.registerAction = function (action) {
  53009. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53010. if (this.getScene().actionManager !== this) {
  53011. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53012. return null;
  53013. }
  53014. }
  53015. this.actions.push(action);
  53016. if (ActionManager.Triggers[action.trigger]) {
  53017. ActionManager.Triggers[action.trigger]++;
  53018. }
  53019. else {
  53020. ActionManager.Triggers[action.trigger] = 1;
  53021. }
  53022. action._actionManager = this;
  53023. action._prepare();
  53024. return action;
  53025. };
  53026. /**
  53027. * Unregisters an action to this action manager
  53028. * @param action The action to be unregistered
  53029. * @return whether the action has been unregistered
  53030. */
  53031. ActionManager.prototype.unregisterAction = function (action) {
  53032. var index = this.actions.indexOf(action);
  53033. if (index !== -1) {
  53034. this.actions.splice(index, 1);
  53035. ActionManager.Triggers[action.trigger] -= 1;
  53036. if (ActionManager.Triggers[action.trigger] === 0) {
  53037. delete ActionManager.Triggers[action.trigger];
  53038. }
  53039. delete action._actionManager;
  53040. return true;
  53041. }
  53042. return false;
  53043. };
  53044. /**
  53045. * Process a specific trigger
  53046. * @param {number} trigger - the trigger to process
  53047. * @param evt {BABYLON.ActionEvent} the event details to be processed
  53048. */
  53049. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53050. for (var index = 0; index < this.actions.length; index++) {
  53051. var action = this.actions[index];
  53052. if (action.trigger === trigger) {
  53053. if (evt) {
  53054. if (trigger === ActionManager.OnKeyUpTrigger
  53055. || trigger === ActionManager.OnKeyDownTrigger) {
  53056. var parameter = action.getTriggerParameter();
  53057. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53058. if (!parameter.toLowerCase) {
  53059. continue;
  53060. }
  53061. var lowerCase = parameter.toLowerCase();
  53062. if (lowerCase !== evt.sourceEvent.key) {
  53063. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53064. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53065. if (actualkey !== lowerCase) {
  53066. continue;
  53067. }
  53068. }
  53069. }
  53070. }
  53071. }
  53072. action._executeCurrent(evt);
  53073. }
  53074. }
  53075. };
  53076. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53077. var properties = propertyPath.split(".");
  53078. for (var index = 0; index < properties.length - 1; index++) {
  53079. target = target[properties[index]];
  53080. }
  53081. return target;
  53082. };
  53083. ActionManager.prototype._getProperty = function (propertyPath) {
  53084. var properties = propertyPath.split(".");
  53085. return properties[properties.length - 1];
  53086. };
  53087. ActionManager.prototype.serialize = function (name) {
  53088. var root = {
  53089. children: new Array(),
  53090. name: name,
  53091. type: 3,
  53092. properties: new Array() // Empty for root but required
  53093. };
  53094. for (var i = 0; i < this.actions.length; i++) {
  53095. var triggerObject = {
  53096. type: 0,
  53097. children: new Array(),
  53098. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53099. properties: new Array()
  53100. };
  53101. var triggerOptions = this.actions[i].triggerOptions;
  53102. if (triggerOptions && typeof triggerOptions !== "number") {
  53103. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53104. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53105. }
  53106. else {
  53107. var parameter = {};
  53108. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53109. if (triggerOptions.parameter.mesh) {
  53110. parameter._meshId = triggerOptions.parameter.mesh.id;
  53111. }
  53112. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53113. }
  53114. }
  53115. // Serialize child action, recursively
  53116. this.actions[i].serialize(triggerObject);
  53117. // Add serialized trigger
  53118. root.children.push(triggerObject);
  53119. }
  53120. return root;
  53121. };
  53122. ActionManager.Parse = function (parsedActions, object, scene) {
  53123. var actionManager = new ActionManager(scene);
  53124. if (object === null)
  53125. scene.actionManager = actionManager;
  53126. else
  53127. object.actionManager = actionManager;
  53128. // instanciate a new object
  53129. var instanciate = function (name, params) {
  53130. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53131. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53132. newInstance.constructor.apply(newInstance, params);
  53133. return newInstance;
  53134. };
  53135. var parseParameter = function (name, value, target, propertyPath) {
  53136. if (propertyPath === null) {
  53137. // String, boolean or float
  53138. var floatValue = parseFloat(value);
  53139. if (value === "true" || value === "false")
  53140. return value === "true";
  53141. else
  53142. return isNaN(floatValue) ? value : floatValue;
  53143. }
  53144. var effectiveTarget = propertyPath.split(".");
  53145. var values = value.split(",");
  53146. // Get effective Target
  53147. for (var i = 0; i < effectiveTarget.length; i++) {
  53148. target = target[effectiveTarget[i]];
  53149. }
  53150. // Return appropriate value with its type
  53151. if (typeof (target) === "boolean")
  53152. return values[0] === "true";
  53153. if (typeof (target) === "string")
  53154. return values[0];
  53155. // Parameters with multiple values such as Vector3 etc.
  53156. var split = new Array();
  53157. for (var i = 0; i < values.length; i++)
  53158. split.push(parseFloat(values[i]));
  53159. if (target instanceof BABYLON.Vector3)
  53160. return BABYLON.Vector3.FromArray(split);
  53161. if (target instanceof BABYLON.Vector4)
  53162. return BABYLON.Vector4.FromArray(split);
  53163. if (target instanceof BABYLON.Color3)
  53164. return BABYLON.Color3.FromArray(split);
  53165. if (target instanceof BABYLON.Color4)
  53166. return BABYLON.Color4.FromArray(split);
  53167. return parseFloat(values[0]);
  53168. };
  53169. // traverse graph per trigger
  53170. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53171. if (combineArray === void 0) { combineArray = null; }
  53172. if (parsedAction.detached)
  53173. return;
  53174. var parameters = new Array();
  53175. var target = null;
  53176. var propertyPath = null;
  53177. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53178. // Parameters
  53179. if (parsedAction.type === 2)
  53180. parameters.push(actionManager);
  53181. else
  53182. parameters.push(trigger);
  53183. if (combine) {
  53184. var actions = new Array();
  53185. for (var j = 0; j < parsedAction.combine.length; j++) {
  53186. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53187. }
  53188. parameters.push(actions);
  53189. }
  53190. else {
  53191. for (var i = 0; i < parsedAction.properties.length; i++) {
  53192. var value = parsedAction.properties[i].value;
  53193. var name = parsedAction.properties[i].name;
  53194. var targetType = parsedAction.properties[i].targetType;
  53195. if (name === "target")
  53196. if (targetType !== null && targetType === "SceneProperties")
  53197. value = target = scene;
  53198. else
  53199. value = target = scene.getNodeByName(value);
  53200. else if (name === "parent")
  53201. value = scene.getNodeByName(value);
  53202. else if (name === "sound")
  53203. value = scene.getSoundByName(value);
  53204. else if (name !== "propertyPath") {
  53205. if (parsedAction.type === 2 && name === "operator")
  53206. value = BABYLON.ValueCondition[value];
  53207. else
  53208. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53209. }
  53210. else {
  53211. propertyPath = value;
  53212. }
  53213. parameters.push(value);
  53214. }
  53215. }
  53216. if (combineArray === null) {
  53217. parameters.push(condition);
  53218. }
  53219. else {
  53220. parameters.push(null);
  53221. }
  53222. // If interpolate value action
  53223. if (parsedAction.name === "InterpolateValueAction") {
  53224. var param = parameters[parameters.length - 2];
  53225. parameters[parameters.length - 1] = param;
  53226. parameters[parameters.length - 2] = condition;
  53227. }
  53228. // Action or condition(s) and not CombineAction
  53229. var newAction = instanciate(parsedAction.name, parameters);
  53230. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53231. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53232. if (action)
  53233. action.then(nothing);
  53234. else
  53235. actionManager.registerAction(nothing);
  53236. action = nothing;
  53237. }
  53238. if (combineArray === null) {
  53239. if (newAction instanceof BABYLON.Condition) {
  53240. condition = newAction;
  53241. newAction = action;
  53242. }
  53243. else {
  53244. condition = null;
  53245. if (action)
  53246. action.then(newAction);
  53247. else
  53248. actionManager.registerAction(newAction);
  53249. }
  53250. }
  53251. else {
  53252. combineArray.push(newAction);
  53253. }
  53254. for (var i = 0; i < parsedAction.children.length; i++)
  53255. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53256. };
  53257. // triggers
  53258. for (var i = 0; i < parsedActions.children.length; i++) {
  53259. var triggerParams;
  53260. var trigger = parsedActions.children[i];
  53261. if (trigger.properties.length > 0) {
  53262. var param = trigger.properties[0].value;
  53263. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53264. if (value._meshId) {
  53265. value.mesh = scene.getMeshByID(value._meshId);
  53266. }
  53267. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53268. }
  53269. else
  53270. triggerParams = ActionManager[trigger.name];
  53271. for (var j = 0; j < trigger.children.length; j++) {
  53272. if (!trigger.detached)
  53273. traverse(trigger.children[j], triggerParams, null, null);
  53274. }
  53275. }
  53276. };
  53277. ActionManager.GetTriggerName = function (trigger) {
  53278. switch (trigger) {
  53279. case 0: return "NothingTrigger";
  53280. case 1: return "OnPickTrigger";
  53281. case 2: return "OnLeftPickTrigger";
  53282. case 3: return "OnRightPickTrigger";
  53283. case 4: return "OnCenterPickTrigger";
  53284. case 5: return "OnPickDownTrigger";
  53285. case 6: return "OnPickUpTrigger";
  53286. case 7: return "OnLongPressTrigger";
  53287. case 8: return "OnPointerOverTrigger";
  53288. case 9: return "OnPointerOutTrigger";
  53289. case 10: return "OnEveryFrameTrigger";
  53290. case 11: return "OnIntersectionEnterTrigger";
  53291. case 12: return "OnIntersectionExitTrigger";
  53292. case 13: return "OnKeyDownTrigger";
  53293. case 14: return "OnKeyUpTrigger";
  53294. case 15: return "OnPickOutTrigger";
  53295. default: return "";
  53296. }
  53297. };
  53298. // Statics
  53299. ActionManager._NothingTrigger = 0;
  53300. ActionManager._OnPickTrigger = 1;
  53301. ActionManager._OnLeftPickTrigger = 2;
  53302. ActionManager._OnRightPickTrigger = 3;
  53303. ActionManager._OnCenterPickTrigger = 4;
  53304. ActionManager._OnPickDownTrigger = 5;
  53305. ActionManager._OnDoublePickTrigger = 6;
  53306. ActionManager._OnPickUpTrigger = 7;
  53307. ActionManager._OnLongPressTrigger = 8;
  53308. ActionManager._OnPointerOverTrigger = 9;
  53309. ActionManager._OnPointerOutTrigger = 10;
  53310. ActionManager._OnEveryFrameTrigger = 11;
  53311. ActionManager._OnIntersectionEnterTrigger = 12;
  53312. ActionManager._OnIntersectionExitTrigger = 13;
  53313. ActionManager._OnKeyDownTrigger = 14;
  53314. ActionManager._OnKeyUpTrigger = 15;
  53315. ActionManager._OnPickOutTrigger = 16;
  53316. ActionManager.Triggers = {};
  53317. return ActionManager;
  53318. }());
  53319. BABYLON.ActionManager = ActionManager;
  53320. })(BABYLON || (BABYLON = {}));
  53321. //# sourceMappingURL=babylon.actionManager.js.map
  53322. var BABYLON;
  53323. (function (BABYLON) {
  53324. var InterpolateValueAction = /** @class */ (function (_super) {
  53325. __extends(InterpolateValueAction, _super);
  53326. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53327. if (duration === void 0) { duration = 1000; }
  53328. var _this = _super.call(this, triggerOptions, condition) || this;
  53329. _this.propertyPath = propertyPath;
  53330. _this.value = value;
  53331. _this.duration = duration;
  53332. _this.stopOtherAnimations = stopOtherAnimations;
  53333. _this.onInterpolationDone = onInterpolationDone;
  53334. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53335. _this._target = _this._effectiveTarget = target;
  53336. return _this;
  53337. }
  53338. InterpolateValueAction.prototype._prepare = function () {
  53339. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53340. this._property = this._getProperty(this.propertyPath);
  53341. };
  53342. InterpolateValueAction.prototype.execute = function () {
  53343. var _this = this;
  53344. var scene = this._actionManager.getScene();
  53345. var keys = [
  53346. {
  53347. frame: 0,
  53348. value: this._effectiveTarget[this._property]
  53349. }, {
  53350. frame: 100,
  53351. value: this.value
  53352. }
  53353. ];
  53354. var dataType;
  53355. if (typeof this.value === "number") {
  53356. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53357. }
  53358. else if (this.value instanceof BABYLON.Color3) {
  53359. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53360. }
  53361. else if (this.value instanceof BABYLON.Vector3) {
  53362. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53363. }
  53364. else if (this.value instanceof BABYLON.Matrix) {
  53365. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53366. }
  53367. else if (this.value instanceof BABYLON.Quaternion) {
  53368. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53369. }
  53370. else {
  53371. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53372. return;
  53373. }
  53374. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53375. animation.setKeys(keys);
  53376. if (this.stopOtherAnimations) {
  53377. scene.stopAnimation(this._effectiveTarget);
  53378. }
  53379. var wrapper = function () {
  53380. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53381. if (_this.onInterpolationDone) {
  53382. _this.onInterpolationDone();
  53383. }
  53384. };
  53385. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53386. };
  53387. InterpolateValueAction.prototype.serialize = function (parent) {
  53388. return _super.prototype._serialize.call(this, {
  53389. name: "InterpolateValueAction",
  53390. properties: [
  53391. BABYLON.Action._GetTargetProperty(this._target),
  53392. { name: "propertyPath", value: this.propertyPath },
  53393. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53394. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53395. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53396. ]
  53397. }, parent);
  53398. };
  53399. return InterpolateValueAction;
  53400. }(BABYLON.Action));
  53401. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53402. })(BABYLON || (BABYLON = {}));
  53403. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53404. var BABYLON;
  53405. (function (BABYLON) {
  53406. var SwitchBooleanAction = /** @class */ (function (_super) {
  53407. __extends(SwitchBooleanAction, _super);
  53408. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53409. var _this = _super.call(this, triggerOptions, condition) || this;
  53410. _this.propertyPath = propertyPath;
  53411. _this._target = _this._effectiveTarget = target;
  53412. return _this;
  53413. }
  53414. SwitchBooleanAction.prototype._prepare = function () {
  53415. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53416. this._property = this._getProperty(this.propertyPath);
  53417. };
  53418. SwitchBooleanAction.prototype.execute = function () {
  53419. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53420. };
  53421. SwitchBooleanAction.prototype.serialize = function (parent) {
  53422. return _super.prototype._serialize.call(this, {
  53423. name: "SwitchBooleanAction",
  53424. properties: [
  53425. BABYLON.Action._GetTargetProperty(this._target),
  53426. { name: "propertyPath", value: this.propertyPath }
  53427. ]
  53428. }, parent);
  53429. };
  53430. return SwitchBooleanAction;
  53431. }(BABYLON.Action));
  53432. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53433. var SetStateAction = /** @class */ (function (_super) {
  53434. __extends(SetStateAction, _super);
  53435. function SetStateAction(triggerOptions, target, value, condition) {
  53436. var _this = _super.call(this, triggerOptions, condition) || this;
  53437. _this.value = value;
  53438. _this._target = target;
  53439. return _this;
  53440. }
  53441. SetStateAction.prototype.execute = function () {
  53442. this._target.state = this.value;
  53443. };
  53444. SetStateAction.prototype.serialize = function (parent) {
  53445. return _super.prototype._serialize.call(this, {
  53446. name: "SetStateAction",
  53447. properties: [
  53448. BABYLON.Action._GetTargetProperty(this._target),
  53449. { name: "value", value: this.value }
  53450. ]
  53451. }, parent);
  53452. };
  53453. return SetStateAction;
  53454. }(BABYLON.Action));
  53455. BABYLON.SetStateAction = SetStateAction;
  53456. var SetValueAction = /** @class */ (function (_super) {
  53457. __extends(SetValueAction, _super);
  53458. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53459. var _this = _super.call(this, triggerOptions, condition) || this;
  53460. _this.propertyPath = propertyPath;
  53461. _this.value = value;
  53462. _this._target = _this._effectiveTarget = target;
  53463. return _this;
  53464. }
  53465. SetValueAction.prototype._prepare = function () {
  53466. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53467. this._property = this._getProperty(this.propertyPath);
  53468. };
  53469. SetValueAction.prototype.execute = function () {
  53470. this._effectiveTarget[this._property] = this.value;
  53471. if (this._target.markAsDirty) {
  53472. this._target.markAsDirty(this._property);
  53473. }
  53474. };
  53475. SetValueAction.prototype.serialize = function (parent) {
  53476. return _super.prototype._serialize.call(this, {
  53477. name: "SetValueAction",
  53478. properties: [
  53479. BABYLON.Action._GetTargetProperty(this._target),
  53480. { name: "propertyPath", value: this.propertyPath },
  53481. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53482. ]
  53483. }, parent);
  53484. };
  53485. return SetValueAction;
  53486. }(BABYLON.Action));
  53487. BABYLON.SetValueAction = SetValueAction;
  53488. var IncrementValueAction = /** @class */ (function (_super) {
  53489. __extends(IncrementValueAction, _super);
  53490. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53491. var _this = _super.call(this, triggerOptions, condition) || this;
  53492. _this.propertyPath = propertyPath;
  53493. _this.value = value;
  53494. _this._target = _this._effectiveTarget = target;
  53495. return _this;
  53496. }
  53497. IncrementValueAction.prototype._prepare = function () {
  53498. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53499. this._property = this._getProperty(this.propertyPath);
  53500. if (typeof this._effectiveTarget[this._property] !== "number") {
  53501. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53502. }
  53503. };
  53504. IncrementValueAction.prototype.execute = function () {
  53505. this._effectiveTarget[this._property] += this.value;
  53506. if (this._target.markAsDirty) {
  53507. this._target.markAsDirty(this._property);
  53508. }
  53509. };
  53510. IncrementValueAction.prototype.serialize = function (parent) {
  53511. return _super.prototype._serialize.call(this, {
  53512. name: "IncrementValueAction",
  53513. properties: [
  53514. BABYLON.Action._GetTargetProperty(this._target),
  53515. { name: "propertyPath", value: this.propertyPath },
  53516. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53517. ]
  53518. }, parent);
  53519. };
  53520. return IncrementValueAction;
  53521. }(BABYLON.Action));
  53522. BABYLON.IncrementValueAction = IncrementValueAction;
  53523. var PlayAnimationAction = /** @class */ (function (_super) {
  53524. __extends(PlayAnimationAction, _super);
  53525. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53526. var _this = _super.call(this, triggerOptions, condition) || this;
  53527. _this.from = from;
  53528. _this.to = to;
  53529. _this.loop = loop;
  53530. _this._target = target;
  53531. return _this;
  53532. }
  53533. PlayAnimationAction.prototype._prepare = function () {
  53534. };
  53535. PlayAnimationAction.prototype.execute = function () {
  53536. var scene = this._actionManager.getScene();
  53537. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53538. };
  53539. PlayAnimationAction.prototype.serialize = function (parent) {
  53540. return _super.prototype._serialize.call(this, {
  53541. name: "PlayAnimationAction",
  53542. properties: [
  53543. BABYLON.Action._GetTargetProperty(this._target),
  53544. { name: "from", value: String(this.from) },
  53545. { name: "to", value: String(this.to) },
  53546. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53547. ]
  53548. }, parent);
  53549. };
  53550. return PlayAnimationAction;
  53551. }(BABYLON.Action));
  53552. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53553. var StopAnimationAction = /** @class */ (function (_super) {
  53554. __extends(StopAnimationAction, _super);
  53555. function StopAnimationAction(triggerOptions, target, condition) {
  53556. var _this = _super.call(this, triggerOptions, condition) || this;
  53557. _this._target = target;
  53558. return _this;
  53559. }
  53560. StopAnimationAction.prototype._prepare = function () {
  53561. };
  53562. StopAnimationAction.prototype.execute = function () {
  53563. var scene = this._actionManager.getScene();
  53564. scene.stopAnimation(this._target);
  53565. };
  53566. StopAnimationAction.prototype.serialize = function (parent) {
  53567. return _super.prototype._serialize.call(this, {
  53568. name: "StopAnimationAction",
  53569. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53570. }, parent);
  53571. };
  53572. return StopAnimationAction;
  53573. }(BABYLON.Action));
  53574. BABYLON.StopAnimationAction = StopAnimationAction;
  53575. var DoNothingAction = /** @class */ (function (_super) {
  53576. __extends(DoNothingAction, _super);
  53577. function DoNothingAction(triggerOptions, condition) {
  53578. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53579. return _super.call(this, triggerOptions, condition) || this;
  53580. }
  53581. DoNothingAction.prototype.execute = function () {
  53582. };
  53583. DoNothingAction.prototype.serialize = function (parent) {
  53584. return _super.prototype._serialize.call(this, {
  53585. name: "DoNothingAction",
  53586. properties: []
  53587. }, parent);
  53588. };
  53589. return DoNothingAction;
  53590. }(BABYLON.Action));
  53591. BABYLON.DoNothingAction = DoNothingAction;
  53592. var CombineAction = /** @class */ (function (_super) {
  53593. __extends(CombineAction, _super);
  53594. function CombineAction(triggerOptions, children, condition) {
  53595. var _this = _super.call(this, triggerOptions, condition) || this;
  53596. _this.children = children;
  53597. return _this;
  53598. }
  53599. CombineAction.prototype._prepare = function () {
  53600. for (var index = 0; index < this.children.length; index++) {
  53601. this.children[index]._actionManager = this._actionManager;
  53602. this.children[index]._prepare();
  53603. }
  53604. };
  53605. CombineAction.prototype.execute = function (evt) {
  53606. for (var index = 0; index < this.children.length; index++) {
  53607. this.children[index].execute(evt);
  53608. }
  53609. };
  53610. CombineAction.prototype.serialize = function (parent) {
  53611. var serializationObject = _super.prototype._serialize.call(this, {
  53612. name: "CombineAction",
  53613. properties: [],
  53614. combine: []
  53615. }, parent);
  53616. for (var i = 0; i < this.children.length; i++) {
  53617. serializationObject.combine.push(this.children[i].serialize(null));
  53618. }
  53619. return serializationObject;
  53620. };
  53621. return CombineAction;
  53622. }(BABYLON.Action));
  53623. BABYLON.CombineAction = CombineAction;
  53624. var ExecuteCodeAction = /** @class */ (function (_super) {
  53625. __extends(ExecuteCodeAction, _super);
  53626. function ExecuteCodeAction(triggerOptions, func, condition) {
  53627. var _this = _super.call(this, triggerOptions, condition) || this;
  53628. _this.func = func;
  53629. return _this;
  53630. }
  53631. ExecuteCodeAction.prototype.execute = function (evt) {
  53632. this.func(evt);
  53633. };
  53634. return ExecuteCodeAction;
  53635. }(BABYLON.Action));
  53636. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53637. var SetParentAction = /** @class */ (function (_super) {
  53638. __extends(SetParentAction, _super);
  53639. function SetParentAction(triggerOptions, target, parent, condition) {
  53640. var _this = _super.call(this, triggerOptions, condition) || this;
  53641. _this._target = target;
  53642. _this._parent = parent;
  53643. return _this;
  53644. }
  53645. SetParentAction.prototype._prepare = function () {
  53646. };
  53647. SetParentAction.prototype.execute = function () {
  53648. if (this._target.parent === this._parent) {
  53649. return;
  53650. }
  53651. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53652. invertParentWorldMatrix.invert();
  53653. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53654. this._target.parent = this._parent;
  53655. };
  53656. SetParentAction.prototype.serialize = function (parent) {
  53657. return _super.prototype._serialize.call(this, {
  53658. name: "SetParentAction",
  53659. properties: [
  53660. BABYLON.Action._GetTargetProperty(this._target),
  53661. BABYLON.Action._GetTargetProperty(this._parent),
  53662. ]
  53663. }, parent);
  53664. };
  53665. return SetParentAction;
  53666. }(BABYLON.Action));
  53667. BABYLON.SetParentAction = SetParentAction;
  53668. var PlaySoundAction = /** @class */ (function (_super) {
  53669. __extends(PlaySoundAction, _super);
  53670. function PlaySoundAction(triggerOptions, sound, condition) {
  53671. var _this = _super.call(this, triggerOptions, condition) || this;
  53672. _this._sound = sound;
  53673. return _this;
  53674. }
  53675. PlaySoundAction.prototype._prepare = function () {
  53676. };
  53677. PlaySoundAction.prototype.execute = function () {
  53678. if (this._sound !== undefined)
  53679. this._sound.play();
  53680. };
  53681. PlaySoundAction.prototype.serialize = function (parent) {
  53682. return _super.prototype._serialize.call(this, {
  53683. name: "PlaySoundAction",
  53684. properties: [{ name: "sound", value: this._sound.name }]
  53685. }, parent);
  53686. };
  53687. return PlaySoundAction;
  53688. }(BABYLON.Action));
  53689. BABYLON.PlaySoundAction = PlaySoundAction;
  53690. var StopSoundAction = /** @class */ (function (_super) {
  53691. __extends(StopSoundAction, _super);
  53692. function StopSoundAction(triggerOptions, sound, condition) {
  53693. var _this = _super.call(this, triggerOptions, condition) || this;
  53694. _this._sound = sound;
  53695. return _this;
  53696. }
  53697. StopSoundAction.prototype._prepare = function () {
  53698. };
  53699. StopSoundAction.prototype.execute = function () {
  53700. if (this._sound !== undefined)
  53701. this._sound.stop();
  53702. };
  53703. StopSoundAction.prototype.serialize = function (parent) {
  53704. return _super.prototype._serialize.call(this, {
  53705. name: "StopSoundAction",
  53706. properties: [{ name: "sound", value: this._sound.name }]
  53707. }, parent);
  53708. };
  53709. return StopSoundAction;
  53710. }(BABYLON.Action));
  53711. BABYLON.StopSoundAction = StopSoundAction;
  53712. })(BABYLON || (BABYLON = {}));
  53713. //# sourceMappingURL=babylon.directActions.js.map
  53714. var BABYLON;
  53715. (function (BABYLON) {
  53716. var SpriteManager = /** @class */ (function () {
  53717. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53718. if (epsilon === void 0) { epsilon = 0.01; }
  53719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53720. this.name = name;
  53721. this.sprites = new Array();
  53722. this.renderingGroupId = 0;
  53723. this.layerMask = 0x0FFFFFFF;
  53724. this.fogEnabled = true;
  53725. this.isPickable = false;
  53726. /**
  53727. * An event triggered when the manager is disposed.
  53728. */
  53729. this.onDisposeObservable = new BABYLON.Observable();
  53730. this._vertexBuffers = {};
  53731. this._capacity = capacity;
  53732. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53733. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53734. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53735. if (cellSize.width && cellSize.height) {
  53736. this.cellWidth = cellSize.width;
  53737. this.cellHeight = cellSize.height;
  53738. }
  53739. else if (cellSize !== undefined) {
  53740. this.cellWidth = cellSize;
  53741. this.cellHeight = cellSize;
  53742. }
  53743. else {
  53744. return;
  53745. }
  53746. this._epsilon = epsilon;
  53747. this._scene = scene;
  53748. this._scene.spriteManagers.push(this);
  53749. var indices = [];
  53750. var index = 0;
  53751. for (var count = 0; count < capacity; count++) {
  53752. indices.push(index);
  53753. indices.push(index + 1);
  53754. indices.push(index + 2);
  53755. indices.push(index);
  53756. indices.push(index + 2);
  53757. indices.push(index + 3);
  53758. index += 4;
  53759. }
  53760. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53761. // VBO
  53762. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53763. this._vertexData = new Float32Array(capacity * 16 * 4);
  53764. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53765. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53766. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53767. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53768. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53769. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53770. this._vertexBuffers["options"] = options;
  53771. this._vertexBuffers["cellInfo"] = cellInfo;
  53772. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53773. // Effects
  53774. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53775. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53776. }
  53777. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53778. set: function (callback) {
  53779. if (this._onDisposeObserver) {
  53780. this.onDisposeObservable.remove(this._onDisposeObserver);
  53781. }
  53782. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53783. },
  53784. enumerable: true,
  53785. configurable: true
  53786. });
  53787. Object.defineProperty(SpriteManager.prototype, "texture", {
  53788. get: function () {
  53789. return this._spriteTexture;
  53790. },
  53791. set: function (value) {
  53792. this._spriteTexture = value;
  53793. },
  53794. enumerable: true,
  53795. configurable: true
  53796. });
  53797. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53798. var arrayOffset = index * 16;
  53799. if (offsetX === 0)
  53800. offsetX = this._epsilon;
  53801. else if (offsetX === 1)
  53802. offsetX = 1 - this._epsilon;
  53803. if (offsetY === 0)
  53804. offsetY = this._epsilon;
  53805. else if (offsetY === 1)
  53806. offsetY = 1 - this._epsilon;
  53807. this._vertexData[arrayOffset] = sprite.position.x;
  53808. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53809. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53810. this._vertexData[arrayOffset + 3] = sprite.angle;
  53811. this._vertexData[arrayOffset + 4] = sprite.width;
  53812. this._vertexData[arrayOffset + 5] = sprite.height;
  53813. this._vertexData[arrayOffset + 6] = offsetX;
  53814. this._vertexData[arrayOffset + 7] = offsetY;
  53815. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53816. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53817. var offset = (sprite.cellIndex / rowSize) >> 0;
  53818. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53819. this._vertexData[arrayOffset + 11] = offset;
  53820. // Color
  53821. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53822. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53823. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53824. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53825. };
  53826. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53827. var count = Math.min(this._capacity, this.sprites.length);
  53828. var min = BABYLON.Vector3.Zero();
  53829. var max = BABYLON.Vector3.Zero();
  53830. var distance = Number.MAX_VALUE;
  53831. var currentSprite = null;
  53832. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53833. var cameraView = camera.getViewMatrix();
  53834. for (var index = 0; index < count; index++) {
  53835. var sprite = this.sprites[index];
  53836. if (!sprite) {
  53837. continue;
  53838. }
  53839. if (predicate) {
  53840. if (!predicate(sprite)) {
  53841. continue;
  53842. }
  53843. }
  53844. else if (!sprite.isPickable) {
  53845. continue;
  53846. }
  53847. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53848. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53849. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53850. if (ray.intersectsBoxMinMax(min, max)) {
  53851. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53852. if (distance > currentDistance) {
  53853. distance = currentDistance;
  53854. currentSprite = sprite;
  53855. if (fastCheck) {
  53856. break;
  53857. }
  53858. }
  53859. }
  53860. }
  53861. if (currentSprite) {
  53862. var result = new BABYLON.PickingInfo();
  53863. result.hit = true;
  53864. result.pickedSprite = currentSprite;
  53865. result.distance = distance;
  53866. return result;
  53867. }
  53868. return null;
  53869. };
  53870. SpriteManager.prototype.render = function () {
  53871. // Check
  53872. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53873. return;
  53874. var engine = this._scene.getEngine();
  53875. var baseSize = this._spriteTexture.getBaseSize();
  53876. // Sprites
  53877. var deltaTime = engine.getDeltaTime();
  53878. var max = Math.min(this._capacity, this.sprites.length);
  53879. var rowSize = baseSize.width / this.cellWidth;
  53880. var offset = 0;
  53881. for (var index = 0; index < max; index++) {
  53882. var sprite = this.sprites[index];
  53883. if (!sprite) {
  53884. continue;
  53885. }
  53886. sprite._animate(deltaTime);
  53887. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53888. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53889. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53890. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53891. }
  53892. this._buffer.update(this._vertexData);
  53893. // Render
  53894. var effect = this._effectBase;
  53895. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53896. effect = this._effectFog;
  53897. }
  53898. engine.enableEffect(effect);
  53899. var viewMatrix = this._scene.getViewMatrix();
  53900. effect.setTexture("diffuseSampler", this._spriteTexture);
  53901. effect.setMatrix("view", viewMatrix);
  53902. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53903. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53904. // Fog
  53905. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53906. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53907. effect.setColor3("vFogColor", this._scene.fogColor);
  53908. }
  53909. // VBOs
  53910. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53911. // Draw order
  53912. engine.setDepthFunctionToLessOrEqual();
  53913. effect.setBool("alphaTest", true);
  53914. engine.setColorWrite(false);
  53915. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53916. engine.setColorWrite(true);
  53917. effect.setBool("alphaTest", false);
  53918. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53919. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  53920. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53921. };
  53922. SpriteManager.prototype.dispose = function () {
  53923. if (this._buffer) {
  53924. this._buffer.dispose();
  53925. this._buffer = null;
  53926. }
  53927. if (this._indexBuffer) {
  53928. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53929. this._indexBuffer = null;
  53930. }
  53931. if (this._spriteTexture) {
  53932. this._spriteTexture.dispose();
  53933. this._spriteTexture = null;
  53934. }
  53935. // Remove from scene
  53936. var index = this._scene.spriteManagers.indexOf(this);
  53937. this._scene.spriteManagers.splice(index, 1);
  53938. // Callback
  53939. this.onDisposeObservable.notifyObservers(this);
  53940. this.onDisposeObservable.clear();
  53941. };
  53942. return SpriteManager;
  53943. }());
  53944. BABYLON.SpriteManager = SpriteManager;
  53945. })(BABYLON || (BABYLON = {}));
  53946. //# sourceMappingURL=babylon.spriteManager.js.map
  53947. var BABYLON;
  53948. (function (BABYLON) {
  53949. var Sprite = /** @class */ (function () {
  53950. function Sprite(name, manager) {
  53951. this.name = name;
  53952. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53953. this.width = 1.0;
  53954. this.height = 1.0;
  53955. this.angle = 0;
  53956. this.cellIndex = 0;
  53957. this.invertU = 0;
  53958. this.invertV = 0;
  53959. this.animations = new Array();
  53960. this.isPickable = false;
  53961. this._animationStarted = false;
  53962. this._loopAnimation = false;
  53963. this._fromIndex = 0;
  53964. this._toIndex = 0;
  53965. this._delay = 0;
  53966. this._direction = 1;
  53967. this._time = 0;
  53968. this._manager = manager;
  53969. this._manager.sprites.push(this);
  53970. this.position = BABYLON.Vector3.Zero();
  53971. }
  53972. Object.defineProperty(Sprite.prototype, "size", {
  53973. get: function () {
  53974. return this.width;
  53975. },
  53976. set: function (value) {
  53977. this.width = value;
  53978. this.height = value;
  53979. },
  53980. enumerable: true,
  53981. configurable: true
  53982. });
  53983. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53984. this._fromIndex = from;
  53985. this._toIndex = to;
  53986. this._loopAnimation = loop;
  53987. this._delay = delay;
  53988. this._animationStarted = true;
  53989. this._direction = from < to ? 1 : -1;
  53990. this.cellIndex = from;
  53991. this._time = 0;
  53992. this._onAnimationEnd = onAnimationEnd;
  53993. };
  53994. Sprite.prototype.stopAnimation = function () {
  53995. this._animationStarted = false;
  53996. };
  53997. Sprite.prototype._animate = function (deltaTime) {
  53998. if (!this._animationStarted)
  53999. return;
  54000. this._time += deltaTime;
  54001. if (this._time > this._delay) {
  54002. this._time = this._time % this._delay;
  54003. this.cellIndex += this._direction;
  54004. if (this.cellIndex > this._toIndex) {
  54005. if (this._loopAnimation) {
  54006. this.cellIndex = this._fromIndex;
  54007. }
  54008. else {
  54009. this.cellIndex = this._toIndex;
  54010. this._animationStarted = false;
  54011. if (this._onAnimationEnd) {
  54012. this._onAnimationEnd();
  54013. }
  54014. if (this.disposeWhenFinishedAnimating) {
  54015. this.dispose();
  54016. }
  54017. }
  54018. }
  54019. }
  54020. };
  54021. Sprite.prototype.dispose = function () {
  54022. for (var i = 0; i < this._manager.sprites.length; i++) {
  54023. if (this._manager.sprites[i] == this) {
  54024. this._manager.sprites.splice(i, 1);
  54025. }
  54026. }
  54027. };
  54028. return Sprite;
  54029. }());
  54030. BABYLON.Sprite = Sprite;
  54031. })(BABYLON || (BABYLON = {}));
  54032. //# sourceMappingURL=babylon.sprite.js.map
  54033. var BABYLON;
  54034. (function (BABYLON) {
  54035. var IntersectionInfo = /** @class */ (function () {
  54036. function IntersectionInfo(bu, bv, distance) {
  54037. this.bu = bu;
  54038. this.bv = bv;
  54039. this.distance = distance;
  54040. this.faceId = 0;
  54041. this.subMeshId = 0;
  54042. }
  54043. return IntersectionInfo;
  54044. }());
  54045. BABYLON.IntersectionInfo = IntersectionInfo;
  54046. var PickingInfo = /** @class */ (function () {
  54047. function PickingInfo() {
  54048. this.hit = false;
  54049. this.distance = 0;
  54050. this.pickedPoint = null;
  54051. this.pickedMesh = null;
  54052. this.bu = 0;
  54053. this.bv = 0;
  54054. this.faceId = -1;
  54055. this.subMeshId = 0;
  54056. this.pickedSprite = null;
  54057. }
  54058. // Methods
  54059. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54060. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54061. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54062. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54063. return null;
  54064. }
  54065. var indices = this.pickedMesh.getIndices();
  54066. if (!indices) {
  54067. return null;
  54068. }
  54069. var result;
  54070. if (useVerticesNormals) {
  54071. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54072. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54073. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54074. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54075. normal0 = normal0.scale(this.bu);
  54076. normal1 = normal1.scale(this.bv);
  54077. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54078. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54079. }
  54080. else {
  54081. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54082. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54083. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54084. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54085. var p1p2 = vertex1.subtract(vertex2);
  54086. var p3p2 = vertex3.subtract(vertex2);
  54087. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54088. }
  54089. if (useWorldCoordinates) {
  54090. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54091. }
  54092. return BABYLON.Vector3.Normalize(result);
  54093. };
  54094. PickingInfo.prototype.getTextureCoordinates = function () {
  54095. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54096. return null;
  54097. }
  54098. var indices = this.pickedMesh.getIndices();
  54099. if (!indices) {
  54100. return null;
  54101. }
  54102. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54103. if (!uvs) {
  54104. return null;
  54105. }
  54106. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54107. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54108. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54109. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54110. uv1 = uv1.scale(this.bu);
  54111. uv2 = uv2.scale(this.bv);
  54112. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54113. };
  54114. return PickingInfo;
  54115. }());
  54116. BABYLON.PickingInfo = PickingInfo;
  54117. })(BABYLON || (BABYLON = {}));
  54118. //# sourceMappingURL=babylon.pickingInfo.js.map
  54119. var BABYLON;
  54120. (function (BABYLON) {
  54121. var Ray = /** @class */ (function () {
  54122. function Ray(origin, direction, length) {
  54123. if (length === void 0) { length = Number.MAX_VALUE; }
  54124. this.origin = origin;
  54125. this.direction = direction;
  54126. this.length = length;
  54127. }
  54128. // Methods
  54129. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54130. var d = 0.0;
  54131. var maxValue = Number.MAX_VALUE;
  54132. var inv;
  54133. var min;
  54134. var max;
  54135. var temp;
  54136. if (Math.abs(this.direction.x) < 0.0000001) {
  54137. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54138. return false;
  54139. }
  54140. }
  54141. else {
  54142. inv = 1.0 / this.direction.x;
  54143. min = (minimum.x - this.origin.x) * inv;
  54144. max = (maximum.x - this.origin.x) * inv;
  54145. if (max === -Infinity) {
  54146. max = Infinity;
  54147. }
  54148. if (min > max) {
  54149. temp = min;
  54150. min = max;
  54151. max = temp;
  54152. }
  54153. d = Math.max(min, d);
  54154. maxValue = Math.min(max, maxValue);
  54155. if (d > maxValue) {
  54156. return false;
  54157. }
  54158. }
  54159. if (Math.abs(this.direction.y) < 0.0000001) {
  54160. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54161. return false;
  54162. }
  54163. }
  54164. else {
  54165. inv = 1.0 / this.direction.y;
  54166. min = (minimum.y - this.origin.y) * inv;
  54167. max = (maximum.y - this.origin.y) * inv;
  54168. if (max === -Infinity) {
  54169. max = Infinity;
  54170. }
  54171. if (min > max) {
  54172. temp = min;
  54173. min = max;
  54174. max = temp;
  54175. }
  54176. d = Math.max(min, d);
  54177. maxValue = Math.min(max, maxValue);
  54178. if (d > maxValue) {
  54179. return false;
  54180. }
  54181. }
  54182. if (Math.abs(this.direction.z) < 0.0000001) {
  54183. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54184. return false;
  54185. }
  54186. }
  54187. else {
  54188. inv = 1.0 / this.direction.z;
  54189. min = (minimum.z - this.origin.z) * inv;
  54190. max = (maximum.z - this.origin.z) * inv;
  54191. if (max === -Infinity) {
  54192. max = Infinity;
  54193. }
  54194. if (min > max) {
  54195. temp = min;
  54196. min = max;
  54197. max = temp;
  54198. }
  54199. d = Math.max(min, d);
  54200. maxValue = Math.min(max, maxValue);
  54201. if (d > maxValue) {
  54202. return false;
  54203. }
  54204. }
  54205. return true;
  54206. };
  54207. Ray.prototype.intersectsBox = function (box) {
  54208. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54209. };
  54210. Ray.prototype.intersectsSphere = function (sphere) {
  54211. var x = sphere.center.x - this.origin.x;
  54212. var y = sphere.center.y - this.origin.y;
  54213. var z = sphere.center.z - this.origin.z;
  54214. var pyth = (x * x) + (y * y) + (z * z);
  54215. var rr = sphere.radius * sphere.radius;
  54216. if (pyth <= rr) {
  54217. return true;
  54218. }
  54219. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54220. if (dot < 0.0) {
  54221. return false;
  54222. }
  54223. var temp = pyth - (dot * dot);
  54224. return temp <= rr;
  54225. };
  54226. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54227. if (!this._edge1) {
  54228. this._edge1 = BABYLON.Vector3.Zero();
  54229. this._edge2 = BABYLON.Vector3.Zero();
  54230. this._pvec = BABYLON.Vector3.Zero();
  54231. this._tvec = BABYLON.Vector3.Zero();
  54232. this._qvec = BABYLON.Vector3.Zero();
  54233. }
  54234. vertex1.subtractToRef(vertex0, this._edge1);
  54235. vertex2.subtractToRef(vertex0, this._edge2);
  54236. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54237. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54238. if (det === 0) {
  54239. return null;
  54240. }
  54241. var invdet = 1 / det;
  54242. this.origin.subtractToRef(vertex0, this._tvec);
  54243. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54244. if (bu < 0 || bu > 1.0) {
  54245. return null;
  54246. }
  54247. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54248. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54249. if (bv < 0 || bu + bv > 1.0) {
  54250. return null;
  54251. }
  54252. //check if the distance is longer than the predefined length.
  54253. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54254. if (distance > this.length) {
  54255. return null;
  54256. }
  54257. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54258. };
  54259. Ray.prototype.intersectsPlane = function (plane) {
  54260. var distance;
  54261. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54262. if (Math.abs(result1) < 9.99999997475243E-07) {
  54263. return null;
  54264. }
  54265. else {
  54266. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54267. distance = (-plane.d - result2) / result1;
  54268. if (distance < 0.0) {
  54269. if (distance < -9.99999997475243E-07) {
  54270. return null;
  54271. }
  54272. else {
  54273. return 0;
  54274. }
  54275. }
  54276. return distance;
  54277. }
  54278. };
  54279. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54280. var tm = BABYLON.Tmp.Matrix[0];
  54281. mesh.getWorldMatrix().invertToRef(tm);
  54282. if (this._tmpRay) {
  54283. Ray.TransformToRef(this, tm, this._tmpRay);
  54284. }
  54285. else {
  54286. this._tmpRay = Ray.Transform(this, tm);
  54287. }
  54288. return mesh.intersects(this._tmpRay, fastCheck);
  54289. };
  54290. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54291. if (results) {
  54292. results.length = 0;
  54293. }
  54294. else {
  54295. results = [];
  54296. }
  54297. for (var i = 0; i < meshes.length; i++) {
  54298. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54299. if (pickInfo.hit) {
  54300. results.push(pickInfo);
  54301. }
  54302. }
  54303. results.sort(this._comparePickingInfo);
  54304. return results;
  54305. };
  54306. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54307. if (pickingInfoA.distance < pickingInfoB.distance) {
  54308. return -1;
  54309. }
  54310. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54311. return 1;
  54312. }
  54313. else {
  54314. return 0;
  54315. }
  54316. };
  54317. /**
  54318. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54319. * @param sega the first point of the segment to test the intersection against
  54320. * @param segb the second point of the segment to test the intersection against
  54321. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54322. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54323. */
  54324. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54325. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54326. var u = segb.subtract(sega);
  54327. var v = rsegb.subtract(this.origin);
  54328. var w = sega.subtract(this.origin);
  54329. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54330. var b = BABYLON.Vector3.Dot(u, v);
  54331. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54332. var d = BABYLON.Vector3.Dot(u, w);
  54333. var e = BABYLON.Vector3.Dot(v, w);
  54334. var D = a * c - b * b; // always >= 0
  54335. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54336. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54337. // compute the line parameters of the two closest points
  54338. if (D < Ray.smallnum) { // the lines are almost parallel
  54339. sN = 0.0; // force using point P0 on segment S1
  54340. sD = 1.0; // to prevent possible division by 0.0 later
  54341. tN = e;
  54342. tD = c;
  54343. }
  54344. else { // get the closest points on the infinite lines
  54345. sN = (b * e - c * d);
  54346. tN = (a * e - b * d);
  54347. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54348. sN = 0.0;
  54349. tN = e;
  54350. tD = c;
  54351. }
  54352. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54353. sN = sD;
  54354. tN = e + b;
  54355. tD = c;
  54356. }
  54357. }
  54358. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54359. tN = 0.0;
  54360. // recompute sc for this edge
  54361. if (-d < 0.0) {
  54362. sN = 0.0;
  54363. }
  54364. else if (-d > a)
  54365. sN = sD;
  54366. else {
  54367. sN = -d;
  54368. sD = a;
  54369. }
  54370. }
  54371. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54372. tN = tD;
  54373. // recompute sc for this edge
  54374. if ((-d + b) < 0.0) {
  54375. sN = 0;
  54376. }
  54377. else if ((-d + b) > a) {
  54378. sN = sD;
  54379. }
  54380. else {
  54381. sN = (-d + b);
  54382. sD = a;
  54383. }
  54384. }
  54385. // finally do the division to get sc and tc
  54386. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54387. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54388. // get the difference of the two closest points
  54389. var qtc = v.multiplyByFloats(tc, tc, tc);
  54390. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54391. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54392. if (isIntersected) {
  54393. return qtc.length();
  54394. }
  54395. return -1;
  54396. };
  54397. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54398. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54399. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54400. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54401. this.direction.normalize();
  54402. return this;
  54403. };
  54404. // Statics
  54405. Ray.Zero = function () {
  54406. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54407. };
  54408. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54409. var result = Ray.Zero();
  54410. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54411. };
  54412. /**
  54413. * 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
  54414. * transformed to the given world matrix.
  54415. * @param origin The origin point
  54416. * @param end The end point
  54417. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54418. */
  54419. Ray.CreateNewFromTo = function (origin, end, world) {
  54420. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54421. var direction = end.subtract(origin);
  54422. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54423. direction.normalize();
  54424. return Ray.Transform(new Ray(origin, direction, length), world);
  54425. };
  54426. Ray.Transform = function (ray, matrix) {
  54427. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54428. Ray.TransformToRef(ray, matrix, result);
  54429. return result;
  54430. };
  54431. Ray.TransformToRef = function (ray, matrix, result) {
  54432. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54433. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54434. result.length = ray.length;
  54435. var dir = result.direction;
  54436. var len = dir.length();
  54437. if (!(len === 0 || len === 1)) {
  54438. var num = 1.0 / len;
  54439. dir.x *= num;
  54440. dir.y *= num;
  54441. dir.z *= num;
  54442. result.length *= len;
  54443. }
  54444. };
  54445. Ray.smallnum = 0.00000001;
  54446. Ray.rayl = 10e8;
  54447. return Ray;
  54448. }());
  54449. BABYLON.Ray = Ray;
  54450. })(BABYLON || (BABYLON = {}));
  54451. //# sourceMappingURL=babylon.ray.js.map
  54452. var BABYLON;
  54453. (function (BABYLON) {
  54454. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54455. if (boxMin.x > sphereCenter.x + sphereRadius)
  54456. return false;
  54457. if (sphereCenter.x - sphereRadius > boxMax.x)
  54458. return false;
  54459. if (boxMin.y > sphereCenter.y + sphereRadius)
  54460. return false;
  54461. if (sphereCenter.y - sphereRadius > boxMax.y)
  54462. return false;
  54463. if (boxMin.z > sphereCenter.z + sphereRadius)
  54464. return false;
  54465. if (sphereCenter.z - sphereRadius > boxMax.z)
  54466. return false;
  54467. return true;
  54468. };
  54469. var getLowestRoot = (function () {
  54470. var result = { root: 0, found: false };
  54471. return function (a, b, c, maxR) {
  54472. result.root = 0;
  54473. result.found = false;
  54474. var determinant = b * b - 4.0 * a * c;
  54475. if (determinant < 0)
  54476. return result;
  54477. var sqrtD = Math.sqrt(determinant);
  54478. var r1 = (-b - sqrtD) / (2.0 * a);
  54479. var r2 = (-b + sqrtD) / (2.0 * a);
  54480. if (r1 > r2) {
  54481. var temp = r2;
  54482. r2 = r1;
  54483. r1 = temp;
  54484. }
  54485. if (r1 > 0 && r1 < maxR) {
  54486. result.root = r1;
  54487. result.found = true;
  54488. return result;
  54489. }
  54490. if (r2 > 0 && r2 < maxR) {
  54491. result.root = r2;
  54492. result.found = true;
  54493. return result;
  54494. }
  54495. return result;
  54496. };
  54497. })();
  54498. var Collider = /** @class */ (function () {
  54499. function Collider() {
  54500. this._collisionPoint = BABYLON.Vector3.Zero();
  54501. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54502. this._tempVector = BABYLON.Vector3.Zero();
  54503. this._tempVector2 = BABYLON.Vector3.Zero();
  54504. this._tempVector3 = BABYLON.Vector3.Zero();
  54505. this._tempVector4 = BABYLON.Vector3.Zero();
  54506. this._edge = BABYLON.Vector3.Zero();
  54507. this._baseToVertex = BABYLON.Vector3.Zero();
  54508. this._destinationPoint = BABYLON.Vector3.Zero();
  54509. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54510. this._displacementVector = BABYLON.Vector3.Zero();
  54511. this._radius = BABYLON.Vector3.One();
  54512. this._retry = 0;
  54513. this._basePointWorld = BABYLON.Vector3.Zero();
  54514. this._velocityWorld = BABYLON.Vector3.Zero();
  54515. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54516. this._collisionMask = -1;
  54517. }
  54518. Object.defineProperty(Collider.prototype, "collisionMask", {
  54519. get: function () {
  54520. return this._collisionMask;
  54521. },
  54522. set: function (mask) {
  54523. this._collisionMask = !isNaN(mask) ? mask : -1;
  54524. },
  54525. enumerable: true,
  54526. configurable: true
  54527. });
  54528. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54529. /**
  54530. * Gets the plane normal used to compute the sliding response (in local space)
  54531. */
  54532. get: function () {
  54533. return this._slidePlaneNormal;
  54534. },
  54535. enumerable: true,
  54536. configurable: true
  54537. });
  54538. // Methods
  54539. Collider.prototype._initialize = function (source, dir, e) {
  54540. this._velocity = dir;
  54541. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54542. this._basePoint = source;
  54543. source.multiplyToRef(this._radius, this._basePointWorld);
  54544. dir.multiplyToRef(this._radius, this._velocityWorld);
  54545. this._velocityWorldLength = this._velocityWorld.length();
  54546. this._epsilon = e;
  54547. this.collisionFound = false;
  54548. };
  54549. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54550. pa.subtractToRef(point, this._tempVector);
  54551. pb.subtractToRef(point, this._tempVector2);
  54552. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54553. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54554. if (d < 0)
  54555. return false;
  54556. pc.subtractToRef(point, this._tempVector3);
  54557. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54558. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54559. if (d < 0)
  54560. return false;
  54561. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54562. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54563. return d >= 0;
  54564. };
  54565. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54566. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54567. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54568. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54569. return false;
  54570. }
  54571. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54572. return false;
  54573. return true;
  54574. };
  54575. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54576. var t0;
  54577. var embeddedInPlane = false;
  54578. //defensive programming, actually not needed.
  54579. if (!trianglePlaneArray) {
  54580. trianglePlaneArray = [];
  54581. }
  54582. if (!trianglePlaneArray[faceIndex]) {
  54583. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54584. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54585. }
  54586. var trianglePlane = trianglePlaneArray[faceIndex];
  54587. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54588. return;
  54589. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54590. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54591. if (normalDotVelocity == 0) {
  54592. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54593. return;
  54594. embeddedInPlane = true;
  54595. t0 = 0;
  54596. }
  54597. else {
  54598. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54599. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54600. if (t0 > t1) {
  54601. var temp = t1;
  54602. t1 = t0;
  54603. t0 = temp;
  54604. }
  54605. if (t0 > 1.0 || t1 < 0.0)
  54606. return;
  54607. if (t0 < 0)
  54608. t0 = 0;
  54609. if (t0 > 1.0)
  54610. t0 = 1.0;
  54611. }
  54612. this._collisionPoint.copyFromFloats(0, 0, 0);
  54613. var found = false;
  54614. var t = 1.0;
  54615. if (!embeddedInPlane) {
  54616. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54617. this._velocity.scaleToRef(t0, this._tempVector);
  54618. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54619. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54620. found = true;
  54621. t = t0;
  54622. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54623. }
  54624. }
  54625. if (!found) {
  54626. var velocitySquaredLength = this._velocity.lengthSquared();
  54627. var a = velocitySquaredLength;
  54628. this._basePoint.subtractToRef(p1, this._tempVector);
  54629. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54630. var c = this._tempVector.lengthSquared() - 1.0;
  54631. var lowestRoot = getLowestRoot(a, b, c, t);
  54632. if (lowestRoot.found) {
  54633. t = lowestRoot.root;
  54634. found = true;
  54635. this._collisionPoint.copyFrom(p1);
  54636. }
  54637. this._basePoint.subtractToRef(p2, this._tempVector);
  54638. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54639. c = this._tempVector.lengthSquared() - 1.0;
  54640. lowestRoot = getLowestRoot(a, b, c, t);
  54641. if (lowestRoot.found) {
  54642. t = lowestRoot.root;
  54643. found = true;
  54644. this._collisionPoint.copyFrom(p2);
  54645. }
  54646. this._basePoint.subtractToRef(p3, this._tempVector);
  54647. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54648. c = this._tempVector.lengthSquared() - 1.0;
  54649. lowestRoot = getLowestRoot(a, b, c, t);
  54650. if (lowestRoot.found) {
  54651. t = lowestRoot.root;
  54652. found = true;
  54653. this._collisionPoint.copyFrom(p3);
  54654. }
  54655. p2.subtractToRef(p1, this._edge);
  54656. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54657. var edgeSquaredLength = this._edge.lengthSquared();
  54658. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54659. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54660. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54661. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54662. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54663. lowestRoot = getLowestRoot(a, b, c, t);
  54664. if (lowestRoot.found) {
  54665. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54666. if (f >= 0.0 && f <= 1.0) {
  54667. t = lowestRoot.root;
  54668. found = true;
  54669. this._edge.scaleInPlace(f);
  54670. p1.addToRef(this._edge, this._collisionPoint);
  54671. }
  54672. }
  54673. p3.subtractToRef(p2, this._edge);
  54674. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54675. edgeSquaredLength = this._edge.lengthSquared();
  54676. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54677. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54678. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54679. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54680. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54681. lowestRoot = getLowestRoot(a, b, c, t);
  54682. if (lowestRoot.found) {
  54683. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54684. if (f >= 0.0 && f <= 1.0) {
  54685. t = lowestRoot.root;
  54686. found = true;
  54687. this._edge.scaleInPlace(f);
  54688. p2.addToRef(this._edge, this._collisionPoint);
  54689. }
  54690. }
  54691. p1.subtractToRef(p3, this._edge);
  54692. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54693. edgeSquaredLength = this._edge.lengthSquared();
  54694. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54695. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54696. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54697. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54698. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54699. lowestRoot = getLowestRoot(a, b, c, t);
  54700. if (lowestRoot.found) {
  54701. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54702. if (f >= 0.0 && f <= 1.0) {
  54703. t = lowestRoot.root;
  54704. found = true;
  54705. this._edge.scaleInPlace(f);
  54706. p3.addToRef(this._edge, this._collisionPoint);
  54707. }
  54708. }
  54709. }
  54710. if (found) {
  54711. var distToCollision = t * this._velocity.length();
  54712. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54713. if (!this.intersectionPoint) {
  54714. this.intersectionPoint = this._collisionPoint.clone();
  54715. }
  54716. else {
  54717. this.intersectionPoint.copyFrom(this._collisionPoint);
  54718. }
  54719. this._nearestDistance = distToCollision;
  54720. this.collisionFound = true;
  54721. }
  54722. }
  54723. };
  54724. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54725. for (var i = indexStart; i < indexEnd; i += 3) {
  54726. var p1 = pts[indices[i] - decal];
  54727. var p2 = pts[indices[i + 1] - decal];
  54728. var p3 = pts[indices[i + 2] - decal];
  54729. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54730. }
  54731. };
  54732. Collider.prototype._getResponse = function (pos, vel) {
  54733. pos.addToRef(vel, this._destinationPoint);
  54734. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54735. this._basePoint.addToRef(vel, pos);
  54736. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54737. this._slidePlaneNormal.normalize();
  54738. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54739. pos.addInPlace(this._displacementVector);
  54740. this.intersectionPoint.addInPlace(this._displacementVector);
  54741. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54742. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54743. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54744. };
  54745. return Collider;
  54746. }());
  54747. BABYLON.Collider = Collider;
  54748. })(BABYLON || (BABYLON = {}));
  54749. //# sourceMappingURL=babylon.collider.js.map
  54750. var BABYLON;
  54751. (function (BABYLON) {
  54752. //WebWorker code will be inserted to this variable.
  54753. BABYLON.CollisionWorker = "";
  54754. /** Defines supported task for worker process */
  54755. var WorkerTaskType;
  54756. (function (WorkerTaskType) {
  54757. /** Initialization */
  54758. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54759. /** Update of geometry */
  54760. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54761. /** Evaluate collision */
  54762. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54763. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54764. /** Defines kind of replies returned by worker */
  54765. var WorkerReplyType;
  54766. (function (WorkerReplyType) {
  54767. /** Success */
  54768. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54769. /** Unkown error */
  54770. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54771. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54772. var CollisionCoordinatorWorker = /** @class */ (function () {
  54773. function CollisionCoordinatorWorker() {
  54774. var _this = this;
  54775. this._scaledPosition = BABYLON.Vector3.Zero();
  54776. this._scaledVelocity = BABYLON.Vector3.Zero();
  54777. this.onMeshUpdated = function (transformNode) {
  54778. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54779. };
  54780. this.onGeometryUpdated = function (geometry) {
  54781. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54782. };
  54783. this._afterRender = function () {
  54784. if (!_this._init)
  54785. return;
  54786. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54787. return;
  54788. }
  54789. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54790. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54791. if (_this._runningUpdated > 4) {
  54792. return;
  54793. }
  54794. ++_this._runningUpdated;
  54795. var payload = {
  54796. updatedMeshes: _this._addUpdateMeshesList,
  54797. updatedGeometries: _this._addUpdateGeometriesList,
  54798. removedGeometries: _this._toRemoveGeometryArray,
  54799. removedMeshes: _this._toRemoveMeshesArray
  54800. };
  54801. var message = {
  54802. payload: payload,
  54803. taskType: WorkerTaskType.UPDATE
  54804. };
  54805. var serializable = [];
  54806. for (var id in payload.updatedGeometries) {
  54807. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54808. //prepare transferables
  54809. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54810. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54811. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54812. }
  54813. }
  54814. _this._worker.postMessage(message, serializable);
  54815. _this._addUpdateMeshesList = {};
  54816. _this._addUpdateGeometriesList = {};
  54817. _this._toRemoveGeometryArray = [];
  54818. _this._toRemoveMeshesArray = [];
  54819. };
  54820. this._onMessageFromWorker = function (e) {
  54821. var returnData = e.data;
  54822. if (returnData.error != WorkerReplyType.SUCCESS) {
  54823. //TODO what errors can be returned from the worker?
  54824. BABYLON.Tools.Warn("error returned from worker!");
  54825. return;
  54826. }
  54827. switch (returnData.taskType) {
  54828. case WorkerTaskType.INIT:
  54829. _this._init = true;
  54830. //Update the worked with ALL of the scene's current state
  54831. _this._scene.meshes.forEach(function (mesh) {
  54832. _this.onMeshAdded(mesh);
  54833. });
  54834. _this._scene.getGeometries().forEach(function (geometry) {
  54835. _this.onGeometryAdded(geometry);
  54836. });
  54837. break;
  54838. case WorkerTaskType.UPDATE:
  54839. _this._runningUpdated--;
  54840. break;
  54841. case WorkerTaskType.COLLIDE:
  54842. var returnPayload = returnData.payload;
  54843. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54844. return;
  54845. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54846. if (callback) {
  54847. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54848. if (mesh) {
  54849. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54850. }
  54851. }
  54852. //cleanup
  54853. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54854. break;
  54855. }
  54856. };
  54857. this._collisionsCallbackArray = [];
  54858. this._init = false;
  54859. this._runningUpdated = 0;
  54860. this._addUpdateMeshesList = {};
  54861. this._addUpdateGeometriesList = {};
  54862. this._toRemoveGeometryArray = [];
  54863. this._toRemoveMeshesArray = [];
  54864. }
  54865. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54866. if (!this._init)
  54867. return;
  54868. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54869. return;
  54870. position.divideToRef(collider._radius, this._scaledPosition);
  54871. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54872. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54873. var payload = {
  54874. collider: {
  54875. position: this._scaledPosition.asArray(),
  54876. velocity: this._scaledVelocity.asArray(),
  54877. radius: collider._radius.asArray()
  54878. },
  54879. collisionId: collisionIndex,
  54880. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54881. maximumRetry: maximumRetry
  54882. };
  54883. var message = {
  54884. payload: payload,
  54885. taskType: WorkerTaskType.COLLIDE
  54886. };
  54887. this._worker.postMessage(message);
  54888. };
  54889. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54890. this._scene = scene;
  54891. this._scene.registerAfterRender(this._afterRender);
  54892. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54893. this._worker = new Worker(workerUrl);
  54894. this._worker.onmessage = this._onMessageFromWorker;
  54895. var message = {
  54896. payload: {},
  54897. taskType: WorkerTaskType.INIT
  54898. };
  54899. this._worker.postMessage(message);
  54900. };
  54901. CollisionCoordinatorWorker.prototype.destroy = function () {
  54902. this._scene.unregisterAfterRender(this._afterRender);
  54903. this._worker.terminate();
  54904. };
  54905. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54906. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54907. this.onMeshUpdated(mesh);
  54908. };
  54909. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54910. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54911. };
  54912. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54913. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54914. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54915. this.onGeometryUpdated(geometry);
  54916. };
  54917. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54918. this._toRemoveGeometryArray.push(geometry.id);
  54919. };
  54920. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54921. var submeshes = [];
  54922. if (mesh.subMeshes) {
  54923. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54924. var boundingInfo = sm.getBoundingInfo();
  54925. return {
  54926. position: idx,
  54927. verticesStart: sm.verticesStart,
  54928. verticesCount: sm.verticesCount,
  54929. indexStart: sm.indexStart,
  54930. indexCount: sm.indexCount,
  54931. hasMaterial: !!sm.getMaterial(),
  54932. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54933. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54934. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54935. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54936. };
  54937. });
  54938. }
  54939. var geometryId = null;
  54940. if (mesh instanceof BABYLON.Mesh) {
  54941. var geometry = mesh.geometry;
  54942. geometryId = geometry ? geometry.id : null;
  54943. }
  54944. else if (mesh instanceof BABYLON.InstancedMesh) {
  54945. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54946. geometryId = geometry ? geometry.id : null;
  54947. }
  54948. var boundingInfo = mesh.getBoundingInfo();
  54949. return {
  54950. uniqueId: mesh.uniqueId,
  54951. id: mesh.id,
  54952. name: mesh.name,
  54953. geometryId: geometryId,
  54954. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54955. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54956. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54957. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54958. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54959. subMeshes: submeshes,
  54960. checkCollisions: mesh.checkCollisions
  54961. };
  54962. };
  54963. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54964. return {
  54965. id: geometry.id,
  54966. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54967. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54968. indices: new Uint32Array(geometry.getIndices() || []),
  54969. };
  54970. };
  54971. return CollisionCoordinatorWorker;
  54972. }());
  54973. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54974. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54975. function CollisionCoordinatorLegacy() {
  54976. this._scaledPosition = BABYLON.Vector3.Zero();
  54977. this._scaledVelocity = BABYLON.Vector3.Zero();
  54978. this._finalPosition = BABYLON.Vector3.Zero();
  54979. }
  54980. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54981. position.divideToRef(collider._radius, this._scaledPosition);
  54982. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54983. collider.collidedMesh = null;
  54984. collider._retry = 0;
  54985. collider._initialVelocity = this._scaledVelocity;
  54986. collider._initialPosition = this._scaledPosition;
  54987. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54988. this._finalPosition.multiplyInPlace(collider._radius);
  54989. //run the callback
  54990. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54991. };
  54992. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54993. this._scene = scene;
  54994. };
  54995. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54996. //Legacy need no destruction method.
  54997. };
  54998. //No update in legacy mode
  54999. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55000. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55001. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55002. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55003. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55004. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55005. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55006. if (excludedMesh === void 0) { excludedMesh = null; }
  55007. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55008. if (collider._retry >= maximumRetry) {
  55009. finalPosition.copyFrom(position);
  55010. return;
  55011. }
  55012. // Check if this is a mesh else camera or -1
  55013. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55014. collider._initialize(position, velocity, closeDistance);
  55015. // Check all meshes
  55016. for (var index = 0; index < this._scene.meshes.length; index++) {
  55017. var mesh = this._scene.meshes[index];
  55018. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55019. mesh._checkCollision(collider);
  55020. }
  55021. }
  55022. if (!collider.collisionFound) {
  55023. position.addToRef(velocity, finalPosition);
  55024. return;
  55025. }
  55026. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55027. collider._getResponse(position, velocity);
  55028. }
  55029. if (velocity.length() <= closeDistance) {
  55030. finalPosition.copyFrom(position);
  55031. return;
  55032. }
  55033. collider._retry++;
  55034. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55035. };
  55036. return CollisionCoordinatorLegacy;
  55037. }());
  55038. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55039. })(BABYLON || (BABYLON = {}));
  55040. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55041. var BABYLON;
  55042. (function (BABYLON) {
  55043. /**
  55044. * A particle represents one of the element emitted by a particle system.
  55045. * This is mainly define by its coordinates, direction, velocity and age.
  55046. */
  55047. var Particle = /** @class */ (function () {
  55048. /**
  55049. * Creates a new instance Particle
  55050. * @param particleSystem the particle system the particle belongs to
  55051. */
  55052. function Particle(
  55053. /**
  55054. * particleSystem the particle system the particle belongs to.
  55055. */
  55056. particleSystem) {
  55057. this.particleSystem = particleSystem;
  55058. /**
  55059. * The world position of the particle in the scene.
  55060. */
  55061. this.position = BABYLON.Vector3.Zero();
  55062. /**
  55063. * The world direction of the particle in the scene.
  55064. */
  55065. this.direction = BABYLON.Vector3.Zero();
  55066. /**
  55067. * The color of the particle.
  55068. */
  55069. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55070. /**
  55071. * The color change of the particle per step.
  55072. */
  55073. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55074. /**
  55075. * Defines how long will the life of the particle be.
  55076. */
  55077. this.lifeTime = 1.0;
  55078. /**
  55079. * The current age of the particle.
  55080. */
  55081. this.age = 0;
  55082. /**
  55083. * The current size of the particle.
  55084. */
  55085. this.size = 0;
  55086. /**
  55087. * The current angle of the particle.
  55088. */
  55089. this.angle = 0;
  55090. /**
  55091. * Defines how fast is the angle changing.
  55092. */
  55093. this.angularSpeed = 0;
  55094. /**
  55095. * Defines the cell index used by the particle to be rendered from a sprite.
  55096. */
  55097. this.cellIndex = 0;
  55098. this._currentFrameCounter = 0;
  55099. if (!this.particleSystem.isAnimationSheetEnabled) {
  55100. return;
  55101. }
  55102. this.updateCellInfoFromSystem();
  55103. }
  55104. Particle.prototype.updateCellInfoFromSystem = function () {
  55105. this.cellIndex = this.particleSystem.startSpriteCellID;
  55106. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55107. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55108. }
  55109. else {
  55110. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55111. }
  55112. };
  55113. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55114. // (ageOffset / scaledUpdateSpeed) / available cells
  55115. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55116. this._currentFrameCounter += scaledUpdateSpeed;
  55117. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55118. this._currentFrameCounter = 0;
  55119. this.cellIndex++;
  55120. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55121. this.cellIndex = this.particleSystem.endSpriteCellID;
  55122. }
  55123. }
  55124. };
  55125. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55126. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55127. this.cellIndex++;
  55128. this._currentFrameCounter = 0;
  55129. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55130. if (this.particleSystem.spriteCellLoop) {
  55131. this.cellIndex = this.particleSystem.startSpriteCellID;
  55132. }
  55133. else {
  55134. this.cellIndex = this.particleSystem.endSpriteCellID;
  55135. }
  55136. }
  55137. }
  55138. else {
  55139. this._currentFrameCounter++;
  55140. }
  55141. };
  55142. /**
  55143. * Copy the properties of particle to another one.
  55144. * @param other the particle to copy the information to.
  55145. */
  55146. Particle.prototype.copyTo = function (other) {
  55147. other.position.copyFrom(this.position);
  55148. other.direction.copyFrom(this.direction);
  55149. other.color.copyFrom(this.color);
  55150. other.colorStep.copyFrom(this.colorStep);
  55151. other.lifeTime = this.lifeTime;
  55152. other.age = this.age;
  55153. other.size = this.size;
  55154. other.angle = this.angle;
  55155. other.angularSpeed = this.angularSpeed;
  55156. other.particleSystem = this.particleSystem;
  55157. other.cellIndex = this.cellIndex;
  55158. };
  55159. return Particle;
  55160. }());
  55161. BABYLON.Particle = Particle;
  55162. })(BABYLON || (BABYLON = {}));
  55163. //# sourceMappingURL=babylon.particle.js.map
  55164. var BABYLON;
  55165. (function (BABYLON) {
  55166. /**
  55167. * This represents a particle system in Babylon.
  55168. * 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.
  55169. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55170. * @example https://doc.babylonjs.com/babylon101/particles
  55171. */
  55172. var ParticleSystem = /** @class */ (function () {
  55173. /**
  55174. * Instantiates a particle system.
  55175. * 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.
  55176. * @param name The name of the particle system
  55177. * @param capacity The max number of particles alive at the same time
  55178. * @param scene The scene the particle system belongs to
  55179. * @param customEffect a custom effect used to change the way particles are rendered by default
  55180. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55181. * @param epsilon Offset used to render the particles
  55182. */
  55183. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55184. if (customEffect === void 0) { customEffect = null; }
  55185. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55186. if (epsilon === void 0) { epsilon = 0.01; }
  55187. var _this = this;
  55188. /**
  55189. * List of animations used by the particle system.
  55190. */
  55191. this.animations = [];
  55192. /**
  55193. * The rendering group used by the Particle system to chose when to render.
  55194. */
  55195. this.renderingGroupId = 0;
  55196. /**
  55197. * The emitter represents the Mesh or position we are attaching the particle system to.
  55198. */
  55199. this.emitter = null;
  55200. /**
  55201. * The maximum number of particles to emit per frame
  55202. */
  55203. this.emitRate = 10;
  55204. /**
  55205. * If you want to launch only a few particles at once, that can be done, as well.
  55206. */
  55207. this.manualEmitCount = -1;
  55208. /**
  55209. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55210. */
  55211. this.updateSpeed = 0.01;
  55212. /**
  55213. * The amount of time the particle system is running (depends of the overall update speed).
  55214. */
  55215. this.targetStopDuration = 0;
  55216. /**
  55217. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55218. */
  55219. this.disposeOnStop = false;
  55220. /**
  55221. * Minimum power of emitting particles.
  55222. */
  55223. this.minEmitPower = 1;
  55224. /**
  55225. * Maximum power of emitting particles.
  55226. */
  55227. this.maxEmitPower = 1;
  55228. /**
  55229. * Minimum life time of emitting particles.
  55230. */
  55231. this.minLifeTime = 1;
  55232. /**
  55233. * Maximum life time of emitting particles.
  55234. */
  55235. this.maxLifeTime = 1;
  55236. /**
  55237. * Minimum Size of emitting particles.
  55238. */
  55239. this.minSize = 1;
  55240. /**
  55241. * Maximum Size of emitting particles.
  55242. */
  55243. this.maxSize = 1;
  55244. /**
  55245. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55246. */
  55247. this.minAngularSpeed = 0;
  55248. /**
  55249. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55250. */
  55251. this.maxAngularSpeed = 0;
  55252. /**
  55253. * The layer mask we are rendering the particles through.
  55254. */
  55255. this.layerMask = 0x0FFFFFFF;
  55256. /**
  55257. * This can help using your own shader to render the particle system.
  55258. * The according effect will be created
  55259. */
  55260. this.customShader = null;
  55261. /**
  55262. * By default particle system starts as soon as they are created. This prevents the
  55263. * automatic start to happen and let you decide when to start emitting particles.
  55264. */
  55265. this.preventAutoStart = false;
  55266. /**
  55267. * Callback triggered when the particle animation is ending.
  55268. */
  55269. this.onAnimationEnd = null;
  55270. /**
  55271. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55272. */
  55273. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55274. /**
  55275. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55276. * to override the particles.
  55277. */
  55278. this.forceDepthWrite = false;
  55279. /**
  55280. * You can use gravity if you want to give an orientation to your particles.
  55281. */
  55282. this.gravity = BABYLON.Vector3.Zero();
  55283. /**
  55284. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55285. */
  55286. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55287. /**
  55288. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55289. */
  55290. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55291. /**
  55292. * Color the particle will have at the end of its lifetime.
  55293. */
  55294. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55295. /**
  55296. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55297. */
  55298. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55299. /**
  55300. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55301. */
  55302. this.spriteCellLoop = true;
  55303. /**
  55304. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55305. */
  55306. this.spriteCellChangeSpeed = 0;
  55307. /**
  55308. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55309. */
  55310. this.startSpriteCellID = 0;
  55311. /**
  55312. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55313. */
  55314. this.endSpriteCellID = 0;
  55315. /**
  55316. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55317. */
  55318. this.spriteCellWidth = 0;
  55319. /**
  55320. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55321. */
  55322. this.spriteCellHeight = 0;
  55323. /**
  55324. * An event triggered when the system is disposed.
  55325. */
  55326. this.onDisposeObservable = new BABYLON.Observable();
  55327. this._particles = new Array();
  55328. this._stockParticles = new Array();
  55329. this._newPartsExcess = 0;
  55330. this._vertexBuffers = {};
  55331. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55332. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55333. this._scaledDirection = BABYLON.Vector3.Zero();
  55334. this._scaledGravity = BABYLON.Vector3.Zero();
  55335. this._currentRenderId = -1;
  55336. this._started = false;
  55337. this._stopped = false;
  55338. this._actualFrame = 0;
  55339. this._vertexBufferSize = 11;
  55340. // start of sub system methods
  55341. /**
  55342. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55343. * Its lifetime will start back at 0.
  55344. */
  55345. this.recycleParticle = function (particle) {
  55346. var lastParticle = _this._particles.pop();
  55347. if (lastParticle !== particle) {
  55348. lastParticle.copyTo(particle);
  55349. }
  55350. _this._stockParticles.push(lastParticle);
  55351. };
  55352. this._createParticle = function () {
  55353. var particle;
  55354. if (_this._stockParticles.length !== 0) {
  55355. particle = _this._stockParticles.pop();
  55356. particle.age = 0;
  55357. particle.cellIndex = _this.startSpriteCellID;
  55358. }
  55359. else {
  55360. particle = new BABYLON.Particle(_this);
  55361. }
  55362. return particle;
  55363. };
  55364. this._emitFromParticle = function (particle) {
  55365. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55366. return;
  55367. }
  55368. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55369. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55370. subSystem._rootParticleSystem = _this;
  55371. _this.activeSubSystems.push(subSystem);
  55372. subSystem.start();
  55373. };
  55374. this._appendParticleVertexes = null;
  55375. this.id = name;
  55376. this.name = name;
  55377. this._capacity = capacity;
  55378. this._epsilon = epsilon;
  55379. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55380. if (isAnimationSheetEnabled) {
  55381. this._vertexBufferSize = 12;
  55382. }
  55383. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55384. this._customEffect = customEffect;
  55385. scene.particleSystems.push(this);
  55386. this._createIndexBuffer();
  55387. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55388. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55389. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55390. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55391. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55392. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55393. if (this._isAnimationSheetEnabled) {
  55394. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55395. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55396. }
  55397. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55398. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55399. this._vertexBuffers["options"] = options;
  55400. // Default emitter type
  55401. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55402. this.updateFunction = function (particles) {
  55403. for (var index = 0; index < particles.length; index++) {
  55404. var particle = particles[index];
  55405. particle.age += _this._scaledUpdateSpeed;
  55406. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55407. _this._emitFromParticle(particle);
  55408. _this.recycleParticle(particle);
  55409. index--;
  55410. continue;
  55411. }
  55412. else {
  55413. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55414. particle.color.addInPlace(_this._scaledColorStep);
  55415. if (particle.color.a < 0)
  55416. particle.color.a = 0;
  55417. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55418. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55419. particle.position.addInPlace(_this._scaledDirection);
  55420. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55421. particle.direction.addInPlace(_this._scaledGravity);
  55422. if (_this._isAnimationSheetEnabled) {
  55423. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55424. }
  55425. }
  55426. }
  55427. };
  55428. }
  55429. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55430. /**
  55431. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55432. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55433. */
  55434. get: function () {
  55435. if (this.particleEmitterType.direction1) {
  55436. return this.particleEmitterType.direction1;
  55437. }
  55438. return BABYLON.Vector3.Zero();
  55439. },
  55440. set: function (value) {
  55441. if (this.particleEmitterType.direction1) {
  55442. this.particleEmitterType.direction1 = value;
  55443. }
  55444. },
  55445. enumerable: true,
  55446. configurable: true
  55447. });
  55448. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55449. /**
  55450. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55451. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55452. */
  55453. get: function () {
  55454. if (this.particleEmitterType.direction2) {
  55455. return this.particleEmitterType.direction2;
  55456. }
  55457. return BABYLON.Vector3.Zero();
  55458. },
  55459. set: function (value) {
  55460. if (this.particleEmitterType.direction2) {
  55461. this.particleEmitterType.direction2 = value;
  55462. }
  55463. },
  55464. enumerable: true,
  55465. configurable: true
  55466. });
  55467. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55468. /**
  55469. * 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.
  55470. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55471. */
  55472. get: function () {
  55473. if (this.particleEmitterType.minEmitBox) {
  55474. return this.particleEmitterType.minEmitBox;
  55475. }
  55476. return BABYLON.Vector3.Zero();
  55477. },
  55478. set: function (value) {
  55479. if (this.particleEmitterType.minEmitBox) {
  55480. this.particleEmitterType.minEmitBox = value;
  55481. }
  55482. },
  55483. enumerable: true,
  55484. configurable: true
  55485. });
  55486. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55487. /**
  55488. * 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.
  55489. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55490. */
  55491. get: function () {
  55492. if (this.particleEmitterType.maxEmitBox) {
  55493. return this.particleEmitterType.maxEmitBox;
  55494. }
  55495. return BABYLON.Vector3.Zero();
  55496. },
  55497. set: function (value) {
  55498. if (this.particleEmitterType.maxEmitBox) {
  55499. this.particleEmitterType.maxEmitBox = value;
  55500. }
  55501. },
  55502. enumerable: true,
  55503. configurable: true
  55504. });
  55505. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55506. /**
  55507. * Sets a callback that will be triggered when the system is disposed.
  55508. */
  55509. set: function (callback) {
  55510. if (this._onDisposeObserver) {
  55511. this.onDisposeObservable.remove(this._onDisposeObserver);
  55512. }
  55513. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55514. },
  55515. enumerable: true,
  55516. configurable: true
  55517. });
  55518. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55519. /**
  55520. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55521. */
  55522. get: function () {
  55523. return this._isAnimationSheetEnabled;
  55524. },
  55525. enumerable: true,
  55526. configurable: true
  55527. });
  55528. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55529. //end of Sub-emitter
  55530. /**
  55531. * Gets the current list of active particles
  55532. */
  55533. get: function () {
  55534. return this._particles;
  55535. },
  55536. enumerable: true,
  55537. configurable: true
  55538. });
  55539. /**
  55540. * Returns the string "ParticleSystem"
  55541. * @returns a string containing the class name
  55542. */
  55543. ParticleSystem.prototype.getClassName = function () {
  55544. return "ParticleSystem";
  55545. };
  55546. ParticleSystem.prototype._createIndexBuffer = function () {
  55547. var indices = [];
  55548. var index = 0;
  55549. for (var count = 0; count < this._capacity; count++) {
  55550. indices.push(index);
  55551. indices.push(index + 1);
  55552. indices.push(index + 2);
  55553. indices.push(index);
  55554. indices.push(index + 2);
  55555. indices.push(index + 3);
  55556. index += 4;
  55557. }
  55558. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55559. };
  55560. /**
  55561. * Gets the maximum number of particles active at the same time.
  55562. * @returns The max number of active particles.
  55563. */
  55564. ParticleSystem.prototype.getCapacity = function () {
  55565. return this._capacity;
  55566. };
  55567. /**
  55568. * Gets Wether there are still active particles in the system.
  55569. * @returns True if it is alive, otherwise false.
  55570. */
  55571. ParticleSystem.prototype.isAlive = function () {
  55572. return this._alive;
  55573. };
  55574. /**
  55575. * Gets Wether the system has been started.
  55576. * @returns True if it has been started, otherwise false.
  55577. */
  55578. ParticleSystem.prototype.isStarted = function () {
  55579. return this._started;
  55580. };
  55581. /**
  55582. * Starts the particle system and begins to emit.
  55583. */
  55584. ParticleSystem.prototype.start = function () {
  55585. this._started = true;
  55586. this._stopped = false;
  55587. this._actualFrame = 0;
  55588. if (this.subEmitters && this.subEmitters.length != 0) {
  55589. this.activeSubSystems = new Array();
  55590. }
  55591. };
  55592. /**
  55593. * Stops the particle system.
  55594. * @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.
  55595. */
  55596. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55597. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55598. this._stopped = true;
  55599. if (stopSubEmitters) {
  55600. this._stopSubEmitters();
  55601. }
  55602. };
  55603. // animation sheet
  55604. /**
  55605. * Remove all active particles
  55606. */
  55607. ParticleSystem.prototype.reset = function () {
  55608. this._stockParticles = [];
  55609. this._particles = [];
  55610. };
  55611. /**
  55612. * @ignore (for internal use only)
  55613. */
  55614. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55615. var offset = index * this._vertexBufferSize;
  55616. this._vertexData[offset] = particle.position.x;
  55617. this._vertexData[offset + 1] = particle.position.y;
  55618. this._vertexData[offset + 2] = particle.position.z;
  55619. this._vertexData[offset + 3] = particle.color.r;
  55620. this._vertexData[offset + 4] = particle.color.g;
  55621. this._vertexData[offset + 5] = particle.color.b;
  55622. this._vertexData[offset + 6] = particle.color.a;
  55623. this._vertexData[offset + 7] = particle.angle;
  55624. this._vertexData[offset + 8] = particle.size;
  55625. this._vertexData[offset + 9] = offsetX;
  55626. this._vertexData[offset + 10] = offsetY;
  55627. };
  55628. /**
  55629. * @ignore (for internal use only)
  55630. */
  55631. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55632. if (offsetX === 0)
  55633. offsetX = this._epsilon;
  55634. else if (offsetX === 1)
  55635. offsetX = 1 - this._epsilon;
  55636. if (offsetY === 0)
  55637. offsetY = this._epsilon;
  55638. else if (offsetY === 1)
  55639. offsetY = 1 - this._epsilon;
  55640. var offset = index * this._vertexBufferSize;
  55641. this._vertexData[offset] = particle.position.x;
  55642. this._vertexData[offset + 1] = particle.position.y;
  55643. this._vertexData[offset + 2] = particle.position.z;
  55644. this._vertexData[offset + 3] = particle.color.r;
  55645. this._vertexData[offset + 4] = particle.color.g;
  55646. this._vertexData[offset + 5] = particle.color.b;
  55647. this._vertexData[offset + 6] = particle.color.a;
  55648. this._vertexData[offset + 7] = particle.angle;
  55649. this._vertexData[offset + 8] = particle.size;
  55650. this._vertexData[offset + 9] = offsetX;
  55651. this._vertexData[offset + 10] = offsetY;
  55652. this._vertexData[offset + 11] = particle.cellIndex;
  55653. };
  55654. ParticleSystem.prototype._stopSubEmitters = function () {
  55655. if (!this.activeSubSystems) {
  55656. return;
  55657. }
  55658. this.activeSubSystems.forEach(function (subSystem) {
  55659. subSystem.stop(true);
  55660. });
  55661. this.activeSubSystems = new Array();
  55662. };
  55663. ParticleSystem.prototype._removeFromRoot = function () {
  55664. if (!this._rootParticleSystem) {
  55665. return;
  55666. }
  55667. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55668. if (index !== -1) {
  55669. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55670. }
  55671. };
  55672. // end of sub system methods
  55673. ParticleSystem.prototype._update = function (newParticles) {
  55674. // Update current
  55675. this._alive = this._particles.length > 0;
  55676. this.updateFunction(this._particles);
  55677. // Add new ones
  55678. var worldMatrix;
  55679. if (this.emitter.position) {
  55680. var emitterMesh = this.emitter;
  55681. worldMatrix = emitterMesh.getWorldMatrix();
  55682. }
  55683. else {
  55684. var emitterPosition = this.emitter;
  55685. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55686. }
  55687. var particle;
  55688. for (var index = 0; index < newParticles; index++) {
  55689. if (this._particles.length === this._capacity) {
  55690. break;
  55691. }
  55692. particle = this._createParticle();
  55693. this._particles.push(particle);
  55694. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  55695. if (this.startPositionFunction) {
  55696. this.startPositionFunction(worldMatrix, particle.position, particle);
  55697. }
  55698. else {
  55699. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55700. }
  55701. if (this.startDirectionFunction) {
  55702. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55703. }
  55704. else {
  55705. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  55706. }
  55707. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  55708. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  55709. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  55710. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  55711. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  55712. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  55713. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55714. }
  55715. };
  55716. ParticleSystem.prototype._getEffect = function () {
  55717. if (this._customEffect) {
  55718. return this._customEffect;
  55719. }
  55720. ;
  55721. var defines = [];
  55722. if (this._scene.clipPlane) {
  55723. defines.push("#define CLIPPLANE");
  55724. }
  55725. if (this._isAnimationSheetEnabled) {
  55726. defines.push("#define ANIMATESHEET");
  55727. }
  55728. // Effect
  55729. var join = defines.join("\n");
  55730. if (this._cachedDefines !== join) {
  55731. this._cachedDefines = join;
  55732. var attributesNamesOrOptions;
  55733. var effectCreationOption;
  55734. if (this._isAnimationSheetEnabled) {
  55735. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  55736. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  55737. }
  55738. else {
  55739. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  55740. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  55741. }
  55742. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  55743. }
  55744. return this._effect;
  55745. };
  55746. /**
  55747. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  55748. */
  55749. ParticleSystem.prototype.animate = function () {
  55750. if (!this._started)
  55751. return;
  55752. var effect = this._getEffect();
  55753. // Check
  55754. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  55755. return;
  55756. if (this._currentRenderId === this._scene.getRenderId()) {
  55757. return;
  55758. }
  55759. this._currentRenderId = this._scene.getRenderId();
  55760. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  55761. // determine the number of particles we need to create
  55762. var newParticles;
  55763. if (this.manualEmitCount > -1) {
  55764. newParticles = this.manualEmitCount;
  55765. this._newPartsExcess = 0;
  55766. this.manualEmitCount = 0;
  55767. }
  55768. else {
  55769. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  55770. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  55771. }
  55772. if (this._newPartsExcess > 1.0) {
  55773. newParticles += this._newPartsExcess >> 0;
  55774. this._newPartsExcess -= this._newPartsExcess >> 0;
  55775. }
  55776. this._alive = false;
  55777. if (!this._stopped) {
  55778. this._actualFrame += this._scaledUpdateSpeed;
  55779. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  55780. this.stop();
  55781. }
  55782. else {
  55783. newParticles = 0;
  55784. }
  55785. this._update(newParticles);
  55786. // Stopped?
  55787. if (this._stopped) {
  55788. if (!this._alive) {
  55789. this._started = false;
  55790. if (this.onAnimationEnd) {
  55791. this.onAnimationEnd();
  55792. }
  55793. if (this.disposeOnStop) {
  55794. this._scene._toBeDisposed.push(this);
  55795. }
  55796. }
  55797. }
  55798. // Animation sheet
  55799. if (this._isAnimationSheetEnabled) {
  55800. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  55801. }
  55802. else {
  55803. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  55804. }
  55805. // Update VBO
  55806. var offset = 0;
  55807. for (var index = 0; index < this._particles.length; index++) {
  55808. var particle = this._particles[index];
  55809. this._appendParticleVertexes(offset, particle);
  55810. offset += 4;
  55811. }
  55812. if (this._vertexBuffer) {
  55813. this._vertexBuffer.update(this._vertexData);
  55814. }
  55815. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  55816. this.stop();
  55817. }
  55818. };
  55819. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  55820. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  55821. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  55822. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  55823. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  55824. };
  55825. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  55826. this._appendParticleVertex(offset++, particle, 0, 0);
  55827. this._appendParticleVertex(offset++, particle, 1, 0);
  55828. this._appendParticleVertex(offset++, particle, 1, 1);
  55829. this._appendParticleVertex(offset++, particle, 0, 1);
  55830. };
  55831. /**
  55832. * Rebuilds the particle system.
  55833. */
  55834. ParticleSystem.prototype.rebuild = function () {
  55835. this._createIndexBuffer();
  55836. if (this._vertexBuffer) {
  55837. this._vertexBuffer._rebuild();
  55838. }
  55839. };
  55840. /**
  55841. * Is this system ready to be used/rendered
  55842. * @return true if the system is ready
  55843. */
  55844. ParticleSystem.prototype.isReady = function () {
  55845. var effect = this._getEffect();
  55846. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  55847. return false;
  55848. }
  55849. return true;
  55850. };
  55851. /**
  55852. * Renders the particle system in its current state.
  55853. * @returns the current number of particles
  55854. */
  55855. ParticleSystem.prototype.render = function () {
  55856. var effect = this._getEffect();
  55857. // Check
  55858. if (!this.isReady() || !this._particles.length) {
  55859. return 0;
  55860. }
  55861. var engine = this._scene.getEngine();
  55862. // Render
  55863. engine.enableEffect(effect);
  55864. engine.setState(false);
  55865. var viewMatrix = this._scene.getViewMatrix();
  55866. effect.setTexture("diffuseSampler", this.particleTexture);
  55867. effect.setMatrix("view", viewMatrix);
  55868. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  55869. if (this._isAnimationSheetEnabled && this.particleTexture) {
  55870. var baseSize = this.particleTexture.getBaseSize();
  55871. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  55872. }
  55873. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  55874. if (this._scene.clipPlane) {
  55875. var clipPlane = this._scene.clipPlane;
  55876. var invView = viewMatrix.clone();
  55877. invView.invert();
  55878. effect.setMatrix("invView", invView);
  55879. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  55880. }
  55881. // VBOs
  55882. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  55883. // Draw order
  55884. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  55885. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  55886. }
  55887. else {
  55888. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  55889. }
  55890. if (this.forceDepthWrite) {
  55891. engine.setDepthWrite(true);
  55892. }
  55893. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  55894. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  55895. return this._particles.length;
  55896. };
  55897. /**
  55898. * Disposes the particle system and free the associated resources
  55899. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  55900. */
  55901. ParticleSystem.prototype.dispose = function (disposeTexture) {
  55902. if (disposeTexture === void 0) { disposeTexture = true; }
  55903. if (this._vertexBuffer) {
  55904. this._vertexBuffer.dispose();
  55905. this._vertexBuffer = null;
  55906. }
  55907. if (this._indexBuffer) {
  55908. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  55909. this._indexBuffer = null;
  55910. }
  55911. if (disposeTexture && this.particleTexture) {
  55912. this.particleTexture.dispose();
  55913. this.particleTexture = null;
  55914. }
  55915. this._removeFromRoot();
  55916. // Remove from scene
  55917. var index = this._scene.particleSystems.indexOf(this);
  55918. if (index > -1) {
  55919. this._scene.particleSystems.splice(index, 1);
  55920. }
  55921. // Callback
  55922. this.onDisposeObservable.notifyObservers(this);
  55923. this.onDisposeObservable.clear();
  55924. };
  55925. /**
  55926. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  55927. * @param radius The radius of the sphere to emit from
  55928. * @returns the emitter
  55929. */
  55930. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  55931. if (radius === void 0) { radius = 1; }
  55932. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  55933. this.particleEmitterType = particleEmitter;
  55934. return particleEmitter;
  55935. };
  55936. /**
  55937. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  55938. * @param radius The radius of the sphere to emit from
  55939. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  55940. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  55941. * @returns the emitter
  55942. */
  55943. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  55944. if (radius === void 0) { radius = 1; }
  55945. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  55946. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  55947. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  55948. this.particleEmitterType = particleEmitter;
  55949. return particleEmitter;
  55950. };
  55951. /**
  55952. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  55953. * @param radius The radius of the cone to emit from
  55954. * @param angle The base angle of the cone
  55955. * @returns the emitter
  55956. */
  55957. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  55958. if (radius === void 0) { radius = 1; }
  55959. if (angle === void 0) { angle = Math.PI / 4; }
  55960. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  55961. this.particleEmitterType = particleEmitter;
  55962. return particleEmitter;
  55963. };
  55964. // 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.
  55965. /**
  55966. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  55967. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  55968. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  55969. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55970. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  55971. * @returns the emitter
  55972. */
  55973. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  55974. var particleEmitter = new BABYLON.BoxParticleEmitter();
  55975. this.particleEmitterType = particleEmitter;
  55976. this.direction1 = direction1;
  55977. this.direction2 = direction2;
  55978. this.minEmitBox = minEmitBox;
  55979. this.maxEmitBox = maxEmitBox;
  55980. return particleEmitter;
  55981. };
  55982. // Clone
  55983. /**
  55984. * Clones the particle system.
  55985. * @param name The name of the cloned object
  55986. * @param newEmitter The new emitter to use
  55987. * @returns the cloned particle system
  55988. */
  55989. ParticleSystem.prototype.clone = function (name, newEmitter) {
  55990. var custom = null;
  55991. var program = null;
  55992. if (this.customShader != null) {
  55993. program = this.customShader;
  55994. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  55995. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  55996. }
  55997. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  55998. result.customShader = program;
  55999. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56000. if (newEmitter === undefined) {
  56001. newEmitter = this.emitter;
  56002. }
  56003. result.emitter = newEmitter;
  56004. if (this.particleTexture) {
  56005. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56006. }
  56007. if (!this.preventAutoStart) {
  56008. result.start();
  56009. }
  56010. return result;
  56011. };
  56012. /**
  56013. * Serializes the particle system to a JSON object.
  56014. * @returns the JSON object
  56015. */
  56016. ParticleSystem.prototype.serialize = function () {
  56017. var serializationObject = {};
  56018. serializationObject.name = this.name;
  56019. serializationObject.id = this.id;
  56020. // Emitter
  56021. if (this.emitter.position) {
  56022. var emitterMesh = this.emitter;
  56023. serializationObject.emitterId = emitterMesh.id;
  56024. }
  56025. else {
  56026. var emitterPosition = this.emitter;
  56027. serializationObject.emitter = emitterPosition.asArray();
  56028. }
  56029. serializationObject.capacity = this.getCapacity();
  56030. if (this.particleTexture) {
  56031. serializationObject.textureName = this.particleTexture.name;
  56032. }
  56033. // Animations
  56034. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56035. // Particle system
  56036. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56037. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56038. serializationObject.minSize = this.minSize;
  56039. serializationObject.maxSize = this.maxSize;
  56040. serializationObject.minEmitPower = this.minEmitPower;
  56041. serializationObject.maxEmitPower = this.maxEmitPower;
  56042. serializationObject.minLifeTime = this.minLifeTime;
  56043. serializationObject.maxLifeTime = this.maxLifeTime;
  56044. serializationObject.emitRate = this.emitRate;
  56045. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56046. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56047. serializationObject.gravity = this.gravity.asArray();
  56048. serializationObject.direction1 = this.direction1.asArray();
  56049. serializationObject.direction2 = this.direction2.asArray();
  56050. serializationObject.color1 = this.color1.asArray();
  56051. serializationObject.color2 = this.color2.asArray();
  56052. serializationObject.colorDead = this.colorDead.asArray();
  56053. serializationObject.updateSpeed = this.updateSpeed;
  56054. serializationObject.targetStopDuration = this.targetStopDuration;
  56055. serializationObject.textureMask = this.textureMask.asArray();
  56056. serializationObject.blendMode = this.blendMode;
  56057. serializationObject.customShader = this.customShader;
  56058. serializationObject.preventAutoStart = this.preventAutoStart;
  56059. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56060. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56061. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56062. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56063. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56064. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56065. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56066. // Emitter
  56067. if (this.particleEmitterType) {
  56068. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56069. }
  56070. return serializationObject;
  56071. };
  56072. /**
  56073. * Parses a JSON object to create a particle system.
  56074. * @param parsedParticleSystem The JSON object to parse
  56075. * @param scene The scene to create the particle system in
  56076. * @param rootUrl The root url to use to load external dependencies like texture
  56077. * @returns the Parsed particle system
  56078. */
  56079. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56080. var name = parsedParticleSystem.name;
  56081. var custom = null;
  56082. var program = null;
  56083. if (parsedParticleSystem.customShader) {
  56084. program = parsedParticleSystem.customShader;
  56085. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56086. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56087. }
  56088. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56089. particleSystem.customShader = program;
  56090. if (parsedParticleSystem.id) {
  56091. particleSystem.id = parsedParticleSystem.id;
  56092. }
  56093. // Auto start
  56094. if (parsedParticleSystem.preventAutoStart) {
  56095. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56096. }
  56097. // Texture
  56098. if (parsedParticleSystem.textureName) {
  56099. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56100. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56101. }
  56102. // Emitter
  56103. if (parsedParticleSystem.emitterId) {
  56104. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56105. }
  56106. else {
  56107. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56108. }
  56109. // Animations
  56110. if (parsedParticleSystem.animations) {
  56111. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56112. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56113. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56114. }
  56115. }
  56116. if (parsedParticleSystem.autoAnimate) {
  56117. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56118. }
  56119. // Particle system
  56120. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56121. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56122. particleSystem.minSize = parsedParticleSystem.minSize;
  56123. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56124. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56125. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56126. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56127. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56128. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56129. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56130. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56131. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56132. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56133. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56134. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56135. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56136. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56137. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56138. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56139. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56140. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56141. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56142. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56143. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56144. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56145. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56146. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56147. if (!particleSystem.preventAutoStart) {
  56148. particleSystem.start();
  56149. }
  56150. return particleSystem;
  56151. };
  56152. /**
  56153. * Source color is added to the destination color without alpha affecting the result.
  56154. */
  56155. ParticleSystem.BLENDMODE_ONEONE = 0;
  56156. /**
  56157. * Blend current color and particle color using particle’s alpha.
  56158. */
  56159. ParticleSystem.BLENDMODE_STANDARD = 1;
  56160. return ParticleSystem;
  56161. }());
  56162. BABYLON.ParticleSystem = ParticleSystem;
  56163. })(BABYLON || (BABYLON = {}));
  56164. //# sourceMappingURL=babylon.particleSystem.js.map
  56165. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56166. var BABYLON;
  56167. (function (BABYLON) {
  56168. /**
  56169. * Particle emitter emitting particles from the inside of a box.
  56170. * It emits the particles randomly between 2 given directions.
  56171. */
  56172. var BoxParticleEmitter = /** @class */ (function () {
  56173. /**
  56174. * Creates a new instance BoxParticleEmitter
  56175. */
  56176. function BoxParticleEmitter() {
  56177. /**
  56178. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56179. */
  56180. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56181. /**
  56182. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56183. */
  56184. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56185. /**
  56186. * 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.
  56187. */
  56188. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56189. /**
  56190. * 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.
  56191. */
  56192. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56193. }
  56194. /**
  56195. * Called by the particle System when the direction is computed for the created particle.
  56196. * @param emitPower is the power of the particle (speed)
  56197. * @param worldMatrix is the world matrix of the particle system
  56198. * @param directionToUpdate is the direction vector to update with the result
  56199. * @param particle is the particle we are computed the direction for
  56200. */
  56201. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56202. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56203. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56204. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56205. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56206. };
  56207. /**
  56208. * Called by the particle System when the position is computed for the created particle.
  56209. * @param worldMatrix is the world matrix of the particle system
  56210. * @param positionToUpdate is the position vector to update with the result
  56211. * @param particle is the particle we are computed the position for
  56212. */
  56213. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56214. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56215. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56216. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56217. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56218. };
  56219. /**
  56220. * Clones the current emitter and returns a copy of it
  56221. * @returns the new emitter
  56222. */
  56223. BoxParticleEmitter.prototype.clone = function () {
  56224. var newOne = new BoxParticleEmitter();
  56225. BABYLON.Tools.DeepCopy(this, newOne);
  56226. return newOne;
  56227. };
  56228. /**
  56229. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56230. * @param effect defines the update shader
  56231. */
  56232. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56233. effect.setVector3("direction1", this.direction1);
  56234. effect.setVector3("direction2", this.direction2);
  56235. effect.setVector3("minEmitBox", this.minEmitBox);
  56236. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56237. };
  56238. /**
  56239. * Returns a string to use to update the GPU particles update shader
  56240. * @returns a string containng the defines string
  56241. */
  56242. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56243. return "#define BOXEMITTER";
  56244. };
  56245. /**
  56246. * Returns the string "BoxEmitter"
  56247. * @returns a string containing the class name
  56248. */
  56249. BoxParticleEmitter.prototype.getClassName = function () {
  56250. return "BoxEmitter";
  56251. };
  56252. /**
  56253. * Serializes the particle system to a JSON object.
  56254. * @returns the JSON object
  56255. */
  56256. BoxParticleEmitter.prototype.serialize = function () {
  56257. var serializationObject = {};
  56258. serializationObject.type = this.getClassName();
  56259. serializationObject.direction1 = this.direction1.asArray();
  56260. ;
  56261. serializationObject.direction2 = this.direction2.asArray();
  56262. ;
  56263. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56264. ;
  56265. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56266. ;
  56267. return serializationObject;
  56268. };
  56269. /**
  56270. * Parse properties from a JSON object
  56271. * @param serializationObject defines the JSON object
  56272. */
  56273. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56274. this.direction1.copyFrom(serializationObject.direction1);
  56275. this.direction2.copyFrom(serializationObject.direction2);
  56276. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56277. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56278. };
  56279. return BoxParticleEmitter;
  56280. }());
  56281. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56282. })(BABYLON || (BABYLON = {}));
  56283. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56284. var BABYLON;
  56285. (function (BABYLON) {
  56286. /**
  56287. * Particle emitter emitting particles from the inside of a cone.
  56288. * It emits the particles alongside the cone volume from the base to the particle.
  56289. * The emission direction might be randomized.
  56290. */
  56291. var ConeParticleEmitter = /** @class */ (function () {
  56292. /**
  56293. * Creates a new instance ConeParticleEmitter
  56294. * @param radius the radius of the emission cone (1 by default)
  56295. * @param angles the cone base angle (PI by default)
  56296. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56297. */
  56298. function ConeParticleEmitter(radius,
  56299. /**
  56300. * The radius of the emission cone.
  56301. */
  56302. angle,
  56303. /**
  56304. * The cone base angle.
  56305. */
  56306. directionRandomizer) {
  56307. if (radius === void 0) { radius = 1; }
  56308. if (angle === void 0) { angle = Math.PI; }
  56309. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56310. this.angle = angle;
  56311. this.directionRandomizer = directionRandomizer;
  56312. this.radius = radius;
  56313. }
  56314. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56315. /**
  56316. * Gets the radius of the emission cone.
  56317. */
  56318. get: function () {
  56319. return this._radius;
  56320. },
  56321. /**
  56322. * Sets the radius of the emission cone.
  56323. */
  56324. set: function (value) {
  56325. this._radius = value;
  56326. if (this.angle !== 0) {
  56327. this._height = value / Math.tan(this.angle / 2);
  56328. }
  56329. else {
  56330. this._height = 1;
  56331. }
  56332. },
  56333. enumerable: true,
  56334. configurable: true
  56335. });
  56336. /**
  56337. * Called by the particle System when the direction is computed for the created particle.
  56338. * @param emitPower is the power of the particle (speed)
  56339. * @param worldMatrix is the world matrix of the particle system
  56340. * @param directionToUpdate is the direction vector to update with the result
  56341. * @param particle is the particle we are computed the direction for
  56342. */
  56343. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56344. if (this.angle === 0) {
  56345. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56346. }
  56347. else {
  56348. // measure the direction Vector from the emitter to the particle.
  56349. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56350. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56351. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56352. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56353. direction.x += randX;
  56354. direction.y += randY;
  56355. direction.z += randZ;
  56356. direction.normalize();
  56357. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56358. }
  56359. };
  56360. /**
  56361. * Called by the particle System when the position is computed for the created particle.
  56362. * @param worldMatrix is the world matrix of the particle system
  56363. * @param positionToUpdate is the position vector to update with the result
  56364. * @param particle is the particle we are computed the position for
  56365. */
  56366. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56367. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56368. var h = BABYLON.Scalar.RandomRange(0, 1);
  56369. // Better distribution in a cone at normal angles.
  56370. h = 1 - h * h;
  56371. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56372. radius = radius * h;
  56373. var randX = radius * Math.sin(s);
  56374. var randZ = radius * Math.cos(s);
  56375. var randY = h * this._height;
  56376. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56377. };
  56378. /**
  56379. * Clones the current emitter and returns a copy of it
  56380. * @returns the new emitter
  56381. */
  56382. ConeParticleEmitter.prototype.clone = function () {
  56383. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56384. BABYLON.Tools.DeepCopy(this, newOne);
  56385. return newOne;
  56386. };
  56387. /**
  56388. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56389. * @param effect defines the update shader
  56390. */
  56391. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56392. effect.setFloat("radius", this.radius);
  56393. effect.setFloat("angle", this.angle);
  56394. effect.setFloat("height", this._height);
  56395. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56396. };
  56397. /**
  56398. * Returns a string to use to update the GPU particles update shader
  56399. * @returns a string containng the defines string
  56400. */
  56401. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56402. return "#define CONEEMITTER";
  56403. };
  56404. /**
  56405. * Returns the string "BoxEmitter"
  56406. * @returns a string containing the class name
  56407. */
  56408. ConeParticleEmitter.prototype.getClassName = function () {
  56409. return "ConeEmitter";
  56410. };
  56411. /**
  56412. * Serializes the particle system to a JSON object.
  56413. * @returns the JSON object
  56414. */
  56415. ConeParticleEmitter.prototype.serialize = function () {
  56416. var serializationObject = {};
  56417. serializationObject.type = this.getClassName();
  56418. serializationObject.radius = this.radius;
  56419. serializationObject.angle = this.angle;
  56420. serializationObject.directionRandomizer = this.directionRandomizer;
  56421. return serializationObject;
  56422. };
  56423. /**
  56424. * Parse properties from a JSON object
  56425. * @param serializationObject defines the JSON object
  56426. */
  56427. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56428. this.radius = serializationObject.radius;
  56429. this.angle = serializationObject.angle;
  56430. this.directionRandomizer = serializationObject.directionRandomizer;
  56431. };
  56432. return ConeParticleEmitter;
  56433. }());
  56434. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56435. })(BABYLON || (BABYLON = {}));
  56436. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56437. var BABYLON;
  56438. (function (BABYLON) {
  56439. /**
  56440. * Particle emitter emitting particles from the inside of a sphere.
  56441. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56442. */
  56443. var SphereParticleEmitter = /** @class */ (function () {
  56444. /**
  56445. * Creates a new instance SphereParticleEmitter
  56446. * @param radius the radius of the emission sphere (1 by default)
  56447. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56448. */
  56449. function SphereParticleEmitter(
  56450. /**
  56451. * The radius of the emission sphere.
  56452. */
  56453. radius,
  56454. /**
  56455. * How much to randomize the particle direction [0-1].
  56456. */
  56457. directionRandomizer) {
  56458. if (radius === void 0) { radius = 1; }
  56459. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56460. this.radius = radius;
  56461. this.directionRandomizer = directionRandomizer;
  56462. }
  56463. /**
  56464. * Called by the particle System when the direction is computed for the created particle.
  56465. * @param emitPower is the power of the particle (speed)
  56466. * @param worldMatrix is the world matrix of the particle system
  56467. * @param directionToUpdate is the direction vector to update with the result
  56468. * @param particle is the particle we are computed the direction for
  56469. */
  56470. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56471. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56472. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56473. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56474. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56475. direction.x += randX;
  56476. direction.y += randY;
  56477. direction.z += randZ;
  56478. direction.normalize();
  56479. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56480. };
  56481. /**
  56482. * Called by the particle System when the position is computed for the created particle.
  56483. * @param worldMatrix is the world matrix of the particle system
  56484. * @param positionToUpdate is the position vector to update with the result
  56485. * @param particle is the particle we are computed the position for
  56486. */
  56487. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56488. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56489. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56490. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56491. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56492. var randY = randRadius * Math.cos(theta);
  56493. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56494. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56495. };
  56496. /**
  56497. * Clones the current emitter and returns a copy of it
  56498. * @returns the new emitter
  56499. */
  56500. SphereParticleEmitter.prototype.clone = function () {
  56501. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56502. BABYLON.Tools.DeepCopy(this, newOne);
  56503. return newOne;
  56504. };
  56505. /**
  56506. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56507. * @param effect defines the update shader
  56508. */
  56509. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56510. effect.setFloat("radius", this.radius);
  56511. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56512. };
  56513. /**
  56514. * Returns a string to use to update the GPU particles update shader
  56515. * @returns a string containng the defines string
  56516. */
  56517. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56518. return "#define SPHEREEMITTER";
  56519. };
  56520. /**
  56521. * Returns the string "SphereParticleEmitter"
  56522. * @returns a string containing the class name
  56523. */
  56524. SphereParticleEmitter.prototype.getClassName = function () {
  56525. return "SphereParticleEmitter";
  56526. };
  56527. /**
  56528. * Serializes the particle system to a JSON object.
  56529. * @returns the JSON object
  56530. */
  56531. SphereParticleEmitter.prototype.serialize = function () {
  56532. var serializationObject = {};
  56533. serializationObject.type = this.getClassName();
  56534. serializationObject.radius = this.radius;
  56535. serializationObject.directionRandomizer = this.directionRandomizer;
  56536. return serializationObject;
  56537. };
  56538. /**
  56539. * Parse properties from a JSON object
  56540. * @param serializationObject defines the JSON object
  56541. */
  56542. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56543. this.radius = serializationObject.radius;
  56544. this.directionRandomizer = serializationObject.directionRandomizer;
  56545. };
  56546. return SphereParticleEmitter;
  56547. }());
  56548. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56549. /**
  56550. * Particle emitter emitting particles from the inside of a sphere.
  56551. * It emits the particles randomly between two vectors.
  56552. */
  56553. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56554. __extends(SphereDirectedParticleEmitter, _super);
  56555. /**
  56556. * Creates a new instance SphereDirectedParticleEmitter
  56557. * @param radius the radius of the emission sphere (1 by default)
  56558. * @param direction1 the min limit of the emission direction (up vector by default)
  56559. * @param direction2 the max limit of the emission direction (up vector by default)
  56560. */
  56561. function SphereDirectedParticleEmitter(radius,
  56562. /**
  56563. * The min limit of the emission direction.
  56564. */
  56565. direction1,
  56566. /**
  56567. * The max limit of the emission direction.
  56568. */
  56569. direction2) {
  56570. if (radius === void 0) { radius = 1; }
  56571. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56572. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56573. var _this = _super.call(this, radius) || this;
  56574. _this.direction1 = direction1;
  56575. _this.direction2 = direction2;
  56576. return _this;
  56577. }
  56578. /**
  56579. * Called by the particle System when the direction is computed for the created particle.
  56580. * @param emitPower is the power of the particle (speed)
  56581. * @param worldMatrix is the world matrix of the particle system
  56582. * @param directionToUpdate is the direction vector to update with the result
  56583. * @param particle is the particle we are computed the direction for
  56584. */
  56585. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56586. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56587. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56588. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56589. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56590. };
  56591. /**
  56592. * Clones the current emitter and returns a copy of it
  56593. * @returns the new emitter
  56594. */
  56595. SphereDirectedParticleEmitter.prototype.clone = function () {
  56596. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56597. BABYLON.Tools.DeepCopy(this, newOne);
  56598. return newOne;
  56599. };
  56600. /**
  56601. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56602. * @param effect defines the update shader
  56603. */
  56604. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56605. effect.setFloat("radius", this.radius);
  56606. effect.setVector3("direction1", this.direction1);
  56607. effect.setVector3("direction2", this.direction2);
  56608. };
  56609. /**
  56610. * Returns a string to use to update the GPU particles update shader
  56611. * @returns a string containng the defines string
  56612. */
  56613. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56614. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56615. };
  56616. /**
  56617. * Returns the string "SphereDirectedParticleEmitter"
  56618. * @returns a string containing the class name
  56619. */
  56620. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56621. return "SphereDirectedParticleEmitter";
  56622. };
  56623. /**
  56624. * Serializes the particle system to a JSON object.
  56625. * @returns the JSON object
  56626. */
  56627. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56628. var serializationObject = _super.prototype.serialize.call(this);
  56629. ;
  56630. serializationObject.direction1 = this.direction1.asArray();
  56631. ;
  56632. serializationObject.direction2 = this.direction2.asArray();
  56633. ;
  56634. return serializationObject;
  56635. };
  56636. /**
  56637. * Parse properties from a JSON object
  56638. * @param serializationObject defines the JSON object
  56639. */
  56640. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56641. _super.prototype.parse.call(this, serializationObject);
  56642. this.direction1.copyFrom(serializationObject.direction1);
  56643. this.direction2.copyFrom(serializationObject.direction2);
  56644. };
  56645. return SphereDirectedParticleEmitter;
  56646. }(SphereParticleEmitter));
  56647. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  56648. })(BABYLON || (BABYLON = {}));
  56649. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  56650. var __assign = (this && this.__assign) || Object.assign || function(t) {
  56651. for (var s, i = 1, n = arguments.length; i < n; i++) {
  56652. s = arguments[i];
  56653. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  56654. t[p] = s[p];
  56655. }
  56656. return t;
  56657. };
  56658. var BABYLON;
  56659. (function (BABYLON) {
  56660. /**
  56661. * This represents a GPU particle system in Babylon
  56662. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  56663. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  56664. */
  56665. var GPUParticleSystem = /** @class */ (function () {
  56666. /**
  56667. * Instantiates a GPU particle system.
  56668. * 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.
  56669. * @param name The name of the particle system
  56670. * @param capacity The max number of particles alive at the same time
  56671. * @param scene The scene the particle system belongs to
  56672. */
  56673. function GPUParticleSystem(name, options, scene) {
  56674. /**
  56675. * The emitter represents the Mesh or position we are attaching the particle system to.
  56676. */
  56677. this.emitter = null;
  56678. /**
  56679. * The rendering group used by the Particle system to chose when to render.
  56680. */
  56681. this.renderingGroupId = 0;
  56682. /**
  56683. * The layer mask we are rendering the particles through.
  56684. */
  56685. this.layerMask = 0x0FFFFFFF;
  56686. this._targetIndex = 0;
  56687. this._currentRenderId = -1;
  56688. this._started = false;
  56689. this._stopped = false;
  56690. this._timeDelta = 0;
  56691. this._attributesStrideSize = 14;
  56692. this._actualFrame = 0;
  56693. /**
  56694. * List of animations used by the particle system.
  56695. */
  56696. this.animations = [];
  56697. /**
  56698. * An event triggered when the system is disposed.
  56699. */
  56700. this.onDisposeObservable = new BABYLON.Observable();
  56701. /**
  56702. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  56703. */
  56704. this.updateSpeed = 0.01;
  56705. /**
  56706. * The amount of time the particle system is running (depends of the overall update speed).
  56707. */
  56708. this.targetStopDuration = 0;
  56709. /**
  56710. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  56711. */
  56712. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  56713. /**
  56714. * Minimum life time of emitting particles.
  56715. */
  56716. this.minLifeTime = 1;
  56717. /**
  56718. * Maximum life time of emitting particles.
  56719. */
  56720. this.maxLifeTime = 1;
  56721. /**
  56722. * Minimum Size of emitting particles.
  56723. */
  56724. this.minSize = 1;
  56725. /**
  56726. * Maximum Size of emitting particles.
  56727. */
  56728. this.maxSize = 1;
  56729. /**
  56730. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56731. */
  56732. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56733. /**
  56734. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  56735. */
  56736. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56737. /**
  56738. * Color the particle will have at the end of its lifetime.
  56739. */
  56740. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  56741. /**
  56742. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  56743. */
  56744. this.emitRate = 100;
  56745. /**
  56746. * You can use gravity if you want to give an orientation to your particles.
  56747. */
  56748. this.gravity = BABYLON.Vector3.Zero();
  56749. /**
  56750. * Minimum power of emitting particles.
  56751. */
  56752. this.minEmitPower = 1;
  56753. /**
  56754. * Maximum power of emitting particles.
  56755. */
  56756. this.maxEmitPower = 1;
  56757. /**
  56758. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  56759. * to override the particles.
  56760. */
  56761. this.forceDepthWrite = false;
  56762. this.id = name;
  56763. this.name = name;
  56764. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56765. this._engine = this._scene.getEngine();
  56766. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  56767. this._capacity = fullOptions.capacity;
  56768. this._activeCount = fullOptions.capacity;
  56769. this._currentActiveCount = 0;
  56770. this._scene.particleSystems.push(this);
  56771. this._updateEffectOptions = {
  56772. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  56773. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  56774. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  56775. uniformBuffersNames: [],
  56776. samplers: ["randomSampler"],
  56777. defines: "",
  56778. fallbacks: null,
  56779. onCompiled: null,
  56780. onError: null,
  56781. indexParameters: null,
  56782. maxSimultaneousLights: 0,
  56783. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  56784. };
  56785. // Random data
  56786. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  56787. var d = [];
  56788. for (var i = 0; i < maxTextureSize; ++i) {
  56789. d.push(Math.random());
  56790. d.push(Math.random());
  56791. d.push(Math.random());
  56792. d.push(Math.random());
  56793. }
  56794. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  56795. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  56796. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  56797. this._randomTextureSize = maxTextureSize;
  56798. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56799. }
  56800. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  56801. /**
  56802. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  56803. */
  56804. get: function () {
  56805. if (!BABYLON.Engine.LastCreatedEngine) {
  56806. return false;
  56807. }
  56808. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  56809. },
  56810. enumerable: true,
  56811. configurable: true
  56812. });
  56813. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  56814. /**
  56815. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56816. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56817. */
  56818. get: function () {
  56819. if (this.particleEmitterType.direction1) {
  56820. return this.particleEmitterType.direction1;
  56821. }
  56822. return BABYLON.Vector3.Zero();
  56823. },
  56824. set: function (value) {
  56825. if (this.particleEmitterType.direction1) {
  56826. this.particleEmitterType.direction1 = value;
  56827. }
  56828. },
  56829. enumerable: true,
  56830. configurable: true
  56831. });
  56832. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  56833. /**
  56834. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56835. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56836. */
  56837. get: function () {
  56838. if (this.particleEmitterType.direction2) {
  56839. return this.particleEmitterType.direction2;
  56840. }
  56841. return BABYLON.Vector3.Zero();
  56842. },
  56843. set: function (value) {
  56844. if (this.particleEmitterType.direction2) {
  56845. this.particleEmitterType.direction2 = value;
  56846. }
  56847. },
  56848. enumerable: true,
  56849. configurable: true
  56850. });
  56851. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  56852. /**
  56853. * 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.
  56854. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56855. */
  56856. get: function () {
  56857. if (this.particleEmitterType.minEmitBox) {
  56858. return this.particleEmitterType.minEmitBox;
  56859. }
  56860. return BABYLON.Vector3.Zero();
  56861. },
  56862. set: function (value) {
  56863. if (this.particleEmitterType.minEmitBox) {
  56864. this.particleEmitterType.minEmitBox = value;
  56865. }
  56866. },
  56867. enumerable: true,
  56868. configurable: true
  56869. });
  56870. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  56871. /**
  56872. * 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.
  56873. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56874. */
  56875. get: function () {
  56876. if (this.particleEmitterType.maxEmitBox) {
  56877. return this.particleEmitterType.maxEmitBox;
  56878. }
  56879. return BABYLON.Vector3.Zero();
  56880. },
  56881. set: function (value) {
  56882. if (this.particleEmitterType.maxEmitBox) {
  56883. this.particleEmitterType.maxEmitBox = value;
  56884. }
  56885. },
  56886. enumerable: true,
  56887. configurable: true
  56888. });
  56889. /**
  56890. * Gets the maximum number of particles active at the same time.
  56891. * @returns The max number of active particles.
  56892. */
  56893. GPUParticleSystem.prototype.getCapacity = function () {
  56894. return this._capacity;
  56895. };
  56896. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  56897. /**
  56898. * Gets or set the number of active particles
  56899. */
  56900. get: function () {
  56901. return this._activeCount;
  56902. },
  56903. set: function (value) {
  56904. this._activeCount = Math.min(value, this._capacity);
  56905. },
  56906. enumerable: true,
  56907. configurable: true
  56908. });
  56909. /**
  56910. * Is this system ready to be used/rendered
  56911. * @return true if the system is ready
  56912. */
  56913. GPUParticleSystem.prototype.isReady = function () {
  56914. if (!this._updateEffect) {
  56915. this._recreateUpdateEffect();
  56916. this._recreateRenderEffect();
  56917. return false;
  56918. }
  56919. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56920. return false;
  56921. }
  56922. return true;
  56923. };
  56924. /**
  56925. * Gets Wether the system has been started.
  56926. * @returns True if it has been started, otherwise false.
  56927. */
  56928. GPUParticleSystem.prototype.isStarted = function () {
  56929. return this._started;
  56930. };
  56931. /**
  56932. * Starts the particle system and begins to emit.
  56933. */
  56934. GPUParticleSystem.prototype.start = function () {
  56935. this._started = true;
  56936. this._stopped = false;
  56937. };
  56938. /**
  56939. * Stops the particle system.
  56940. */
  56941. GPUParticleSystem.prototype.stop = function () {
  56942. this._stopped = true;
  56943. };
  56944. /**
  56945. * Remove all active particles
  56946. */
  56947. GPUParticleSystem.prototype.reset = function () {
  56948. this._releaseBuffers();
  56949. this._releaseVAOs();
  56950. this._currentActiveCount = 0;
  56951. this._targetIndex = 0;
  56952. };
  56953. /**
  56954. * Returns the string "GPUParticleSystem"
  56955. * @returns a string containing the class name
  56956. */
  56957. GPUParticleSystem.prototype.getClassName = function () {
  56958. return "GPUParticleSystem";
  56959. };
  56960. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  56961. var updateVertexBuffers = {};
  56962. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  56963. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  56964. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  56965. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  56966. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  56967. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  56968. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  56969. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  56970. this._engine.bindArrayBuffer(null);
  56971. return vao;
  56972. };
  56973. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  56974. var renderVertexBuffers = {};
  56975. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  56976. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  56977. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  56978. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  56979. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  56980. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  56981. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  56982. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  56983. this._engine.bindArrayBuffer(null);
  56984. return vao;
  56985. };
  56986. GPUParticleSystem.prototype._initialize = function (force) {
  56987. if (force === void 0) { force = false; }
  56988. if (this._buffer0 && !force) {
  56989. return;
  56990. }
  56991. var engine = this._scene.getEngine();
  56992. var data = new Array();
  56993. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  56994. // position
  56995. data.push(0.0);
  56996. data.push(0.0);
  56997. data.push(0.0);
  56998. // Age and life
  56999. data.push(0.0); // create the particle as a dead one to create a new one at start
  57000. data.push(0.0);
  57001. // Seed
  57002. data.push(Math.random());
  57003. // Size
  57004. data.push(0.0);
  57005. // color
  57006. data.push(0.0);
  57007. data.push(0.0);
  57008. data.push(0.0);
  57009. data.push(0.0);
  57010. // direction
  57011. data.push(0.0);
  57012. data.push(0.0);
  57013. data.push(0.0);
  57014. }
  57015. // Sprite data
  57016. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57017. -0.5, 0.5, 0, 1,
  57018. -0.5, -0.5, 0, 0,
  57019. 0.5, -0.5, 1, 0]);
  57020. // Buffers
  57021. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57022. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57023. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57024. // Update VAO
  57025. this._updateVAO = [];
  57026. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57027. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57028. // Render VAO
  57029. this._renderVAO = [];
  57030. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57031. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57032. // Links
  57033. this._sourceBuffer = this._buffer0;
  57034. this._targetBuffer = this._buffer1;
  57035. };
  57036. /** @ignore */
  57037. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57038. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57039. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57040. return;
  57041. }
  57042. this._updateEffectOptions.defines = defines;
  57043. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57044. };
  57045. /** @ignore */
  57046. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57047. var defines = "";
  57048. if (this._scene.clipPlane) {
  57049. defines = "\n#define CLIPPLANE";
  57050. }
  57051. if (this._renderEffect && this._renderEffect.defines === defines) {
  57052. return;
  57053. }
  57054. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57055. };
  57056. /**
  57057. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57058. */
  57059. GPUParticleSystem.prototype.animate = function () {
  57060. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57061. this._actualFrame += this._timeDelta;
  57062. if (!this._stopped) {
  57063. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57064. this.stop();
  57065. }
  57066. }
  57067. };
  57068. /**
  57069. * Renders the particle system in its current state.
  57070. * @returns the current number of particles
  57071. */
  57072. GPUParticleSystem.prototype.render = function () {
  57073. if (!this._started) {
  57074. return 0;
  57075. }
  57076. this._recreateUpdateEffect();
  57077. this._recreateRenderEffect();
  57078. if (!this.isReady()) {
  57079. return 0;
  57080. }
  57081. if (this._currentRenderId === this._scene.getRenderId()) {
  57082. return 0;
  57083. }
  57084. this._currentRenderId = this._scene.getRenderId();
  57085. // Get everything ready to render
  57086. this._initialize();
  57087. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57088. // Enable update effect
  57089. this._engine.enableEffect(this._updateEffect);
  57090. this._engine.setState(false);
  57091. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57092. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57093. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57094. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57095. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57096. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57097. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57098. this._updateEffect.setDirectColor4("color1", this.color1);
  57099. this._updateEffect.setDirectColor4("color2", this.color2);
  57100. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57101. this._updateEffect.setVector3("gravity", this.gravity);
  57102. if (this.particleEmitterType) {
  57103. this.particleEmitterType.applyToShader(this._updateEffect);
  57104. }
  57105. var emitterWM;
  57106. if (this.emitter.position) {
  57107. var emitterMesh = this.emitter;
  57108. emitterWM = emitterMesh.getWorldMatrix();
  57109. }
  57110. else {
  57111. var emitterPosition = this.emitter;
  57112. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57113. }
  57114. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57115. // Bind source VAO
  57116. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57117. // Update
  57118. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57119. this._engine.setRasterizerState(false);
  57120. this._engine.beginTransformFeedback();
  57121. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57122. this._engine.endTransformFeedback();
  57123. this._engine.setRasterizerState(true);
  57124. this._engine.bindTransformFeedbackBuffer(null);
  57125. // Enable render effect
  57126. this._engine.enableEffect(this._renderEffect);
  57127. var viewMatrix = this._scene.getViewMatrix();
  57128. this._renderEffect.setMatrix("view", viewMatrix);
  57129. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57130. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57131. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57132. if (this._scene.clipPlane) {
  57133. var clipPlane = this._scene.clipPlane;
  57134. var invView = viewMatrix.clone();
  57135. invView.invert();
  57136. this._renderEffect.setMatrix("invView", invView);
  57137. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57138. }
  57139. // Draw order
  57140. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57141. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57142. }
  57143. else {
  57144. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57145. }
  57146. if (this.forceDepthWrite) {
  57147. this._engine.setDepthWrite(true);
  57148. }
  57149. // Bind source VAO
  57150. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57151. // Render
  57152. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57153. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57154. // Switch VAOs
  57155. this._targetIndex++;
  57156. if (this._targetIndex === 2) {
  57157. this._targetIndex = 0;
  57158. }
  57159. // Switch buffers
  57160. var tmpBuffer = this._sourceBuffer;
  57161. this._sourceBuffer = this._targetBuffer;
  57162. this._targetBuffer = tmpBuffer;
  57163. return this._currentActiveCount;
  57164. };
  57165. /**
  57166. * Rebuilds the particle system
  57167. */
  57168. GPUParticleSystem.prototype.rebuild = function () {
  57169. this._initialize(true);
  57170. };
  57171. GPUParticleSystem.prototype._releaseBuffers = function () {
  57172. if (this._buffer0) {
  57173. this._buffer0.dispose();
  57174. this._buffer0 = null;
  57175. }
  57176. if (this._buffer1) {
  57177. this._buffer1.dispose();
  57178. this._buffer1 = null;
  57179. }
  57180. if (this._spriteBuffer) {
  57181. this._spriteBuffer.dispose();
  57182. this._spriteBuffer = null;
  57183. }
  57184. };
  57185. GPUParticleSystem.prototype._releaseVAOs = function () {
  57186. if (!this._updateVAO) {
  57187. return;
  57188. }
  57189. for (var index = 0; index < this._updateVAO.length; index++) {
  57190. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57191. }
  57192. this._updateVAO = [];
  57193. for (var index = 0; index < this._renderVAO.length; index++) {
  57194. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57195. }
  57196. this._renderVAO = [];
  57197. };
  57198. /**
  57199. * Disposes the particle system and free the associated resources
  57200. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57201. */
  57202. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57203. if (disposeTexture === void 0) { disposeTexture = true; }
  57204. var index = this._scene.particleSystems.indexOf(this);
  57205. if (index > -1) {
  57206. this._scene.particleSystems.splice(index, 1);
  57207. }
  57208. this._releaseBuffers();
  57209. this._releaseVAOs();
  57210. if (this._randomTexture) {
  57211. this._randomTexture.dispose();
  57212. this._randomTexture = null;
  57213. }
  57214. if (disposeTexture && this.particleTexture) {
  57215. this.particleTexture.dispose();
  57216. this.particleTexture = null;
  57217. }
  57218. // Callback
  57219. this.onDisposeObservable.notifyObservers(this);
  57220. this.onDisposeObservable.clear();
  57221. };
  57222. /**
  57223. * Clones the particle system.
  57224. * @param name The name of the cloned object
  57225. * @param newEmitter The new emitter to use
  57226. * @returns the cloned particle system
  57227. */
  57228. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57229. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57230. BABYLON.Tools.DeepCopy(this, result);
  57231. if (newEmitter === undefined) {
  57232. newEmitter = this.emitter;
  57233. }
  57234. result.emitter = newEmitter;
  57235. if (this.particleTexture) {
  57236. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57237. }
  57238. return result;
  57239. };
  57240. /**
  57241. * Serializes the particle system to a JSON object.
  57242. * @returns the JSON object
  57243. */
  57244. GPUParticleSystem.prototype.serialize = function () {
  57245. var serializationObject = {};
  57246. serializationObject.name = this.name;
  57247. serializationObject.id = this.id;
  57248. // Emitter
  57249. if (this.emitter.position) {
  57250. var emitterMesh = this.emitter;
  57251. serializationObject.emitterId = emitterMesh.id;
  57252. }
  57253. else {
  57254. var emitterPosition = this.emitter;
  57255. serializationObject.emitter = emitterPosition.asArray();
  57256. }
  57257. serializationObject.capacity = this.getCapacity();
  57258. if (this.particleTexture) {
  57259. serializationObject.textureName = this.particleTexture.name;
  57260. }
  57261. // Animations
  57262. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57263. // Particle system
  57264. serializationObject.activeParticleCount = this.activeParticleCount;
  57265. serializationObject.randomTextureSize = this._randomTextureSize;
  57266. serializationObject.minSize = this.minSize;
  57267. serializationObject.maxSize = this.maxSize;
  57268. serializationObject.minEmitPower = this.minEmitPower;
  57269. serializationObject.maxEmitPower = this.maxEmitPower;
  57270. serializationObject.minLifeTime = this.minLifeTime;
  57271. serializationObject.maxLifeTime = this.maxLifeTime;
  57272. serializationObject.emitRate = this.emitRate;
  57273. serializationObject.gravity = this.gravity.asArray();
  57274. serializationObject.color1 = this.color1.asArray();
  57275. serializationObject.color2 = this.color2.asArray();
  57276. serializationObject.colorDead = this.colorDead.asArray();
  57277. serializationObject.updateSpeed = this.updateSpeed;
  57278. serializationObject.targetStopDuration = this.targetStopDuration;
  57279. serializationObject.blendMode = this.blendMode;
  57280. // Emitter
  57281. if (this.particleEmitterType) {
  57282. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57283. }
  57284. return serializationObject;
  57285. };
  57286. /**
  57287. * Parses a JSON object to create a GPU particle system.
  57288. * @param parsedParticleSystem The JSON object to parse
  57289. * @param scene The scene to create the particle system in
  57290. * @param rootUrl The root url to use to load external dependencies like texture
  57291. * @returns the parsed GPU particle system
  57292. */
  57293. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57294. var name = parsedParticleSystem.name;
  57295. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57296. if (parsedParticleSystem.id) {
  57297. particleSystem.id = parsedParticleSystem.id;
  57298. }
  57299. // Texture
  57300. if (parsedParticleSystem.textureName) {
  57301. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57302. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57303. }
  57304. // Emitter
  57305. if (parsedParticleSystem.emitterId) {
  57306. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57307. }
  57308. else {
  57309. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57310. }
  57311. // Animations
  57312. if (parsedParticleSystem.animations) {
  57313. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57314. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57315. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57316. }
  57317. }
  57318. // Particle system
  57319. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57320. particleSystem.minSize = parsedParticleSystem.minSize;
  57321. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57322. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57323. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57324. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57325. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57326. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57327. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57328. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57329. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57330. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57331. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57332. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57333. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57334. // Emitter
  57335. if (parsedParticleSystem.particleEmitterType) {
  57336. var emitterType = void 0;
  57337. switch (parsedParticleSystem.particleEmitterType.type) {
  57338. case "SphereEmitter":
  57339. emitterType = new BABYLON.SphereParticleEmitter();
  57340. break;
  57341. case "SphereDirectedParticleEmitter":
  57342. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57343. break;
  57344. case "ConeEmitter":
  57345. emitterType = new BABYLON.ConeParticleEmitter();
  57346. break;
  57347. case "BoxEmitter":
  57348. default:
  57349. emitterType = new BABYLON.BoxParticleEmitter();
  57350. break;
  57351. }
  57352. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57353. particleSystem.particleEmitterType = emitterType;
  57354. }
  57355. return particleSystem;
  57356. };
  57357. return GPUParticleSystem;
  57358. }());
  57359. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57360. })(BABYLON || (BABYLON = {}));
  57361. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57362. var BABYLON;
  57363. (function (BABYLON) {
  57364. /**
  57365. * Represents one particle of a solid particle system.
  57366. */
  57367. var SolidParticle = /** @class */ (function () {
  57368. /**
  57369. * Creates a Solid Particle object.
  57370. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57371. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57372. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57373. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57374. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57375. * @param shapeId (integer) is the model shape identifier in the SPS.
  57376. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57377. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57378. */
  57379. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57380. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57381. /**
  57382. * particle global index
  57383. */
  57384. this.idx = 0;
  57385. /**
  57386. * The color of the particle
  57387. */
  57388. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57389. /**
  57390. * The world space position of the particle.
  57391. */
  57392. this.position = BABYLON.Vector3.Zero();
  57393. /**
  57394. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57395. */
  57396. this.rotation = BABYLON.Vector3.Zero();
  57397. /**
  57398. * The scaling of the particle.
  57399. */
  57400. this.scaling = BABYLON.Vector3.One();
  57401. /**
  57402. * The uvs of the particle.
  57403. */
  57404. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57405. /**
  57406. * The current speed of the particle.
  57407. */
  57408. this.velocity = BABYLON.Vector3.Zero();
  57409. /**
  57410. * The pivot point in the particle local space.
  57411. */
  57412. this.pivot = BABYLON.Vector3.Zero();
  57413. /**
  57414. * Must the particle be translated from its pivot point in its local space ?
  57415. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57416. * Default : false
  57417. */
  57418. this.translateFromPivot = false;
  57419. /**
  57420. * Is the particle active or not ?
  57421. */
  57422. this.alive = true;
  57423. /**
  57424. * Is the particle visible or not ?
  57425. */
  57426. this.isVisible = true;
  57427. /**
  57428. * Index of this particle in the global "positions" array (Internal use)
  57429. */
  57430. this._pos = 0;
  57431. /**
  57432. * Index of this particle in the global "indices" array (Internal use)
  57433. */
  57434. this._ind = 0;
  57435. /**
  57436. * ModelShape id of this particle
  57437. */
  57438. this.shapeId = 0;
  57439. /**
  57440. * Index of the particle in its shape id (Internal use)
  57441. */
  57442. this.idxInShape = 0;
  57443. /**
  57444. * Still set as invisible in order to skip useless computations (Internal use)
  57445. */
  57446. this._stillInvisible = false;
  57447. /**
  57448. * Last computed particle rotation matrix
  57449. */
  57450. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57451. /**
  57452. * Parent particle Id, if any.
  57453. * Default null.
  57454. */
  57455. this.parentId = null;
  57456. /**
  57457. * Internal global position in the SPS.
  57458. */
  57459. this._globalPosition = BABYLON.Vector3.Zero();
  57460. this.idx = particleIndex;
  57461. this._pos = positionIndex;
  57462. this._ind = indiceIndex;
  57463. this._model = model;
  57464. this.shapeId = shapeId;
  57465. this.idxInShape = idxInShape;
  57466. this._sps = sps;
  57467. if (modelBoundingInfo) {
  57468. this._modelBoundingInfo = modelBoundingInfo;
  57469. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57470. }
  57471. }
  57472. Object.defineProperty(SolidParticle.prototype, "scale", {
  57473. /**
  57474. * Legacy support, changed scale to scaling
  57475. */
  57476. get: function () {
  57477. return this.scaling;
  57478. },
  57479. /**
  57480. * Legacy support, changed scale to scaling
  57481. */
  57482. set: function (scale) {
  57483. this.scaling = scale;
  57484. },
  57485. enumerable: true,
  57486. configurable: true
  57487. });
  57488. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57489. /**
  57490. * Legacy support, changed quaternion to rotationQuaternion
  57491. */
  57492. get: function () {
  57493. return this.rotationQuaternion;
  57494. },
  57495. /**
  57496. * Legacy support, changed quaternion to rotationQuaternion
  57497. */
  57498. set: function (q) {
  57499. this.rotationQuaternion = q;
  57500. },
  57501. enumerable: true,
  57502. configurable: true
  57503. });
  57504. /**
  57505. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57506. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57507. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57508. * @returns true if it intersects
  57509. */
  57510. SolidParticle.prototype.intersectsMesh = function (target) {
  57511. if (!this._boundingInfo || !target._boundingInfo) {
  57512. return false;
  57513. }
  57514. if (this._sps._bSphereOnly) {
  57515. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57516. }
  57517. return this._boundingInfo.intersects(target._boundingInfo, false);
  57518. };
  57519. return SolidParticle;
  57520. }());
  57521. BABYLON.SolidParticle = SolidParticle;
  57522. /**
  57523. * Represents the shape of the model used by one particle of a solid particle system.
  57524. * SPS internal tool, don't use it manually.
  57525. */
  57526. var ModelShape = /** @class */ (function () {
  57527. /**
  57528. * 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.
  57529. * SPS internal tool, don't use it manually.
  57530. * @ignore
  57531. */
  57532. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57533. /**
  57534. * length of the shape in the model indices array (internal use)
  57535. */
  57536. this._indicesLength = 0;
  57537. this.shapeID = id;
  57538. this._shape = shape;
  57539. this._indicesLength = indicesLength;
  57540. this._shapeUV = shapeUV;
  57541. this._positionFunction = posFunction;
  57542. this._vertexFunction = vtxFunction;
  57543. }
  57544. return ModelShape;
  57545. }());
  57546. BABYLON.ModelShape = ModelShape;
  57547. /**
  57548. * Represents a Depth Sorted Particle in the solid particle system.
  57549. */
  57550. var DepthSortedParticle = /** @class */ (function () {
  57551. function DepthSortedParticle() {
  57552. /**
  57553. * Index of the particle in the "indices" array
  57554. */
  57555. this.ind = 0;
  57556. /**
  57557. * Length of the particle shape in the "indices" array
  57558. */
  57559. this.indicesLength = 0;
  57560. /**
  57561. * Squared distance from the particle to the camera
  57562. */
  57563. this.sqDistance = 0.0;
  57564. }
  57565. return DepthSortedParticle;
  57566. }());
  57567. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57568. })(BABYLON || (BABYLON = {}));
  57569. //# sourceMappingURL=babylon.solidParticle.js.map
  57570. var BABYLON;
  57571. (function (BABYLON) {
  57572. /**
  57573. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57574. *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.
  57575. * The SPS is also a particle system. It provides some methods to manage the particles.
  57576. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57577. *
  57578. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57579. */
  57580. var SolidParticleSystem = /** @class */ (function () {
  57581. /**
  57582. * Creates a SPS (Solid Particle System) object.
  57583. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57584. * @param scene (Scene) is the scene in which the SPS is added.
  57585. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57586. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57587. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57588. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57589. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57590. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57591. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57592. */
  57593. function SolidParticleSystem(name, scene, options) {
  57594. /**
  57595. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57596. * Example : var p = SPS.particles[i];
  57597. */
  57598. this.particles = new Array();
  57599. /**
  57600. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57601. */
  57602. this.nbParticles = 0;
  57603. /**
  57604. * If the particles must ever face the camera (default false). Useful for planar particles.
  57605. */
  57606. this.billboard = false;
  57607. /**
  57608. * Recompute normals when adding a shape
  57609. */
  57610. this.recomputeNormals = true;
  57611. /**
  57612. * This a counter ofr your own usage. It's not set by any SPS functions.
  57613. */
  57614. this.counter = 0;
  57615. /**
  57616. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57617. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57618. */
  57619. this.vars = {};
  57620. /**
  57621. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57622. */
  57623. this._bSphereOnly = false;
  57624. /**
  57625. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57626. */
  57627. this._bSphereRadiusFactor = 1.0;
  57628. this._positions = new Array();
  57629. this._indices = new Array();
  57630. this._normals = new Array();
  57631. this._colors = new Array();
  57632. this._uvs = new Array();
  57633. this._index = 0; // indices index
  57634. this._updatable = true;
  57635. this._pickable = false;
  57636. this._isVisibilityBoxLocked = false;
  57637. this._alwaysVisible = false;
  57638. this._depthSort = false;
  57639. this._shapeCounter = 0;
  57640. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57641. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57642. this._computeParticleColor = true;
  57643. this._computeParticleTexture = true;
  57644. this._computeParticleRotation = true;
  57645. this._computeParticleVertex = false;
  57646. this._computeBoundingBox = false;
  57647. this._depthSortParticles = true;
  57648. this._cam_axisZ = BABYLON.Vector3.Zero();
  57649. this._cam_axisY = BABYLON.Vector3.Zero();
  57650. this._cam_axisX = BABYLON.Vector3.Zero();
  57651. this._axisZ = BABYLON.Axis.Z;
  57652. this._camDir = BABYLON.Vector3.Zero();
  57653. this._camInvertedPosition = BABYLON.Vector3.Zero();
  57654. this._rotMatrix = new BABYLON.Matrix();
  57655. this._invertMatrix = new BABYLON.Matrix();
  57656. this._rotated = BABYLON.Vector3.Zero();
  57657. this._quaternion = new BABYLON.Quaternion();
  57658. this._vertex = BABYLON.Vector3.Zero();
  57659. this._normal = BABYLON.Vector3.Zero();
  57660. this._yaw = 0.0;
  57661. this._pitch = 0.0;
  57662. this._roll = 0.0;
  57663. this._halfroll = 0.0;
  57664. this._halfpitch = 0.0;
  57665. this._halfyaw = 0.0;
  57666. this._sinRoll = 0.0;
  57667. this._cosRoll = 0.0;
  57668. this._sinPitch = 0.0;
  57669. this._cosPitch = 0.0;
  57670. this._sinYaw = 0.0;
  57671. this._cosYaw = 0.0;
  57672. this._mustUnrotateFixedNormals = false;
  57673. this._minimum = BABYLON.Vector3.Zero();
  57674. this._maximum = BABYLON.Vector3.Zero();
  57675. this._minBbox = BABYLON.Vector3.Zero();
  57676. this._maxBbox = BABYLON.Vector3.Zero();
  57677. this._particlesIntersect = false;
  57678. this._depthSortFunction = function (p1, p2) {
  57679. return (p2.sqDistance - p1.sqDistance);
  57680. };
  57681. this._needs32Bits = false;
  57682. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  57683. this._scaledPivot = BABYLON.Vector3.Zero();
  57684. this._particleHasParent = false;
  57685. this.name = name;
  57686. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57687. this._camera = scene.activeCamera;
  57688. this._pickable = options ? options.isPickable : false;
  57689. this._depthSort = options ? options.enableDepthSort : false;
  57690. this._particlesIntersect = options ? options.particleIntersection : false;
  57691. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  57692. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  57693. if (options && options.updatable) {
  57694. this._updatable = options.updatable;
  57695. }
  57696. else {
  57697. this._updatable = true;
  57698. }
  57699. if (this._pickable) {
  57700. this.pickedParticles = [];
  57701. }
  57702. if (this._depthSort) {
  57703. this.depthSortedParticles = [];
  57704. }
  57705. }
  57706. /**
  57707. * Builds the SPS underlying mesh. Returns a standard Mesh.
  57708. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  57709. * @returns the created mesh
  57710. */
  57711. SolidParticleSystem.prototype.buildMesh = function () {
  57712. if (this.nbParticles === 0) {
  57713. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  57714. this.addShape(triangle, 1);
  57715. triangle.dispose();
  57716. }
  57717. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  57718. this._positions32 = new Float32Array(this._positions);
  57719. this._uvs32 = new Float32Array(this._uvs);
  57720. this._colors32 = new Float32Array(this._colors);
  57721. if (this.recomputeNormals) {
  57722. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  57723. }
  57724. this._normals32 = new Float32Array(this._normals);
  57725. this._fixedNormal32 = new Float32Array(this._normals);
  57726. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  57727. this._unrotateFixedNormals();
  57728. }
  57729. var vertexData = new BABYLON.VertexData();
  57730. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  57731. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  57732. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  57733. if (this._uvs32) {
  57734. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  57735. ;
  57736. }
  57737. if (this._colors32) {
  57738. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  57739. }
  57740. var mesh = new BABYLON.Mesh(this.name, this._scene);
  57741. vertexData.applyToMesh(mesh, this._updatable);
  57742. this.mesh = mesh;
  57743. this.mesh.isPickable = this._pickable;
  57744. // free memory
  57745. if (!this._depthSort) {
  57746. this._indices = null;
  57747. }
  57748. this._positions = null;
  57749. this._normals = null;
  57750. this._uvs = null;
  57751. this._colors = null;
  57752. if (!this._updatable) {
  57753. this.particles.length = 0;
  57754. }
  57755. return mesh;
  57756. };
  57757. /**
  57758. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  57759. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  57760. * Thus the particles generated from `digest()` have their property `position` set yet.
  57761. * @param mesh ( Mesh ) is the mesh to be digested
  57762. * @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
  57763. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  57764. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  57765. * @returns the current SPS
  57766. */
  57767. SolidParticleSystem.prototype.digest = function (mesh, options) {
  57768. var size = (options && options.facetNb) || 1;
  57769. var number = (options && options.number) || 0;
  57770. var delta = (options && options.delta) || 0;
  57771. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57772. var meshInd = mesh.getIndices();
  57773. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57774. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  57775. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57776. var f = 0; // facet counter
  57777. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  57778. // compute size from number
  57779. if (number) {
  57780. number = (number > totalFacets) ? totalFacets : number;
  57781. size = Math.round(totalFacets / number);
  57782. delta = 0;
  57783. }
  57784. else {
  57785. size = (size > totalFacets) ? totalFacets : size;
  57786. }
  57787. var facetPos = []; // submesh positions
  57788. var facetInd = []; // submesh indices
  57789. var facetUV = []; // submesh UV
  57790. var facetCol = []; // submesh colors
  57791. var barycenter = BABYLON.Vector3.Zero();
  57792. var sizeO = size;
  57793. while (f < totalFacets) {
  57794. size = sizeO + Math.floor((1 + delta) * Math.random());
  57795. if (f > totalFacets - size) {
  57796. size = totalFacets - f;
  57797. }
  57798. // reset temp arrays
  57799. facetPos.length = 0;
  57800. facetInd.length = 0;
  57801. facetUV.length = 0;
  57802. facetCol.length = 0;
  57803. // iterate over "size" facets
  57804. var fi = 0;
  57805. for (var j = f * 3; j < (f + size) * 3; j++) {
  57806. facetInd.push(fi);
  57807. var i = meshInd[j];
  57808. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  57809. if (meshUV) {
  57810. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  57811. }
  57812. if (meshCol) {
  57813. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  57814. }
  57815. fi++;
  57816. }
  57817. // create a model shape for each single particle
  57818. var idx = this.nbParticles;
  57819. var shape = this._posToShape(facetPos);
  57820. var shapeUV = this._uvsToShapeUV(facetUV);
  57821. // compute the barycenter of the shape
  57822. var v;
  57823. for (v = 0; v < shape.length; v++) {
  57824. barycenter.addInPlace(shape[v]);
  57825. }
  57826. barycenter.scaleInPlace(1 / shape.length);
  57827. // shift the shape from its barycenter to the origin
  57828. for (v = 0; v < shape.length; v++) {
  57829. shape[v].subtractInPlace(barycenter);
  57830. }
  57831. var bInfo;
  57832. if (this._particlesIntersect) {
  57833. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  57834. }
  57835. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  57836. // add the particle in the SPS
  57837. var currentPos = this._positions.length;
  57838. var currentInd = this._indices.length;
  57839. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  57840. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  57841. // initialize the particle position
  57842. this.particles[this.nbParticles].position.addInPlace(barycenter);
  57843. this._index += shape.length;
  57844. idx++;
  57845. this.nbParticles++;
  57846. this._shapeCounter++;
  57847. f += size;
  57848. }
  57849. return this;
  57850. };
  57851. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  57852. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  57853. var index = 0;
  57854. var idx = 0;
  57855. for (var p = 0; p < this.particles.length; p++) {
  57856. this._particle = this.particles[p];
  57857. this._shape = this._particle._model._shape;
  57858. if (this._particle.rotationQuaternion) {
  57859. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  57860. }
  57861. else {
  57862. this._yaw = this._particle.rotation.y;
  57863. this._pitch = this._particle.rotation.x;
  57864. this._roll = this._particle.rotation.z;
  57865. this._quaternionRotationYPR();
  57866. }
  57867. this._quaternionToRotationMatrix();
  57868. this._rotMatrix.invertToRef(this._invertMatrix);
  57869. for (var pt = 0; pt < this._shape.length; pt++) {
  57870. idx = index + pt * 3;
  57871. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  57872. this._fixedNormal32[idx] = this._normal.x;
  57873. this._fixedNormal32[idx + 1] = this._normal.y;
  57874. this._fixedNormal32[idx + 2] = this._normal.z;
  57875. }
  57876. index = idx + 3;
  57877. }
  57878. };
  57879. //reset copy
  57880. SolidParticleSystem.prototype._resetCopy = function () {
  57881. this._copy.position.x = 0;
  57882. this._copy.position.y = 0;
  57883. this._copy.position.z = 0;
  57884. this._copy.rotation.x = 0;
  57885. this._copy.rotation.y = 0;
  57886. this._copy.rotation.z = 0;
  57887. this._copy.rotationQuaternion = null;
  57888. this._copy.scaling.x = 1.0;
  57889. this._copy.scaling.y = 1.0;
  57890. this._copy.scaling.z = 1.0;
  57891. this._copy.uvs.x = 0;
  57892. this._copy.uvs.y = 0;
  57893. this._copy.uvs.z = 1.0;
  57894. this._copy.uvs.w = 1.0;
  57895. this._copy.color = null;
  57896. this._copy.translateFromPivot = false;
  57897. };
  57898. // _meshBuilder : inserts the shape model in the global SPS mesh
  57899. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  57900. var i;
  57901. var u = 0;
  57902. var c = 0;
  57903. var n = 0;
  57904. this._resetCopy();
  57905. if (options && options.positionFunction) { // call to custom positionFunction
  57906. options.positionFunction(this._copy, idx, idxInShape);
  57907. this._mustUnrotateFixedNormals = true;
  57908. }
  57909. if (this._copy.rotationQuaternion) {
  57910. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  57911. }
  57912. else {
  57913. this._yaw = this._copy.rotation.y;
  57914. this._pitch = this._copy.rotation.x;
  57915. this._roll = this._copy.rotation.z;
  57916. this._quaternionRotationYPR();
  57917. }
  57918. this._quaternionToRotationMatrix();
  57919. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  57920. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  57921. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  57922. if (this._copy.translateFromPivot) {
  57923. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  57924. }
  57925. else {
  57926. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  57927. }
  57928. for (i = 0; i < shape.length; i++) {
  57929. this._vertex.x = shape[i].x;
  57930. this._vertex.y = shape[i].y;
  57931. this._vertex.z = shape[i].z;
  57932. if (options && options.vertexFunction) {
  57933. options.vertexFunction(this._copy, this._vertex, i);
  57934. }
  57935. this._vertex.x *= this._copy.scaling.x;
  57936. this._vertex.y *= this._copy.scaling.y;
  57937. this._vertex.z *= this._copy.scaling.z;
  57938. this._vertex.x -= this._scaledPivot.x;
  57939. this._vertex.y -= this._scaledPivot.y;
  57940. this._vertex.z -= this._scaledPivot.z;
  57941. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  57942. this._rotated.addInPlace(this._pivotBackTranslation);
  57943. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  57944. if (meshUV) {
  57945. 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);
  57946. u += 2;
  57947. }
  57948. if (this._copy.color) {
  57949. this._color = this._copy.color;
  57950. }
  57951. else if (meshCol && meshCol[c] !== undefined) {
  57952. this._color.r = meshCol[c];
  57953. this._color.g = meshCol[c + 1];
  57954. this._color.b = meshCol[c + 2];
  57955. this._color.a = meshCol[c + 3];
  57956. }
  57957. else {
  57958. this._color.r = 1.0;
  57959. this._color.g = 1.0;
  57960. this._color.b = 1.0;
  57961. this._color.a = 1.0;
  57962. }
  57963. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  57964. c += 4;
  57965. if (!this.recomputeNormals && meshNor) {
  57966. this._normal.x = meshNor[n];
  57967. this._normal.y = meshNor[n + 1];
  57968. this._normal.z = meshNor[n + 2];
  57969. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  57970. normals.push(this._normal.x, this._normal.y, this._normal.z);
  57971. n += 3;
  57972. }
  57973. }
  57974. for (i = 0; i < meshInd.length; i++) {
  57975. var current_ind = p + meshInd[i];
  57976. indices.push(current_ind);
  57977. if (current_ind > 65535) {
  57978. this._needs32Bits = true;
  57979. }
  57980. }
  57981. if (this._pickable) {
  57982. var nbfaces = meshInd.length / 3;
  57983. for (i = 0; i < nbfaces; i++) {
  57984. this.pickedParticles.push({ idx: idx, faceId: i });
  57985. }
  57986. }
  57987. if (this._depthSort) {
  57988. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  57989. }
  57990. return this._copy;
  57991. };
  57992. // returns a shape array from positions array
  57993. SolidParticleSystem.prototype._posToShape = function (positions) {
  57994. var shape = [];
  57995. for (var i = 0; i < positions.length; i += 3) {
  57996. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  57997. }
  57998. return shape;
  57999. };
  58000. // returns a shapeUV array from a Vector4 uvs
  58001. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58002. var shapeUV = [];
  58003. if (uvs) {
  58004. for (var i = 0; i < uvs.length; i++)
  58005. shapeUV.push(uvs[i]);
  58006. }
  58007. return shapeUV;
  58008. };
  58009. // adds a new particle object in the particles array
  58010. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58011. if (bInfo === void 0) { bInfo = null; }
  58012. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58013. this.particles.push(sp);
  58014. return sp;
  58015. };
  58016. /**
  58017. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58018. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58019. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58020. * @param nb (positive integer) the number of particles to be created from this model
  58021. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58022. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58023. * @returns the number of shapes in the system
  58024. */
  58025. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58026. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58027. var meshInd = mesh.getIndices();
  58028. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58029. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58030. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58031. var bbInfo;
  58032. if (this._particlesIntersect) {
  58033. bbInfo = mesh.getBoundingInfo();
  58034. }
  58035. var shape = this._posToShape(meshPos);
  58036. var shapeUV = this._uvsToShapeUV(meshUV);
  58037. var posfunc = options ? options.positionFunction : null;
  58038. var vtxfunc = options ? options.vertexFunction : null;
  58039. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58040. // particles
  58041. var sp;
  58042. var currentCopy;
  58043. var idx = this.nbParticles;
  58044. for (var i = 0; i < nb; i++) {
  58045. var currentPos = this._positions.length;
  58046. var currentInd = this._indices.length;
  58047. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58048. if (this._updatable) {
  58049. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58050. sp.position.copyFrom(currentCopy.position);
  58051. sp.rotation.copyFrom(currentCopy.rotation);
  58052. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58053. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58054. }
  58055. if (currentCopy.color && sp.color) {
  58056. sp.color.copyFrom(currentCopy.color);
  58057. }
  58058. sp.scaling.copyFrom(currentCopy.scaling);
  58059. sp.uvs.copyFrom(currentCopy.uvs);
  58060. }
  58061. this._index += shape.length;
  58062. idx++;
  58063. }
  58064. this.nbParticles += nb;
  58065. this._shapeCounter++;
  58066. return this._shapeCounter - 1;
  58067. };
  58068. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58069. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58070. this._resetCopy();
  58071. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58072. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58073. }
  58074. if (this._copy.rotationQuaternion) {
  58075. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58076. }
  58077. else {
  58078. this._yaw = this._copy.rotation.y;
  58079. this._pitch = this._copy.rotation.x;
  58080. this._roll = this._copy.rotation.z;
  58081. this._quaternionRotationYPR();
  58082. }
  58083. this._quaternionToRotationMatrix();
  58084. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58085. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58086. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58087. if (this._copy.translateFromPivot) {
  58088. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58089. }
  58090. else {
  58091. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58092. }
  58093. this._shape = particle._model._shape;
  58094. for (var pt = 0; pt < this._shape.length; pt++) {
  58095. this._vertex.x = this._shape[pt].x;
  58096. this._vertex.y = this._shape[pt].y;
  58097. this._vertex.z = this._shape[pt].z;
  58098. if (particle._model._vertexFunction) {
  58099. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58100. }
  58101. this._vertex.x *= this._copy.scaling.x;
  58102. this._vertex.y *= this._copy.scaling.y;
  58103. this._vertex.z *= this._copy.scaling.z;
  58104. this._vertex.x -= this._scaledPivot.x;
  58105. this._vertex.y -= this._scaledPivot.y;
  58106. this._vertex.z -= this._scaledPivot.z;
  58107. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58108. this._rotated.addInPlace(this._pivotBackTranslation);
  58109. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58110. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58111. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58112. }
  58113. particle.position.x = 0.0;
  58114. particle.position.y = 0.0;
  58115. particle.position.z = 0.0;
  58116. particle.rotation.x = 0.0;
  58117. particle.rotation.y = 0.0;
  58118. particle.rotation.z = 0.0;
  58119. particle.rotationQuaternion = null;
  58120. particle.scaling.x = 1.0;
  58121. particle.scaling.y = 1.0;
  58122. particle.scaling.z = 1.0;
  58123. particle.uvs.x = 0.0;
  58124. particle.uvs.y = 0.0;
  58125. particle.uvs.z = 1.0;
  58126. particle.uvs.w = 1.0;
  58127. particle.pivot.x = 0.0;
  58128. particle.pivot.y = 0.0;
  58129. particle.pivot.z = 0.0;
  58130. particle.translateFromPivot = false;
  58131. particle.parentId = null;
  58132. };
  58133. /**
  58134. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58135. * @returns the SPS.
  58136. */
  58137. SolidParticleSystem.prototype.rebuildMesh = function () {
  58138. for (var p = 0; p < this.particles.length; p++) {
  58139. this._rebuildParticle(this.particles[p]);
  58140. }
  58141. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58142. return this;
  58143. };
  58144. /**
  58145. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58146. * This method calls `updateParticle()` for each particle of the SPS.
  58147. * For an animated SPS, it is usually called within the render loop.
  58148. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58149. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58150. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58151. * @returns the SPS.
  58152. */
  58153. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58154. if (start === void 0) { start = 0; }
  58155. if (end === void 0) { end = this.nbParticles - 1; }
  58156. if (update === void 0) { update = true; }
  58157. if (!this._updatable) {
  58158. return this;
  58159. }
  58160. // custom beforeUpdate
  58161. this.beforeUpdateParticles(start, end, update);
  58162. this._cam_axisX.x = 1.0;
  58163. this._cam_axisX.y = 0.0;
  58164. this._cam_axisX.z = 0.0;
  58165. this._cam_axisY.x = 0.0;
  58166. this._cam_axisY.y = 1.0;
  58167. this._cam_axisY.z = 0.0;
  58168. this._cam_axisZ.x = 0.0;
  58169. this._cam_axisZ.y = 0.0;
  58170. this._cam_axisZ.z = 1.0;
  58171. // cases when the World Matrix is to be computed first
  58172. if (this.billboard || this._depthSort) {
  58173. this.mesh.computeWorldMatrix(true);
  58174. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58175. }
  58176. // if the particles will always face the camera
  58177. if (this.billboard) {
  58178. // compute the camera position and un-rotate it by the current mesh rotation
  58179. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58180. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58181. this._cam_axisZ.normalize();
  58182. // same for camera up vector extracted from the cam view matrix
  58183. var view = this._camera.getViewMatrix(true);
  58184. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58185. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58186. this._cam_axisY.normalize();
  58187. this._cam_axisX.normalize();
  58188. }
  58189. // if depthSort, compute the camera global position in the mesh local system
  58190. if (this._depthSort) {
  58191. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58192. }
  58193. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58194. var idx = 0; // current position index in the global array positions32
  58195. var index = 0; // position start index in the global array positions32 of the current particle
  58196. var colidx = 0; // current color index in the global array colors32
  58197. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58198. var uvidx = 0; // current uv index in the global array uvs32
  58199. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58200. var pt = 0; // current index in the particle model shape
  58201. if (this.mesh.isFacetDataEnabled) {
  58202. this._computeBoundingBox = true;
  58203. }
  58204. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58205. if (this._computeBoundingBox) {
  58206. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58207. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58208. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58209. }
  58210. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58211. if (this.mesh._boundingInfo) {
  58212. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58213. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58214. }
  58215. }
  58216. }
  58217. // particle loop
  58218. index = this.particles[start]._pos;
  58219. var vpos = (index / 3) | 0;
  58220. colorIndex = vpos * 4;
  58221. uvIndex = vpos * 2;
  58222. for (var p = start; p <= end; p++) {
  58223. this._particle = this.particles[p];
  58224. this._shape = this._particle._model._shape;
  58225. this._shapeUV = this._particle._model._shapeUV;
  58226. // call to custom user function to update the particle properties
  58227. this.updateParticle(this._particle);
  58228. // camera-particle distance for depth sorting
  58229. if (this._depthSort && this._depthSortParticles) {
  58230. var dsp = this.depthSortedParticles[p];
  58231. dsp.ind = this._particle._ind;
  58232. dsp.indicesLength = this._particle._model._indicesLength;
  58233. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58234. }
  58235. // skip the computations for inactive or already invisible particles
  58236. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58237. // increment indexes for the next particle
  58238. pt = this._shape.length;
  58239. index += pt * 3;
  58240. colorIndex += pt * 4;
  58241. uvIndex += pt * 2;
  58242. continue;
  58243. }
  58244. if (this._particle.isVisible) {
  58245. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58246. this._particleHasParent = (this._particle.parentId !== null);
  58247. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58248. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58249. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58250. // particle rotation matrix
  58251. if (this.billboard) {
  58252. this._particle.rotation.x = 0.0;
  58253. this._particle.rotation.y = 0.0;
  58254. }
  58255. if (this._computeParticleRotation || this.billboard) {
  58256. if (this._particle.rotationQuaternion) {
  58257. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58258. }
  58259. else {
  58260. this._yaw = this._particle.rotation.y;
  58261. this._pitch = this._particle.rotation.x;
  58262. this._roll = this._particle.rotation.z;
  58263. this._quaternionRotationYPR();
  58264. }
  58265. this._quaternionToRotationMatrix();
  58266. }
  58267. if (this._particleHasParent) {
  58268. this._parent = this.particles[this._particle.parentId];
  58269. 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];
  58270. 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];
  58271. 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];
  58272. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58273. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58274. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58275. if (this._computeParticleRotation || this.billboard) {
  58276. 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];
  58277. 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];
  58278. 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];
  58279. 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];
  58280. 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];
  58281. 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];
  58282. 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];
  58283. 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];
  58284. 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];
  58285. }
  58286. }
  58287. else {
  58288. this._particle._globalPosition.x = this._particle.position.x;
  58289. this._particle._globalPosition.y = this._particle.position.y;
  58290. this._particle._globalPosition.z = this._particle.position.z;
  58291. if (this._computeParticleRotation || this.billboard) {
  58292. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58293. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58294. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58295. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58296. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58297. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58298. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58299. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58300. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58301. }
  58302. }
  58303. if (this._particle.translateFromPivot) {
  58304. this._pivotBackTranslation.x = 0.0;
  58305. this._pivotBackTranslation.y = 0.0;
  58306. this._pivotBackTranslation.z = 0.0;
  58307. }
  58308. else {
  58309. this._pivotBackTranslation.x = this._scaledPivot.x;
  58310. this._pivotBackTranslation.y = this._scaledPivot.y;
  58311. this._pivotBackTranslation.z = this._scaledPivot.z;
  58312. }
  58313. // particle vertex loop
  58314. for (pt = 0; pt < this._shape.length; pt++) {
  58315. idx = index + pt * 3;
  58316. colidx = colorIndex + pt * 4;
  58317. uvidx = uvIndex + pt * 2;
  58318. this._vertex.x = this._shape[pt].x;
  58319. this._vertex.y = this._shape[pt].y;
  58320. this._vertex.z = this._shape[pt].z;
  58321. if (this._computeParticleVertex) {
  58322. this.updateParticleVertex(this._particle, this._vertex, pt);
  58323. }
  58324. // positions
  58325. this._vertex.x *= this._particle.scaling.x;
  58326. this._vertex.y *= this._particle.scaling.y;
  58327. this._vertex.z *= this._particle.scaling.z;
  58328. this._vertex.x -= this._scaledPivot.x;
  58329. this._vertex.y -= this._scaledPivot.y;
  58330. this._vertex.z -= this._scaledPivot.z;
  58331. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58332. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58333. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58334. this._rotated.x += this._pivotBackTranslation.x;
  58335. this._rotated.y += this._pivotBackTranslation.y;
  58336. this._rotated.z += this._pivotBackTranslation.z;
  58337. 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;
  58338. 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;
  58339. 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;
  58340. if (this._computeBoundingBox) {
  58341. if (this._positions32[idx] < this._minimum.x) {
  58342. this._minimum.x = this._positions32[idx];
  58343. }
  58344. if (this._positions32[idx] > this._maximum.x) {
  58345. this._maximum.x = this._positions32[idx];
  58346. }
  58347. if (this._positions32[idx + 1] < this._minimum.y) {
  58348. this._minimum.y = this._positions32[idx + 1];
  58349. }
  58350. if (this._positions32[idx + 1] > this._maximum.y) {
  58351. this._maximum.y = this._positions32[idx + 1];
  58352. }
  58353. if (this._positions32[idx + 2] < this._minimum.z) {
  58354. this._minimum.z = this._positions32[idx + 2];
  58355. }
  58356. if (this._positions32[idx + 2] > this._maximum.z) {
  58357. this._maximum.z = this._positions32[idx + 2];
  58358. }
  58359. }
  58360. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58361. if (!this._computeParticleVertex) {
  58362. this._normal.x = this._fixedNormal32[idx];
  58363. this._normal.y = this._fixedNormal32[idx + 1];
  58364. this._normal.z = this._fixedNormal32[idx + 2];
  58365. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58366. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58367. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58368. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58369. 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;
  58370. 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;
  58371. }
  58372. if (this._computeParticleColor && this._particle.color) {
  58373. this._colors32[colidx] = this._particle.color.r;
  58374. this._colors32[colidx + 1] = this._particle.color.g;
  58375. this._colors32[colidx + 2] = this._particle.color.b;
  58376. this._colors32[colidx + 3] = this._particle.color.a;
  58377. }
  58378. if (this._computeParticleTexture) {
  58379. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58380. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58381. }
  58382. }
  58383. }
  58384. // particle just set invisible : scaled to zero and positioned at the origin
  58385. else {
  58386. this._particle._stillInvisible = true; // mark the particle as invisible
  58387. for (pt = 0; pt < this._shape.length; pt++) {
  58388. idx = index + pt * 3;
  58389. colidx = colorIndex + pt * 4;
  58390. uvidx = uvIndex + pt * 2;
  58391. this._positions32[idx] = 0.0;
  58392. this._positions32[idx + 1] = 0.0;
  58393. this._positions32[idx + 2] = 0.0;
  58394. this._normals32[idx] = 0.0;
  58395. this._normals32[idx + 1] = 0.0;
  58396. this._normals32[idx + 2] = 0.0;
  58397. if (this._computeParticleColor && this._particle.color) {
  58398. this._colors32[colidx] = this._particle.color.r;
  58399. this._colors32[colidx + 1] = this._particle.color.g;
  58400. this._colors32[colidx + 2] = this._particle.color.b;
  58401. this._colors32[colidx + 3] = this._particle.color.a;
  58402. }
  58403. if (this._computeParticleTexture) {
  58404. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58405. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58406. }
  58407. }
  58408. }
  58409. // if the particle intersections must be computed : update the bbInfo
  58410. if (this._particlesIntersect) {
  58411. var bInfo = this._particle._boundingInfo;
  58412. var bBox = bInfo.boundingBox;
  58413. var bSphere = bInfo.boundingSphere;
  58414. if (!this._bSphereOnly) {
  58415. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58416. for (var b = 0; b < bBox.vectors.length; b++) {
  58417. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58418. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58419. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58420. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58421. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58422. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58423. 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;
  58424. 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;
  58425. 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;
  58426. }
  58427. bBox._update(this.mesh._worldMatrix);
  58428. }
  58429. // place and scale the particle bouding sphere in the SPS local system, then update it
  58430. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58431. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58432. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58433. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58434. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58435. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58436. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58437. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58438. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58439. 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));
  58440. bSphere._update(this.mesh._worldMatrix);
  58441. }
  58442. // increment indexes for the next particle
  58443. index = idx + 3;
  58444. colorIndex = colidx + 4;
  58445. uvIndex = uvidx + 2;
  58446. }
  58447. // if the VBO must be updated
  58448. if (update) {
  58449. if (this._computeParticleColor) {
  58450. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58451. }
  58452. if (this._computeParticleTexture) {
  58453. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58454. }
  58455. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58456. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58457. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58458. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58459. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58460. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58461. for (var i = 0; i < this._normals32.length; i++) {
  58462. this._fixedNormal32[i] = this._normals32[i];
  58463. }
  58464. }
  58465. if (!this.mesh.areNormalsFrozen) {
  58466. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58467. }
  58468. }
  58469. if (this._depthSort && this._depthSortParticles) {
  58470. this.depthSortedParticles.sort(this._depthSortFunction);
  58471. var dspl = this.depthSortedParticles.length;
  58472. var sorted = 0;
  58473. var lind = 0;
  58474. var sind = 0;
  58475. var sid = 0;
  58476. for (sorted = 0; sorted < dspl; sorted++) {
  58477. lind = this.depthSortedParticles[sorted].indicesLength;
  58478. sind = this.depthSortedParticles[sorted].ind;
  58479. for (var i = 0; i < lind; i++) {
  58480. this._indices32[sid] = this._indices[sind + i];
  58481. sid++;
  58482. }
  58483. }
  58484. this.mesh.updateIndices(this._indices32);
  58485. }
  58486. }
  58487. if (this._computeBoundingBox) {
  58488. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58489. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58490. }
  58491. this.afterUpdateParticles(start, end, update);
  58492. return this;
  58493. };
  58494. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58495. this._halfroll = this._roll * 0.5;
  58496. this._halfpitch = this._pitch * 0.5;
  58497. this._halfyaw = this._yaw * 0.5;
  58498. this._sinRoll = Math.sin(this._halfroll);
  58499. this._cosRoll = Math.cos(this._halfroll);
  58500. this._sinPitch = Math.sin(this._halfpitch);
  58501. this._cosPitch = Math.cos(this._halfpitch);
  58502. this._sinYaw = Math.sin(this._halfyaw);
  58503. this._cosYaw = Math.cos(this._halfyaw);
  58504. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58505. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58506. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58507. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58508. };
  58509. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58510. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58511. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58512. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58513. this._rotMatrix.m[3] = 0;
  58514. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58515. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58516. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58517. this._rotMatrix.m[7] = 0;
  58518. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58519. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58520. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58521. this._rotMatrix.m[11] = 0;
  58522. this._rotMatrix.m[12] = 0;
  58523. this._rotMatrix.m[13] = 0;
  58524. this._rotMatrix.m[14] = 0;
  58525. this._rotMatrix.m[15] = 1.0;
  58526. };
  58527. /**
  58528. * Disposes the SPS.
  58529. */
  58530. SolidParticleSystem.prototype.dispose = function () {
  58531. this.mesh.dispose();
  58532. this.vars = null;
  58533. // drop references to internal big arrays for the GC
  58534. this._positions = null;
  58535. this._indices = null;
  58536. this._normals = null;
  58537. this._uvs = null;
  58538. this._colors = null;
  58539. this._indices32 = null;
  58540. this._positions32 = null;
  58541. this._normals32 = null;
  58542. this._fixedNormal32 = null;
  58543. this._uvs32 = null;
  58544. this._colors32 = null;
  58545. this.pickedParticles = null;
  58546. };
  58547. /**
  58548. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58549. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58550. * @returns the SPS.
  58551. */
  58552. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58553. if (!this._isVisibilityBoxLocked) {
  58554. this.mesh.refreshBoundingInfo();
  58555. }
  58556. return this;
  58557. };
  58558. /**
  58559. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58560. * @param size the size (float) of the visibility box
  58561. * note : this doesn't lock the SPS mesh bounding box.
  58562. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58563. */
  58564. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58565. var vis = size / 2;
  58566. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58567. };
  58568. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58569. /**
  58570. * Gets whether the SPS as always visible or not
  58571. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58572. */
  58573. get: function () {
  58574. return this._alwaysVisible;
  58575. },
  58576. /**
  58577. * Sets the SPS as always visible or not
  58578. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58579. */
  58580. set: function (val) {
  58581. this._alwaysVisible = val;
  58582. this.mesh.alwaysSelectAsActiveMesh = val;
  58583. },
  58584. enumerable: true,
  58585. configurable: true
  58586. });
  58587. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58588. /**
  58589. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58590. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58591. */
  58592. get: function () {
  58593. return this._isVisibilityBoxLocked;
  58594. },
  58595. /**
  58596. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58597. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58598. */
  58599. set: function (val) {
  58600. this._isVisibilityBoxLocked = val;
  58601. var boundingInfo = this.mesh.getBoundingInfo();
  58602. boundingInfo.isLocked = val;
  58603. },
  58604. enumerable: true,
  58605. configurable: true
  58606. });
  58607. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58608. /**
  58609. * Gets if `setParticles()` computes the particle rotations or not.
  58610. * Default value : true. The SPS is faster when it's set to false.
  58611. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58612. */
  58613. get: function () {
  58614. return this._computeParticleRotation;
  58615. },
  58616. /**
  58617. * Tells to `setParticles()` to compute the particle rotations or not.
  58618. * Default value : true. The SPS is faster when it's set to false.
  58619. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58620. */
  58621. set: function (val) {
  58622. this._computeParticleRotation = val;
  58623. },
  58624. enumerable: true,
  58625. configurable: true
  58626. });
  58627. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58628. /**
  58629. * Gets if `setParticles()` computes the particle colors or not.
  58630. * Default value : true. The SPS is faster when it's set to false.
  58631. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58632. */
  58633. get: function () {
  58634. return this._computeParticleColor;
  58635. },
  58636. /**
  58637. * Tells to `setParticles()` to compute the particle colors or not.
  58638. * Default value : true. The SPS is faster when it's set to false.
  58639. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58640. */
  58641. set: function (val) {
  58642. this._computeParticleColor = val;
  58643. },
  58644. enumerable: true,
  58645. configurable: true
  58646. });
  58647. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  58648. /**
  58649. * Gets if `setParticles()` computes the particle textures or not.
  58650. * Default value : true. The SPS is faster when it's set to false.
  58651. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  58652. */
  58653. get: function () {
  58654. return this._computeParticleTexture;
  58655. },
  58656. set: function (val) {
  58657. this._computeParticleTexture = val;
  58658. },
  58659. enumerable: true,
  58660. configurable: true
  58661. });
  58662. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  58663. /**
  58664. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  58665. * Default value : false. The SPS is faster when it's set to false.
  58666. * Note : the particle custom vertex positions aren't stored values.
  58667. */
  58668. get: function () {
  58669. return this._computeParticleVertex;
  58670. },
  58671. /**
  58672. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  58673. * Default value : false. The SPS is faster when it's set to false.
  58674. * Note : the particle custom vertex positions aren't stored values.
  58675. */
  58676. set: function (val) {
  58677. this._computeParticleVertex = val;
  58678. },
  58679. enumerable: true,
  58680. configurable: true
  58681. });
  58682. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  58683. /**
  58684. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  58685. */
  58686. get: function () {
  58687. return this._computeBoundingBox;
  58688. },
  58689. /**
  58690. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  58691. */
  58692. set: function (val) {
  58693. this._computeBoundingBox = val;
  58694. },
  58695. enumerable: true,
  58696. configurable: true
  58697. });
  58698. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  58699. /**
  58700. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  58701. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58702. * Default : `true`
  58703. */
  58704. get: function () {
  58705. return this._depthSortParticles;
  58706. },
  58707. /**
  58708. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  58709. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  58710. * Default : `true`
  58711. */
  58712. set: function (val) {
  58713. this._depthSortParticles = val;
  58714. },
  58715. enumerable: true,
  58716. configurable: true
  58717. });
  58718. // =======================================================================
  58719. // Particle behavior logic
  58720. // these following methods may be overwritten by the user to fit his needs
  58721. /**
  58722. * This function does nothing. It may be overwritten to set all the particle first values.
  58723. * The SPS doesn't call this function, you may have to call it by your own.
  58724. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58725. */
  58726. SolidParticleSystem.prototype.initParticles = function () {
  58727. };
  58728. /**
  58729. * This function does nothing. It may be overwritten to recycle a particle.
  58730. * The SPS doesn't call this function, you may have to call it by your own.
  58731. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58732. * @param particle The particle to recycle
  58733. * @returns the recycled particle
  58734. */
  58735. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  58736. return particle;
  58737. };
  58738. /**
  58739. * Updates a particle : this function should be overwritten by the user.
  58740. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  58741. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  58742. * @example : just set a particle position or velocity and recycle conditions
  58743. * @param particle The particle to update
  58744. * @returns the updated particle
  58745. */
  58746. SolidParticleSystem.prototype.updateParticle = function (particle) {
  58747. return particle;
  58748. };
  58749. /**
  58750. * Updates a vertex of a particle : it can be overwritten by the user.
  58751. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  58752. * @param particle the current particle
  58753. * @param vertex the current index of the current particle
  58754. * @param pt the index of the current vertex in the particle shape
  58755. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  58756. * @example : just set a vertex particle position
  58757. * @returns the updated vertex
  58758. */
  58759. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  58760. return vertex;
  58761. };
  58762. /**
  58763. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  58764. * This does nothing and may be overwritten by the user.
  58765. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58766. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58767. * @param update the boolean update value actually passed to setParticles()
  58768. */
  58769. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  58770. };
  58771. /**
  58772. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  58773. * This will be passed three parameters.
  58774. * This does nothing and may be overwritten by the user.
  58775. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58776. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  58777. * @param update the boolean update value actually passed to setParticles()
  58778. */
  58779. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  58780. };
  58781. return SolidParticleSystem;
  58782. }());
  58783. BABYLON.SolidParticleSystem = SolidParticleSystem;
  58784. })(BABYLON || (BABYLON = {}));
  58785. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  58786. var BABYLON;
  58787. (function (BABYLON) {
  58788. var ShaderMaterial = /** @class */ (function (_super) {
  58789. __extends(ShaderMaterial, _super);
  58790. function ShaderMaterial(name, scene, shaderPath, options) {
  58791. var _this = _super.call(this, name, scene) || this;
  58792. _this._textures = {};
  58793. _this._textureArrays = {};
  58794. _this._floats = {};
  58795. _this._ints = {};
  58796. _this._floatsArrays = {};
  58797. _this._colors3 = {};
  58798. _this._colors3Arrays = {};
  58799. _this._colors4 = {};
  58800. _this._vectors2 = {};
  58801. _this._vectors3 = {};
  58802. _this._vectors4 = {};
  58803. _this._matrices = {};
  58804. _this._matrices3x3 = {};
  58805. _this._matrices2x2 = {};
  58806. _this._vectors2Arrays = {};
  58807. _this._vectors3Arrays = {};
  58808. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  58809. _this._shaderPath = shaderPath;
  58810. options.needAlphaBlending = options.needAlphaBlending || false;
  58811. options.needAlphaTesting = options.needAlphaTesting || false;
  58812. options.attributes = options.attributes || ["position", "normal", "uv"];
  58813. options.uniforms = options.uniforms || ["worldViewProjection"];
  58814. options.uniformBuffers = options.uniformBuffers || [];
  58815. options.samplers = options.samplers || [];
  58816. options.defines = options.defines || [];
  58817. _this._options = options;
  58818. return _this;
  58819. }
  58820. ShaderMaterial.prototype.getClassName = function () {
  58821. return "ShaderMaterial";
  58822. };
  58823. ShaderMaterial.prototype.needAlphaBlending = function () {
  58824. return this._options.needAlphaBlending;
  58825. };
  58826. ShaderMaterial.prototype.needAlphaTesting = function () {
  58827. return this._options.needAlphaTesting;
  58828. };
  58829. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  58830. if (this._options.uniforms.indexOf(uniformName) === -1) {
  58831. this._options.uniforms.push(uniformName);
  58832. }
  58833. };
  58834. ShaderMaterial.prototype.setTexture = function (name, texture) {
  58835. if (this._options.samplers.indexOf(name) === -1) {
  58836. this._options.samplers.push(name);
  58837. }
  58838. this._textures[name] = texture;
  58839. return this;
  58840. };
  58841. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  58842. if (this._options.samplers.indexOf(name) === -1) {
  58843. this._options.samplers.push(name);
  58844. }
  58845. this._checkUniform(name);
  58846. this._textureArrays[name] = textures;
  58847. return this;
  58848. };
  58849. ShaderMaterial.prototype.setFloat = function (name, value) {
  58850. this._checkUniform(name);
  58851. this._floats[name] = value;
  58852. return this;
  58853. };
  58854. ShaderMaterial.prototype.setInt = function (name, value) {
  58855. this._checkUniform(name);
  58856. this._ints[name] = value;
  58857. return this;
  58858. };
  58859. ShaderMaterial.prototype.setFloats = function (name, value) {
  58860. this._checkUniform(name);
  58861. this._floatsArrays[name] = value;
  58862. return this;
  58863. };
  58864. ShaderMaterial.prototype.setColor3 = function (name, value) {
  58865. this._checkUniform(name);
  58866. this._colors3[name] = value;
  58867. return this;
  58868. };
  58869. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  58870. this._checkUniform(name);
  58871. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  58872. color.toArray(arr, arr.length);
  58873. return arr;
  58874. }, []);
  58875. return this;
  58876. };
  58877. ShaderMaterial.prototype.setColor4 = function (name, value) {
  58878. this._checkUniform(name);
  58879. this._colors4[name] = value;
  58880. return this;
  58881. };
  58882. ShaderMaterial.prototype.setVector2 = function (name, value) {
  58883. this._checkUniform(name);
  58884. this._vectors2[name] = value;
  58885. return this;
  58886. };
  58887. ShaderMaterial.prototype.setVector3 = function (name, value) {
  58888. this._checkUniform(name);
  58889. this._vectors3[name] = value;
  58890. return this;
  58891. };
  58892. ShaderMaterial.prototype.setVector4 = function (name, value) {
  58893. this._checkUniform(name);
  58894. this._vectors4[name] = value;
  58895. return this;
  58896. };
  58897. ShaderMaterial.prototype.setMatrix = function (name, value) {
  58898. this._checkUniform(name);
  58899. this._matrices[name] = value;
  58900. return this;
  58901. };
  58902. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  58903. this._checkUniform(name);
  58904. this._matrices3x3[name] = value;
  58905. return this;
  58906. };
  58907. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  58908. this._checkUniform(name);
  58909. this._matrices2x2[name] = value;
  58910. return this;
  58911. };
  58912. ShaderMaterial.prototype.setArray2 = function (name, value) {
  58913. this._checkUniform(name);
  58914. this._vectors2Arrays[name] = value;
  58915. return this;
  58916. };
  58917. ShaderMaterial.prototype.setArray3 = function (name, value) {
  58918. this._checkUniform(name);
  58919. this._vectors3Arrays[name] = value;
  58920. return this;
  58921. };
  58922. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  58923. if (!mesh) {
  58924. return true;
  58925. }
  58926. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  58927. return false;
  58928. }
  58929. return false;
  58930. };
  58931. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  58932. var scene = this.getScene();
  58933. var engine = scene.getEngine();
  58934. if (!this.checkReadyOnEveryCall) {
  58935. if (this._renderId === scene.getRenderId()) {
  58936. if (this._checkCache(scene, mesh, useInstances)) {
  58937. return true;
  58938. }
  58939. }
  58940. }
  58941. // Instances
  58942. var defines = [];
  58943. var attribs = [];
  58944. var fallbacks = new BABYLON.EffectFallbacks();
  58945. if (useInstances) {
  58946. defines.push("#define INSTANCES");
  58947. }
  58948. for (var index = 0; index < this._options.defines.length; index++) {
  58949. defines.push(this._options.defines[index]);
  58950. }
  58951. for (var index = 0; index < this._options.attributes.length; index++) {
  58952. attribs.push(this._options.attributes[index]);
  58953. }
  58954. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  58955. attribs.push(BABYLON.VertexBuffer.ColorKind);
  58956. defines.push("#define VERTEXCOLOR");
  58957. }
  58958. // Bones
  58959. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  58960. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  58961. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  58962. if (mesh.numBoneInfluencers > 4) {
  58963. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  58964. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  58965. }
  58966. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  58967. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  58968. fallbacks.addCPUSkinningFallback(0, mesh);
  58969. if (this._options.uniforms.indexOf("mBones") === -1) {
  58970. this._options.uniforms.push("mBones");
  58971. }
  58972. }
  58973. else {
  58974. defines.push("#define NUM_BONE_INFLUENCERS 0");
  58975. }
  58976. // Textures
  58977. for (var name in this._textures) {
  58978. if (!this._textures[name].isReady()) {
  58979. return false;
  58980. }
  58981. }
  58982. // Alpha test
  58983. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  58984. defines.push("#define ALPHATEST");
  58985. }
  58986. var previousEffect = this._effect;
  58987. var join = defines.join("\n");
  58988. this._effect = engine.createEffect(this._shaderPath, {
  58989. attributes: attribs,
  58990. uniformsNames: this._options.uniforms,
  58991. uniformBuffersNames: this._options.uniformBuffers,
  58992. samplers: this._options.samplers,
  58993. defines: join,
  58994. fallbacks: fallbacks,
  58995. onCompiled: this.onCompiled,
  58996. onError: this.onError
  58997. }, engine);
  58998. if (!this._effect.isReady()) {
  58999. return false;
  59000. }
  59001. if (previousEffect !== this._effect) {
  59002. scene.resetCachedMaterial();
  59003. }
  59004. this._renderId = scene.getRenderId();
  59005. return true;
  59006. };
  59007. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59008. var scene = this.getScene();
  59009. if (!this._effect) {
  59010. return;
  59011. }
  59012. if (this._options.uniforms.indexOf("world") !== -1) {
  59013. this._effect.setMatrix("world", world);
  59014. }
  59015. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59016. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59017. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59018. }
  59019. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59020. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59021. }
  59022. };
  59023. ShaderMaterial.prototype.bind = function (world, mesh) {
  59024. // Std values
  59025. this.bindOnlyWorldMatrix(world);
  59026. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59027. if (this._options.uniforms.indexOf("view") !== -1) {
  59028. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59029. }
  59030. if (this._options.uniforms.indexOf("projection") !== -1) {
  59031. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59032. }
  59033. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59034. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59035. }
  59036. // Bones
  59037. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59038. var name;
  59039. // Texture
  59040. for (name in this._textures) {
  59041. this._effect.setTexture(name, this._textures[name]);
  59042. }
  59043. // Texture arrays
  59044. for (name in this._textureArrays) {
  59045. this._effect.setTextureArray(name, this._textureArrays[name]);
  59046. }
  59047. // Int
  59048. for (name in this._ints) {
  59049. this._effect.setInt(name, this._ints[name]);
  59050. }
  59051. // Float
  59052. for (name in this._floats) {
  59053. this._effect.setFloat(name, this._floats[name]);
  59054. }
  59055. // Floats
  59056. for (name in this._floatsArrays) {
  59057. this._effect.setArray(name, this._floatsArrays[name]);
  59058. }
  59059. // Color3
  59060. for (name in this._colors3) {
  59061. this._effect.setColor3(name, this._colors3[name]);
  59062. }
  59063. for (name in this._colors3Arrays) {
  59064. this._effect.setArray3(name, this._colors3Arrays[name]);
  59065. }
  59066. // Color4
  59067. for (name in this._colors4) {
  59068. var color = this._colors4[name];
  59069. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59070. }
  59071. // Vector2
  59072. for (name in this._vectors2) {
  59073. this._effect.setVector2(name, this._vectors2[name]);
  59074. }
  59075. // Vector3
  59076. for (name in this._vectors3) {
  59077. this._effect.setVector3(name, this._vectors3[name]);
  59078. }
  59079. // Vector4
  59080. for (name in this._vectors4) {
  59081. this._effect.setVector4(name, this._vectors4[name]);
  59082. }
  59083. // Matrix
  59084. for (name in this._matrices) {
  59085. this._effect.setMatrix(name, this._matrices[name]);
  59086. }
  59087. // Matrix 3x3
  59088. for (name in this._matrices3x3) {
  59089. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59090. }
  59091. // Matrix 2x2
  59092. for (name in this._matrices2x2) {
  59093. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59094. }
  59095. // Vector2Array
  59096. for (name in this._vectors2Arrays) {
  59097. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59098. }
  59099. // Vector3Array
  59100. for (name in this._vectors3Arrays) {
  59101. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59102. }
  59103. }
  59104. this._afterBind(mesh);
  59105. };
  59106. ShaderMaterial.prototype.getActiveTextures = function () {
  59107. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59108. for (var name in this._textures) {
  59109. activeTextures.push(this._textures[name]);
  59110. }
  59111. for (var name in this._textureArrays) {
  59112. var array = this._textureArrays[name];
  59113. for (var index = 0; index < array.length; index++) {
  59114. activeTextures.push(array[index]);
  59115. }
  59116. }
  59117. return activeTextures;
  59118. };
  59119. ShaderMaterial.prototype.hasTexture = function (texture) {
  59120. if (_super.prototype.hasTexture.call(this, texture)) {
  59121. return true;
  59122. }
  59123. for (var name in this._textures) {
  59124. if (this._textures[name] === texture) {
  59125. return true;
  59126. }
  59127. }
  59128. for (var name in this._textureArrays) {
  59129. var array = this._textureArrays[name];
  59130. for (var index = 0; index < array.length; index++) {
  59131. if (array[index] === texture) {
  59132. return true;
  59133. }
  59134. }
  59135. }
  59136. return false;
  59137. };
  59138. ShaderMaterial.prototype.clone = function (name) {
  59139. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59140. return newShaderMaterial;
  59141. };
  59142. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59143. if (forceDisposeTextures) {
  59144. var name;
  59145. for (name in this._textures) {
  59146. this._textures[name].dispose();
  59147. }
  59148. for (name in this._textureArrays) {
  59149. var array = this._textureArrays[name];
  59150. for (var index = 0; index < array.length; index++) {
  59151. array[index].dispose();
  59152. }
  59153. }
  59154. }
  59155. this._textures = {};
  59156. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59157. };
  59158. ShaderMaterial.prototype.serialize = function () {
  59159. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59160. serializationObject.customType = "BABYLON.ShaderMaterial";
  59161. serializationObject.options = this._options;
  59162. serializationObject.shaderPath = this._shaderPath;
  59163. var name;
  59164. // Texture
  59165. serializationObject.textures = {};
  59166. for (name in this._textures) {
  59167. serializationObject.textures[name] = this._textures[name].serialize();
  59168. }
  59169. // Texture arrays
  59170. serializationObject.textureArrays = {};
  59171. for (name in this._textureArrays) {
  59172. serializationObject.textureArrays[name] = [];
  59173. var array = this._textureArrays[name];
  59174. for (var index = 0; index < array.length; index++) {
  59175. serializationObject.textureArrays[name].push(array[index].serialize());
  59176. }
  59177. }
  59178. // Float
  59179. serializationObject.floats = {};
  59180. for (name in this._floats) {
  59181. serializationObject.floats[name] = this._floats[name];
  59182. }
  59183. // Float s
  59184. serializationObject.FloatArrays = {};
  59185. for (name in this._floatsArrays) {
  59186. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59187. }
  59188. // Color3
  59189. serializationObject.colors3 = {};
  59190. for (name in this._colors3) {
  59191. serializationObject.colors3[name] = this._colors3[name].asArray();
  59192. }
  59193. // Color3 array
  59194. serializationObject.colors3Arrays = {};
  59195. for (name in this._colors3Arrays) {
  59196. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59197. }
  59198. // Color4
  59199. serializationObject.colors4 = {};
  59200. for (name in this._colors4) {
  59201. serializationObject.colors4[name] = this._colors4[name].asArray();
  59202. }
  59203. // Vector2
  59204. serializationObject.vectors2 = {};
  59205. for (name in this._vectors2) {
  59206. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59207. }
  59208. // Vector3
  59209. serializationObject.vectors3 = {};
  59210. for (name in this._vectors3) {
  59211. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59212. }
  59213. // Vector4
  59214. serializationObject.vectors4 = {};
  59215. for (name in this._vectors4) {
  59216. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59217. }
  59218. // Matrix
  59219. serializationObject.matrices = {};
  59220. for (name in this._matrices) {
  59221. serializationObject.matrices[name] = this._matrices[name].asArray();
  59222. }
  59223. // Matrix 3x3
  59224. serializationObject.matrices3x3 = {};
  59225. for (name in this._matrices3x3) {
  59226. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59227. }
  59228. // Matrix 2x2
  59229. serializationObject.matrices2x2 = {};
  59230. for (name in this._matrices2x2) {
  59231. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59232. }
  59233. // Vector2Array
  59234. serializationObject.vectors2Arrays = {};
  59235. for (name in this._vectors2Arrays) {
  59236. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59237. }
  59238. // Vector3Array
  59239. serializationObject.vectors3Arrays = {};
  59240. for (name in this._vectors3Arrays) {
  59241. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59242. }
  59243. return serializationObject;
  59244. };
  59245. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59246. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59247. var name;
  59248. // Texture
  59249. for (name in source.textures) {
  59250. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59251. }
  59252. // Texture arrays
  59253. for (name in source.textureArrays) {
  59254. var array = source.textureArrays[name];
  59255. var textureArray = new Array();
  59256. for (var index = 0; index < array.length; index++) {
  59257. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59258. }
  59259. material.setTextureArray(name, textureArray);
  59260. }
  59261. // Float
  59262. for (name in source.floats) {
  59263. material.setFloat(name, source.floats[name]);
  59264. }
  59265. // Float s
  59266. for (name in source.floatsArrays) {
  59267. material.setFloats(name, source.floatsArrays[name]);
  59268. }
  59269. // Color3
  59270. for (name in source.colors3) {
  59271. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59272. }
  59273. // Color3 arrays
  59274. for (name in source.colors3Arrays) {
  59275. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59276. if (i % 3 === 0) {
  59277. arr.push([num]);
  59278. }
  59279. else {
  59280. arr[arr.length - 1].push(num);
  59281. }
  59282. return arr;
  59283. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59284. material.setColor3Array(name, colors);
  59285. }
  59286. // Color4
  59287. for (name in source.colors4) {
  59288. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59289. }
  59290. // Vector2
  59291. for (name in source.vectors2) {
  59292. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59293. }
  59294. // Vector3
  59295. for (name in source.vectors3) {
  59296. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59297. }
  59298. // Vector4
  59299. for (name in source.vectors4) {
  59300. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59301. }
  59302. // Matrix
  59303. for (name in source.matrices) {
  59304. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59305. }
  59306. // Matrix 3x3
  59307. for (name in source.matrices3x3) {
  59308. material.setMatrix3x3(name, source.matrices3x3[name]);
  59309. }
  59310. // Matrix 2x2
  59311. for (name in source.matrices2x2) {
  59312. material.setMatrix2x2(name, source.matrices2x2[name]);
  59313. }
  59314. // Vector2Array
  59315. for (name in source.vectors2Arrays) {
  59316. material.setArray2(name, source.vectors2Arrays[name]);
  59317. }
  59318. // Vector3Array
  59319. for (name in source.vectors3Arrays) {
  59320. material.setArray3(name, source.vectors3Arrays[name]);
  59321. }
  59322. return material;
  59323. };
  59324. return ShaderMaterial;
  59325. }(BABYLON.Material));
  59326. BABYLON.ShaderMaterial = ShaderMaterial;
  59327. })(BABYLON || (BABYLON = {}));
  59328. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59329. var BABYLON;
  59330. (function (BABYLON) {
  59331. var GroundMesh = /** @class */ (function (_super) {
  59332. __extends(GroundMesh, _super);
  59333. function GroundMesh(name, scene) {
  59334. var _this = _super.call(this, name, scene) || this;
  59335. _this.generateOctree = false;
  59336. return _this;
  59337. }
  59338. GroundMesh.prototype.getClassName = function () {
  59339. return "GroundMesh";
  59340. };
  59341. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59342. get: function () {
  59343. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59344. },
  59345. enumerable: true,
  59346. configurable: true
  59347. });
  59348. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59349. get: function () {
  59350. return this._subdivisionsX;
  59351. },
  59352. enumerable: true,
  59353. configurable: true
  59354. });
  59355. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59356. get: function () {
  59357. return this._subdivisionsY;
  59358. },
  59359. enumerable: true,
  59360. configurable: true
  59361. });
  59362. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59363. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59364. this._subdivisionsX = chunksCount;
  59365. this._subdivisionsY = chunksCount;
  59366. this.subdivide(chunksCount);
  59367. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59368. };
  59369. /**
  59370. * Returns a height (y) value in the Worl system :
  59371. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59372. * Returns the ground y position if (x, z) are outside the ground surface.
  59373. */
  59374. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59375. var world = this.getWorldMatrix();
  59376. var invMat = BABYLON.Tmp.Matrix[5];
  59377. world.invertToRef(invMat);
  59378. var tmpVect = BABYLON.Tmp.Vector3[8];
  59379. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59380. x = tmpVect.x;
  59381. z = tmpVect.z;
  59382. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59383. return this.position.y;
  59384. }
  59385. if (!this._heightQuads || this._heightQuads.length == 0) {
  59386. this._initHeightQuads();
  59387. this._computeHeightQuads();
  59388. }
  59389. var facet = this._getFacetAt(x, z);
  59390. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59391. // return y in the World system
  59392. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59393. return tmpVect.y;
  59394. };
  59395. /**
  59396. * Returns a normalized vector (Vector3) orthogonal to the ground
  59397. * at the ground coordinates (x, z) expressed in the World system.
  59398. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59399. */
  59400. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59401. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59402. this.getNormalAtCoordinatesToRef(x, z, normal);
  59403. return normal;
  59404. };
  59405. /**
  59406. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59407. * at the ground coordinates (x, z) expressed in the World system.
  59408. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59409. * Returns the GroundMesh.
  59410. */
  59411. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59412. var world = this.getWorldMatrix();
  59413. var tmpMat = BABYLON.Tmp.Matrix[5];
  59414. world.invertToRef(tmpMat);
  59415. var tmpVect = BABYLON.Tmp.Vector3[8];
  59416. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59417. x = tmpVect.x;
  59418. z = tmpVect.z;
  59419. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59420. return this;
  59421. }
  59422. if (!this._heightQuads || this._heightQuads.length == 0) {
  59423. this._initHeightQuads();
  59424. this._computeHeightQuads();
  59425. }
  59426. var facet = this._getFacetAt(x, z);
  59427. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59428. return this;
  59429. };
  59430. /**
  59431. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59432. * if the ground has been updated.
  59433. * This can be used in the render loop.
  59434. * Returns the GroundMesh.
  59435. */
  59436. GroundMesh.prototype.updateCoordinateHeights = function () {
  59437. if (!this._heightQuads || this._heightQuads.length == 0) {
  59438. this._initHeightQuads();
  59439. }
  59440. this._computeHeightQuads();
  59441. return this;
  59442. };
  59443. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59444. GroundMesh.prototype._getFacetAt = function (x, z) {
  59445. // retrieve col and row from x, z coordinates in the ground local system
  59446. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59447. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59448. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59449. var facet;
  59450. if (z < quad.slope.x * x + quad.slope.y) {
  59451. facet = quad.facet1;
  59452. }
  59453. else {
  59454. facet = quad.facet2;
  59455. }
  59456. return facet;
  59457. };
  59458. // Creates and populates the heightMap array with "facet" elements :
  59459. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59460. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59461. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59462. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59463. // Returns the GroundMesh.
  59464. GroundMesh.prototype._initHeightQuads = function () {
  59465. var subdivisionsX = this._subdivisionsX;
  59466. var subdivisionsY = this._subdivisionsY;
  59467. this._heightQuads = new Array();
  59468. for (var row = 0; row < subdivisionsY; row++) {
  59469. for (var col = 0; col < subdivisionsX; col++) {
  59470. 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) };
  59471. this._heightQuads[row * subdivisionsX + col] = quad;
  59472. }
  59473. }
  59474. return this;
  59475. };
  59476. // Compute each quad element values and update the the heightMap array :
  59477. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59478. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59479. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59480. // Returns the GroundMesh.
  59481. GroundMesh.prototype._computeHeightQuads = function () {
  59482. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59483. if (!positions) {
  59484. return this;
  59485. }
  59486. var v1 = BABYLON.Tmp.Vector3[3];
  59487. var v2 = BABYLON.Tmp.Vector3[2];
  59488. var v3 = BABYLON.Tmp.Vector3[1];
  59489. var v4 = BABYLON.Tmp.Vector3[0];
  59490. var v1v2 = BABYLON.Tmp.Vector3[4];
  59491. var v1v3 = BABYLON.Tmp.Vector3[5];
  59492. var v1v4 = BABYLON.Tmp.Vector3[6];
  59493. var norm1 = BABYLON.Tmp.Vector3[7];
  59494. var norm2 = BABYLON.Tmp.Vector3[8];
  59495. var i = 0;
  59496. var j = 0;
  59497. var k = 0;
  59498. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59499. var h = 0;
  59500. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59501. var d2 = 0;
  59502. var subdivisionsX = this._subdivisionsX;
  59503. var subdivisionsY = this._subdivisionsY;
  59504. for (var row = 0; row < subdivisionsY; row++) {
  59505. for (var col = 0; col < subdivisionsX; col++) {
  59506. i = col * 3;
  59507. j = row * (subdivisionsX + 1) * 3;
  59508. k = (row + 1) * (subdivisionsX + 1) * 3;
  59509. v1.x = positions[j + i];
  59510. v1.y = positions[j + i + 1];
  59511. v1.z = positions[j + i + 2];
  59512. v2.x = positions[j + i + 3];
  59513. v2.y = positions[j + i + 4];
  59514. v2.z = positions[j + i + 5];
  59515. v3.x = positions[k + i];
  59516. v3.y = positions[k + i + 1];
  59517. v3.z = positions[k + i + 2];
  59518. v4.x = positions[k + i + 3];
  59519. v4.y = positions[k + i + 4];
  59520. v4.z = positions[k + i + 5];
  59521. // 2D slope V1V4
  59522. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59523. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59524. // facet equations :
  59525. // we compute each facet normal vector
  59526. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59527. // we compute the value d by applying the equation to v1 which belongs to the plane
  59528. // then we store the facet equation in a Vector4
  59529. v2.subtractToRef(v1, v1v2);
  59530. v3.subtractToRef(v1, v1v3);
  59531. v4.subtractToRef(v1, v1v4);
  59532. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59533. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59534. norm1.normalize();
  59535. norm2.normalize();
  59536. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59537. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59538. var quad = this._heightQuads[row * subdivisionsX + col];
  59539. quad.slope.copyFromFloats(cd, h);
  59540. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59541. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59542. }
  59543. }
  59544. return this;
  59545. };
  59546. GroundMesh.prototype.serialize = function (serializationObject) {
  59547. _super.prototype.serialize.call(this, serializationObject);
  59548. serializationObject.subdivisionsX = this._subdivisionsX;
  59549. serializationObject.subdivisionsY = this._subdivisionsY;
  59550. serializationObject.minX = this._minX;
  59551. serializationObject.maxX = this._maxX;
  59552. serializationObject.minZ = this._minZ;
  59553. serializationObject.maxZ = this._maxZ;
  59554. serializationObject.width = this._width;
  59555. serializationObject.height = this._height;
  59556. };
  59557. GroundMesh.Parse = function (parsedMesh, scene) {
  59558. var result = new GroundMesh(parsedMesh.name, scene);
  59559. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59560. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59561. result._minX = parsedMesh.minX;
  59562. result._maxX = parsedMesh.maxX;
  59563. result._minZ = parsedMesh.minZ;
  59564. result._maxZ = parsedMesh.maxZ;
  59565. result._width = parsedMesh.width;
  59566. result._height = parsedMesh.height;
  59567. return result;
  59568. };
  59569. return GroundMesh;
  59570. }(BABYLON.Mesh));
  59571. BABYLON.GroundMesh = GroundMesh;
  59572. })(BABYLON || (BABYLON = {}));
  59573. //# sourceMappingURL=babylon.groundMesh.js.map
  59574. var BABYLON;
  59575. (function (BABYLON) {
  59576. /**
  59577. * Creates an instance based on a source mesh.
  59578. */
  59579. var InstancedMesh = /** @class */ (function (_super) {
  59580. __extends(InstancedMesh, _super);
  59581. function InstancedMesh(name, source) {
  59582. var _this = _super.call(this, name, source.getScene()) || this;
  59583. source.instances.push(_this);
  59584. _this._sourceMesh = source;
  59585. _this.position.copyFrom(source.position);
  59586. _this.rotation.copyFrom(source.rotation);
  59587. _this.scaling.copyFrom(source.scaling);
  59588. if (source.rotationQuaternion) {
  59589. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59590. }
  59591. _this.infiniteDistance = source.infiniteDistance;
  59592. _this.setPivotMatrix(source.getPivotMatrix());
  59593. _this.refreshBoundingInfo();
  59594. _this._syncSubMeshes();
  59595. return _this;
  59596. }
  59597. /**
  59598. * Returns the string "InstancedMesh".
  59599. */
  59600. InstancedMesh.prototype.getClassName = function () {
  59601. return "InstancedMesh";
  59602. };
  59603. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59604. // Methods
  59605. get: function () {
  59606. return this._sourceMesh.receiveShadows;
  59607. },
  59608. enumerable: true,
  59609. configurable: true
  59610. });
  59611. Object.defineProperty(InstancedMesh.prototype, "material", {
  59612. get: function () {
  59613. return this._sourceMesh.material;
  59614. },
  59615. enumerable: true,
  59616. configurable: true
  59617. });
  59618. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59619. get: function () {
  59620. return this._sourceMesh.visibility;
  59621. },
  59622. enumerable: true,
  59623. configurable: true
  59624. });
  59625. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59626. get: function () {
  59627. return this._sourceMesh.skeleton;
  59628. },
  59629. enumerable: true,
  59630. configurable: true
  59631. });
  59632. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59633. get: function () {
  59634. return this._sourceMesh.renderingGroupId;
  59635. },
  59636. set: function (value) {
  59637. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59638. return;
  59639. }
  59640. //no-op with warning
  59641. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59642. },
  59643. enumerable: true,
  59644. configurable: true
  59645. });
  59646. /**
  59647. * Returns the total number of vertices (integer).
  59648. */
  59649. InstancedMesh.prototype.getTotalVertices = function () {
  59650. return this._sourceMesh.getTotalVertices();
  59651. };
  59652. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  59653. get: function () {
  59654. return this._sourceMesh;
  59655. },
  59656. enumerable: true,
  59657. configurable: true
  59658. });
  59659. /**
  59660. * Is this node ready to be used/rendered
  59661. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  59662. * @return {boolean} is it ready
  59663. */
  59664. InstancedMesh.prototype.isReady = function (completeCheck) {
  59665. if (completeCheck === void 0) { completeCheck = false; }
  59666. return this._sourceMesh.isReady(completeCheck, true);
  59667. };
  59668. /**
  59669. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  59670. */
  59671. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  59672. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  59673. };
  59674. /**
  59675. * Sets the vertex data of the mesh geometry for the requested `kind`.
  59676. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  59677. * The `data` are either a numeric array either a Float32Array.
  59678. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  59679. * 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).
  59680. * Note that a new underlying VertexBuffer object is created each call.
  59681. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  59682. *
  59683. * Possible `kind` values :
  59684. * - BABYLON.VertexBuffer.PositionKind
  59685. * - BABYLON.VertexBuffer.UVKind
  59686. * - BABYLON.VertexBuffer.UV2Kind
  59687. * - BABYLON.VertexBuffer.UV3Kind
  59688. * - BABYLON.VertexBuffer.UV4Kind
  59689. * - BABYLON.VertexBuffer.UV5Kind
  59690. * - BABYLON.VertexBuffer.UV6Kind
  59691. * - BABYLON.VertexBuffer.ColorKind
  59692. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59693. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59694. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59695. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59696. *
  59697. * Returns the Mesh.
  59698. */
  59699. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  59700. if (this.sourceMesh) {
  59701. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  59702. }
  59703. return this.sourceMesh;
  59704. };
  59705. /**
  59706. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  59707. * If the mesh has no geometry, it is simply returned as it is.
  59708. * The `data` are either a numeric array either a Float32Array.
  59709. * No new underlying VertexBuffer object is created.
  59710. * 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.
  59711. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  59712. *
  59713. * Possible `kind` values :
  59714. * - BABYLON.VertexBuffer.PositionKind
  59715. * - BABYLON.VertexBuffer.UVKind
  59716. * - BABYLON.VertexBuffer.UV2Kind
  59717. * - BABYLON.VertexBuffer.UV3Kind
  59718. * - BABYLON.VertexBuffer.UV4Kind
  59719. * - BABYLON.VertexBuffer.UV5Kind
  59720. * - BABYLON.VertexBuffer.UV6Kind
  59721. * - BABYLON.VertexBuffer.ColorKind
  59722. * - BABYLON.VertexBuffer.MatricesIndicesKind
  59723. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  59724. * - BABYLON.VertexBuffer.MatricesWeightsKind
  59725. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  59726. *
  59727. * Returns the Mesh.
  59728. */
  59729. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  59730. if (this.sourceMesh) {
  59731. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  59732. }
  59733. return this.sourceMesh;
  59734. };
  59735. /**
  59736. * Sets the mesh indices.
  59737. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  59738. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  59739. * This method creates a new index buffer each call.
  59740. * Returns the Mesh.
  59741. */
  59742. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  59743. if (totalVertices === void 0) { totalVertices = null; }
  59744. if (this.sourceMesh) {
  59745. this.sourceMesh.setIndices(indices, totalVertices);
  59746. }
  59747. return this.sourceMesh;
  59748. };
  59749. /**
  59750. * Boolean : True if the mesh owns the requested kind of data.
  59751. */
  59752. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  59753. return this._sourceMesh.isVerticesDataPresent(kind);
  59754. };
  59755. /**
  59756. * Returns an array of indices (IndicesArray).
  59757. */
  59758. InstancedMesh.prototype.getIndices = function () {
  59759. return this._sourceMesh.getIndices();
  59760. };
  59761. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  59762. get: function () {
  59763. return this._sourceMesh._positions;
  59764. },
  59765. enumerable: true,
  59766. configurable: true
  59767. });
  59768. /**
  59769. * Sets a new updated BoundingInfo to the mesh.
  59770. * Returns the mesh.
  59771. */
  59772. InstancedMesh.prototype.refreshBoundingInfo = function () {
  59773. var meshBB = this._sourceMesh.getBoundingInfo();
  59774. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  59775. this._updateBoundingInfo();
  59776. return this;
  59777. };
  59778. InstancedMesh.prototype._preActivate = function () {
  59779. if (this._currentLOD) {
  59780. this._currentLOD._preActivate();
  59781. }
  59782. return this;
  59783. };
  59784. InstancedMesh.prototype._activate = function (renderId) {
  59785. if (this._currentLOD) {
  59786. this._currentLOD._registerInstanceForRenderId(this, renderId);
  59787. }
  59788. return this;
  59789. };
  59790. /**
  59791. * Returns the current associated LOD AbstractMesh.
  59792. */
  59793. InstancedMesh.prototype.getLOD = function (camera) {
  59794. if (!camera) {
  59795. return this;
  59796. }
  59797. var boundingInfo = this.getBoundingInfo();
  59798. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  59799. if (this._currentLOD === this.sourceMesh) {
  59800. return this;
  59801. }
  59802. return this._currentLOD;
  59803. };
  59804. InstancedMesh.prototype._syncSubMeshes = function () {
  59805. this.releaseSubMeshes();
  59806. if (this._sourceMesh.subMeshes) {
  59807. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  59808. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  59809. }
  59810. }
  59811. return this;
  59812. };
  59813. InstancedMesh.prototype._generatePointsArray = function () {
  59814. return this._sourceMesh._generatePointsArray();
  59815. };
  59816. /**
  59817. * Creates a new InstancedMesh from the current mesh.
  59818. * - name (string) : the cloned mesh name
  59819. * - newParent (optional Node) : the optional Node to parent the clone to.
  59820. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  59821. *
  59822. * Returns the clone.
  59823. */
  59824. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59825. var result = this._sourceMesh.createInstance(name);
  59826. // Deep copy
  59827. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  59828. // Bounding info
  59829. this.refreshBoundingInfo();
  59830. // Parent
  59831. if (newParent) {
  59832. result.parent = newParent;
  59833. }
  59834. if (!doNotCloneChildren) {
  59835. // Children
  59836. for (var index = 0; index < this.getScene().meshes.length; index++) {
  59837. var mesh = this.getScene().meshes[index];
  59838. if (mesh.parent === this) {
  59839. mesh.clone(mesh.name, result);
  59840. }
  59841. }
  59842. }
  59843. result.computeWorldMatrix(true);
  59844. return result;
  59845. };
  59846. /**
  59847. * Disposes the InstancedMesh.
  59848. * Returns nothing.
  59849. */
  59850. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  59851. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  59852. // Remove from mesh
  59853. var index = this._sourceMesh.instances.indexOf(this);
  59854. this._sourceMesh.instances.splice(index, 1);
  59855. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  59856. };
  59857. return InstancedMesh;
  59858. }(BABYLON.AbstractMesh));
  59859. BABYLON.InstancedMesh = InstancedMesh;
  59860. })(BABYLON || (BABYLON = {}));
  59861. //# sourceMappingURL=babylon.instancedMesh.js.map
  59862. var BABYLON;
  59863. (function (BABYLON) {
  59864. var LinesMesh = /** @class */ (function (_super) {
  59865. __extends(LinesMesh, _super);
  59866. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  59867. if (scene === void 0) { scene = null; }
  59868. if (parent === void 0) { parent = null; }
  59869. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  59870. _this.useVertexColor = useVertexColor;
  59871. _this.useVertexAlpha = useVertexAlpha;
  59872. _this.color = new BABYLON.Color3(1, 1, 1);
  59873. _this.alpha = 1;
  59874. if (source) {
  59875. _this.color = source.color.clone();
  59876. _this.alpha = source.alpha;
  59877. _this.useVertexColor = source.useVertexColor;
  59878. _this.useVertexAlpha = source.useVertexAlpha;
  59879. }
  59880. _this._intersectionThreshold = 0.1;
  59881. var defines = [];
  59882. var options = {
  59883. attributes: [BABYLON.VertexBuffer.PositionKind],
  59884. uniforms: ["world", "viewProjection"],
  59885. needAlphaBlending: true,
  59886. defines: defines
  59887. };
  59888. if (useVertexAlpha === false) {
  59889. options.needAlphaBlending = false;
  59890. }
  59891. if (!useVertexColor) {
  59892. options.uniforms.push("color");
  59893. }
  59894. else {
  59895. options.defines.push("#define VERTEXCOLOR");
  59896. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  59897. }
  59898. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  59899. return _this;
  59900. }
  59901. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  59902. /**
  59903. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59904. * This margin is expressed in world space coordinates, so its value may vary.
  59905. * Default value is 0.1
  59906. * @returns the intersection Threshold value.
  59907. */
  59908. get: function () {
  59909. return this._intersectionThreshold;
  59910. },
  59911. /**
  59912. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  59913. * This margin is expressed in world space coordinates, so its value may vary.
  59914. * @param value the new threshold to apply
  59915. */
  59916. set: function (value) {
  59917. if (this._intersectionThreshold === value) {
  59918. return;
  59919. }
  59920. this._intersectionThreshold = value;
  59921. if (this.geometry) {
  59922. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  59923. }
  59924. },
  59925. enumerable: true,
  59926. configurable: true
  59927. });
  59928. /**
  59929. * Returns the string "LineMesh"
  59930. */
  59931. LinesMesh.prototype.getClassName = function () {
  59932. return "LinesMesh";
  59933. };
  59934. Object.defineProperty(LinesMesh.prototype, "material", {
  59935. get: function () {
  59936. return this._colorShader;
  59937. },
  59938. set: function (value) {
  59939. // Do nothing
  59940. },
  59941. enumerable: true,
  59942. configurable: true
  59943. });
  59944. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  59945. get: function () {
  59946. return false;
  59947. },
  59948. enumerable: true,
  59949. configurable: true
  59950. });
  59951. LinesMesh.prototype.createInstance = function (name) {
  59952. throw new Error("LinesMeshes do not support createInstance.");
  59953. };
  59954. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  59955. if (!this._geometry) {
  59956. return this;
  59957. }
  59958. // VBOs
  59959. this._geometry._bind(this._colorShader.getEffect());
  59960. // Color
  59961. if (!this.useVertexColor) {
  59962. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  59963. }
  59964. return this;
  59965. };
  59966. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  59967. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  59968. return this;
  59969. }
  59970. var engine = this.getScene().getEngine();
  59971. // Draw order
  59972. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  59973. return this;
  59974. };
  59975. LinesMesh.prototype.dispose = function (doNotRecurse) {
  59976. this._colorShader.dispose();
  59977. _super.prototype.dispose.call(this, doNotRecurse);
  59978. };
  59979. /**
  59980. * Returns a new LineMesh object cloned from the current one.
  59981. */
  59982. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  59983. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  59984. };
  59985. return LinesMesh;
  59986. }(BABYLON.Mesh));
  59987. BABYLON.LinesMesh = LinesMesh;
  59988. })(BABYLON || (BABYLON = {}));
  59989. //# sourceMappingURL=babylon.linesMesh.js.map
  59990. var BABYLON;
  59991. (function (BABYLON) {
  59992. /**
  59993. * Class containing static functions to help procedurally build meshes
  59994. */
  59995. var MeshBuilder = /** @class */ (function () {
  59996. function MeshBuilder() {
  59997. }
  59998. MeshBuilder.updateSideOrientation = function (orientation) {
  59999. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60000. return BABYLON.Mesh.DOUBLESIDE;
  60001. }
  60002. if (orientation === undefined || orientation === null) {
  60003. return BABYLON.Mesh.FRONTSIDE;
  60004. }
  60005. return orientation;
  60006. };
  60007. /**
  60008. * Creates a box mesh
  60009. * * The parameter `size` sets the size (float) of each box side (default 1)
  60010. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60011. * * 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)
  60012. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60013. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60014. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60015. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60016. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60017. * @param name defines the name of the mesh
  60018. * @param options defines the options used to create the mesh
  60019. * @param scene defines the hosting scene
  60020. * @returns the box mesh
  60021. */
  60022. MeshBuilder.CreateBox = function (name, options, scene) {
  60023. if (scene === void 0) { scene = null; }
  60024. var box = new BABYLON.Mesh(name, scene);
  60025. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60026. box._originalBuilderSideOrientation = options.sideOrientation;
  60027. var vertexData = BABYLON.VertexData.CreateBox(options);
  60028. vertexData.applyToMesh(box, options.updatable);
  60029. return box;
  60030. };
  60031. /**
  60032. * Creates a sphere mesh
  60033. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60034. * * 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`)
  60035. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60036. * * 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
  60037. * * 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)
  60038. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60039. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60040. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60041. * @param name defines the name of the mesh
  60042. * @param options defines the options used to create the mesh
  60043. * @param scene defines the hosting scene
  60044. * @returns the sphere mesh
  60045. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60046. */
  60047. MeshBuilder.CreateSphere = function (name, options, scene) {
  60048. var sphere = new BABYLON.Mesh(name, scene);
  60049. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60050. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60051. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60052. vertexData.applyToMesh(sphere, options.updatable);
  60053. return sphere;
  60054. };
  60055. /**
  60056. * Creates a plane polygonal mesh. By default, this is a disc
  60057. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60058. * * 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
  60059. * * 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
  60060. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60061. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60062. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60063. * @param name defines the name of the mesh
  60064. * @param options defines the options used to create the mesh
  60065. * @param scene defines the hosting scene
  60066. * @returns the plane polygonal mesh
  60067. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  60068. */
  60069. MeshBuilder.CreateDisc = function (name, options, scene) {
  60070. if (scene === void 0) { scene = null; }
  60071. var disc = new BABYLON.Mesh(name, scene);
  60072. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60073. disc._originalBuilderSideOrientation = options.sideOrientation;
  60074. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60075. vertexData.applyToMesh(disc, options.updatable);
  60076. return disc;
  60077. };
  60078. /**
  60079. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60080. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60081. * * 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`)
  60082. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60083. * * 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
  60084. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60085. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60086. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60087. * @param name defines the name of the mesh
  60088. * @param options defines the options used to create the mesh
  60089. * @param scene defines the hosting scene
  60090. * @returns the icosahedron mesh
  60091. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  60092. */
  60093. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60094. var sphere = new BABYLON.Mesh(name, scene);
  60095. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60096. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60097. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60098. vertexData.applyToMesh(sphere, options.updatable);
  60099. return sphere;
  60100. };
  60101. ;
  60102. /**
  60103. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60104. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60105. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60106. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60107. * * 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
  60108. * * 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
  60109. * * 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
  60110. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60111. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60112. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60113. * * 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
  60114. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60115. * * 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
  60116. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60117. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60118. * @param name defines the name of the mesh
  60119. * @param options defines the options used to create the mesh
  60120. * @param scene defines the hosting scene
  60121. * @returns the ribbon mesh
  60122. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60123. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60124. */
  60125. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60126. if (scene === void 0) { scene = null; }
  60127. var pathArray = options.pathArray;
  60128. var closeArray = options.closeArray;
  60129. var closePath = options.closePath;
  60130. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60131. var instance = options.instance;
  60132. var updatable = options.updatable;
  60133. if (instance) { // existing ribbon instance update
  60134. // positionFunction : ribbon case
  60135. // only pathArray and sideOrientation parameters are taken into account for positions update
  60136. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60137. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60138. var positionFunction = function (positions) {
  60139. var minlg = pathArray[0].length;
  60140. var i = 0;
  60141. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60142. for (var si = 1; si <= ns; si++) {
  60143. for (var p = 0; p < pathArray.length; p++) {
  60144. var path = pathArray[p];
  60145. var l = path.length;
  60146. minlg = (minlg < l) ? minlg : l;
  60147. var j = 0;
  60148. while (j < minlg) {
  60149. positions[i] = path[j].x;
  60150. positions[i + 1] = path[j].y;
  60151. positions[i + 2] = path[j].z;
  60152. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60153. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60154. }
  60155. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60156. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60157. }
  60158. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60159. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60160. }
  60161. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60162. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60163. }
  60164. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60165. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60166. }
  60167. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60168. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60169. }
  60170. j++;
  60171. i += 3;
  60172. }
  60173. if (instance._closePath) {
  60174. positions[i] = path[0].x;
  60175. positions[i + 1] = path[0].y;
  60176. positions[i + 2] = path[0].z;
  60177. i += 3;
  60178. }
  60179. }
  60180. }
  60181. };
  60182. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60183. positionFunction(positions);
  60184. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60185. instance._boundingInfo.update(instance._worldMatrix);
  60186. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60187. if (options.colors) {
  60188. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60189. for (var c = 0; c < options.colors.length; c++) {
  60190. colors[c * 4] = options.colors[c].r;
  60191. colors[c * 4 + 1] = options.colors[c].g;
  60192. colors[c * 4 + 2] = options.colors[c].b;
  60193. colors[c * 4 + 3] = options.colors[c].a;
  60194. }
  60195. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60196. }
  60197. if (options.uvs) {
  60198. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60199. for (var i = 0; i < options.uvs.length; i++) {
  60200. uvs[i * 2] = options.uvs[i].x;
  60201. uvs[i * 2 + 1] = options.uvs[i].y;
  60202. }
  60203. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60204. }
  60205. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60206. var indices = instance.getIndices();
  60207. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60208. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60209. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60210. if (instance._closePath) {
  60211. var indexFirst = 0;
  60212. var indexLast = 0;
  60213. for (var p = 0; p < pathArray.length; p++) {
  60214. indexFirst = instance._idx[p] * 3;
  60215. if (p + 1 < pathArray.length) {
  60216. indexLast = (instance._idx[p + 1] - 1) * 3;
  60217. }
  60218. else {
  60219. indexLast = normals.length - 3;
  60220. }
  60221. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60222. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60223. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60224. normals[indexLast] = normals[indexFirst];
  60225. normals[indexLast + 1] = normals[indexFirst + 1];
  60226. normals[indexLast + 2] = normals[indexFirst + 2];
  60227. }
  60228. }
  60229. if (!(instance.areNormalsFrozen)) {
  60230. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60231. }
  60232. }
  60233. return instance;
  60234. }
  60235. else { // new ribbon creation
  60236. var ribbon = new BABYLON.Mesh(name, scene);
  60237. ribbon._originalBuilderSideOrientation = sideOrientation;
  60238. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60239. if (closePath) {
  60240. ribbon._idx = vertexData._idx;
  60241. }
  60242. ribbon._closePath = closePath;
  60243. ribbon._closeArray = closeArray;
  60244. vertexData.applyToMesh(ribbon, updatable);
  60245. return ribbon;
  60246. }
  60247. };
  60248. /**
  60249. * Creates a cylinder or a cone mesh
  60250. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60251. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60252. * * 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.
  60253. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60254. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60255. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60256. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60257. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60258. * * 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).
  60259. * * 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
  60260. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60261. * * 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
  60262. * * 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.
  60263. * * If `enclose` is false, a ring surface is one element.
  60264. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60265. * * 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
  60266. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60267. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60268. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60269. * @param name defines the name of the mesh
  60270. * @param options defines the options used to create the mesh
  60271. * @param scene defines the hosting scene
  60272. * @returns the cylinder mesh
  60273. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60274. */
  60275. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60276. var cylinder = new BABYLON.Mesh(name, scene);
  60277. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60278. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60279. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60280. vertexData.applyToMesh(cylinder, options.updatable);
  60281. return cylinder;
  60282. };
  60283. /**
  60284. * Creates a torus mesh
  60285. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60286. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60287. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60288. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60289. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60290. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60291. * @param name defines the name of the mesh
  60292. * @param options defines the options used to create the mesh
  60293. * @param scene defines the hosting scene
  60294. * @returns the torus mesh
  60295. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60296. */
  60297. MeshBuilder.CreateTorus = function (name, options, scene) {
  60298. var torus = new BABYLON.Mesh(name, scene);
  60299. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60300. torus._originalBuilderSideOrientation = options.sideOrientation;
  60301. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60302. vertexData.applyToMesh(torus, options.updatable);
  60303. return torus;
  60304. };
  60305. /**
  60306. * Creates a torus knot mesh
  60307. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60308. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60309. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60310. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60311. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60312. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60313. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60314. * @param name defines the name of the mesh
  60315. * @param options defines the options used to create the mesh
  60316. * @param scene defines the hosting scene
  60317. * @returns the torus knot mesh
  60318. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60319. */
  60320. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60321. var torusKnot = new BABYLON.Mesh(name, scene);
  60322. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60323. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60324. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60325. vertexData.applyToMesh(torusKnot, options.updatable);
  60326. return torusKnot;
  60327. };
  60328. /**
  60329. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60330. * * 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
  60331. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60332. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60333. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60334. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60335. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60336. * * 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
  60337. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60338. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60339. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  60340. * @param name defines the name of the new line system
  60341. * @param options defines the options used to create the line system
  60342. * @param scene defines the hosting scene
  60343. * @returns a new line system mesh
  60344. */
  60345. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60346. var instance = options.instance;
  60347. var lines = options.lines;
  60348. var colors = options.colors;
  60349. if (instance) { // lines update
  60350. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60351. var vertexColor;
  60352. var lineColors;
  60353. if (colors) {
  60354. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60355. }
  60356. var i = 0;
  60357. var c = 0;
  60358. for (var l = 0; l < lines.length; l++) {
  60359. var points = lines[l];
  60360. for (var p = 0; p < points.length; p++) {
  60361. positions[i] = points[p].x;
  60362. positions[i + 1] = points[p].y;
  60363. positions[i + 2] = points[p].z;
  60364. if (colors && vertexColor) {
  60365. lineColors = colors[l];
  60366. vertexColor[c] = lineColors[p].r;
  60367. vertexColor[c + 1] = lineColors[p].g;
  60368. vertexColor[c + 2] = lineColors[p].b;
  60369. vertexColor[c + 3] = lineColors[p].a;
  60370. c += 4;
  60371. }
  60372. i += 3;
  60373. }
  60374. }
  60375. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60376. if (colors && vertexColor) {
  60377. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60378. }
  60379. return instance;
  60380. }
  60381. // line system creation
  60382. var useVertexColor = (colors) ? true : false;
  60383. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60384. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60385. vertexData.applyToMesh(lineSystem, options.updatable);
  60386. return lineSystem;
  60387. };
  60388. /**
  60389. * Creates a line mesh
  60390. * 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
  60391. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60392. * * The parameter `points` is an array successive Vector3
  60393. * * 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
  60394. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60395. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60396. * * When updating an instance, remember that only point positions can change, not the number of points
  60397. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60398. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  60399. * @param name defines the name of the new line system
  60400. * @param options defines the options used to create the line system
  60401. * @param scene defines the hosting scene
  60402. * @returns a new line mesh
  60403. */
  60404. MeshBuilder.CreateLines = function (name, options, scene) {
  60405. if (scene === void 0) { scene = null; }
  60406. var colors = (options.colors) ? [options.colors] : null;
  60407. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60408. return lines;
  60409. };
  60410. /**
  60411. * Creates a dashed line mesh
  60412. * * 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
  60413. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60414. * * The parameter `points` is an array successive Vector3
  60415. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60416. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60417. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60418. * * 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
  60419. * * When updating an instance, remember that only point positions can change, not the number of points
  60420. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60421. * @param name defines the name of the mesh
  60422. * @param options defines the options used to create the mesh
  60423. * @param scene defines the hosting scene
  60424. * @returns the dashed line mesh
  60425. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  60426. */
  60427. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60428. if (scene === void 0) { scene = null; }
  60429. var points = options.points;
  60430. var instance = options.instance;
  60431. var gapSize = options.gapSize || 1;
  60432. var dashSize = options.dashSize || 3;
  60433. if (instance) { // dashed lines update
  60434. var positionFunction = function (positions) {
  60435. var curvect = BABYLON.Vector3.Zero();
  60436. var nbSeg = positions.length / 6;
  60437. var lg = 0;
  60438. var nb = 0;
  60439. var shft = 0;
  60440. var dashshft = 0;
  60441. var curshft = 0;
  60442. var p = 0;
  60443. var i = 0;
  60444. var j = 0;
  60445. for (i = 0; i < points.length - 1; i++) {
  60446. points[i + 1].subtractToRef(points[i], curvect);
  60447. lg += curvect.length();
  60448. }
  60449. shft = lg / nbSeg;
  60450. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60451. for (i = 0; i < points.length - 1; i++) {
  60452. points[i + 1].subtractToRef(points[i], curvect);
  60453. nb = Math.floor(curvect.length() / shft);
  60454. curvect.normalize();
  60455. j = 0;
  60456. while (j < nb && p < positions.length) {
  60457. curshft = shft * j;
  60458. positions[p] = points[i].x + curshft * curvect.x;
  60459. positions[p + 1] = points[i].y + curshft * curvect.y;
  60460. positions[p + 2] = points[i].z + curshft * curvect.z;
  60461. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60462. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60463. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60464. p += 6;
  60465. j++;
  60466. }
  60467. }
  60468. while (p < positions.length) {
  60469. positions[p] = points[i].x;
  60470. positions[p + 1] = points[i].y;
  60471. positions[p + 2] = points[i].z;
  60472. p += 3;
  60473. }
  60474. };
  60475. instance.updateMeshPositions(positionFunction, false);
  60476. return instance;
  60477. }
  60478. // dashed lines creation
  60479. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60480. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60481. vertexData.applyToMesh(dashedLines, options.updatable);
  60482. dashedLines.dashSize = dashSize;
  60483. dashedLines.gapSize = gapSize;
  60484. return dashedLines;
  60485. };
  60486. /**
  60487. * 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.
  60488. * * 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.
  60489. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60490. * * 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.
  60491. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60492. * * 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
  60493. * * 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
  60494. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60495. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60496. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60497. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60498. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60499. * @param name defines the name of the mesh
  60500. * @param options defines the options used to create the mesh
  60501. * @param scene defines the hosting scene
  60502. * @returns the extruded shape mesh
  60503. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60504. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60505. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  60506. */
  60507. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60508. if (scene === void 0) { scene = null; }
  60509. var path = options.path;
  60510. var shape = options.shape;
  60511. var scale = options.scale || 1;
  60512. var rotation = options.rotation || 0;
  60513. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60514. var updatable = options.updatable;
  60515. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60516. var instance = options.instance || null;
  60517. var invertUV = options.invertUV || false;
  60518. 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);
  60519. };
  60520. /**
  60521. * Creates an custom extruded shape mesh.
  60522. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60523. * * 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.
  60524. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60525. * * 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
  60526. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60527. * * 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
  60528. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60529. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60530. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60531. * * 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
  60532. * * 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
  60533. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60534. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60535. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60536. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60537. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60538. * @param name defines the name of the mesh
  60539. * @param options defines the options used to create the mesh
  60540. * @param scene defines the hosting scene
  60541. * @returns the custom extruded shape mesh
  60542. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  60543. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60544. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  60545. */
  60546. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60547. var path = options.path;
  60548. var shape = options.shape;
  60549. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60550. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60551. var ribbonCloseArray = options.ribbonCloseArray || false;
  60552. var ribbonClosePath = options.ribbonClosePath || false;
  60553. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60554. var updatable = options.updatable;
  60555. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60556. var instance = options.instance;
  60557. var invertUV = options.invertUV || false;
  60558. 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);
  60559. };
  60560. /**
  60561. * Creates lathe mesh.
  60562. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60563. * * 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
  60564. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60565. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60566. * * 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
  60567. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60568. * * 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
  60569. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60570. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60571. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60572. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60573. * @param name defines the name of the mesh
  60574. * @param options defines the options used to create the mesh
  60575. * @param scene defines the hosting scene
  60576. * @returns the lathe mesh
  60577. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  60578. */
  60579. MeshBuilder.CreateLathe = function (name, options, scene) {
  60580. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60581. var closed = (options.closed === undefined) ? true : options.closed;
  60582. var shape = options.shape;
  60583. var radius = options.radius || 1;
  60584. var tessellation = options.tessellation || 64;
  60585. var updatable = options.updatable;
  60586. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60587. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60588. var pi2 = Math.PI * 2;
  60589. var paths = new Array();
  60590. var invertUV = options.invertUV || false;
  60591. var i = 0;
  60592. var p = 0;
  60593. var step = pi2 / tessellation * arc;
  60594. var rotated;
  60595. var path = new Array();
  60596. ;
  60597. for (i = 0; i <= tessellation; i++) {
  60598. var path = [];
  60599. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60600. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60601. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60602. }
  60603. for (p = 0; p < shape.length; p++) {
  60604. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60605. path.push(rotated);
  60606. }
  60607. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60608. 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));
  60609. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60610. }
  60611. paths.push(path);
  60612. }
  60613. // lathe ribbon
  60614. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60615. return lathe;
  60616. };
  60617. /**
  60618. * Creates a plane mesh
  60619. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60620. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60621. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60622. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60623. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60624. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60625. * @param name defines the name of the mesh
  60626. * @param options defines the options used to create the mesh
  60627. * @param scene defines the hosting scene
  60628. * @returns the plane mesh
  60629. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60630. */
  60631. MeshBuilder.CreatePlane = function (name, options, scene) {
  60632. var plane = new BABYLON.Mesh(name, scene);
  60633. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60634. plane._originalBuilderSideOrientation = options.sideOrientation;
  60635. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60636. vertexData.applyToMesh(plane, options.updatable);
  60637. if (options.sourcePlane) {
  60638. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60639. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60640. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60641. plane.rotate(vectorProduct, product);
  60642. }
  60643. return plane;
  60644. };
  60645. /**
  60646. * Creates a ground mesh
  60647. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  60648. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  60649. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60650. * @param name defines the name of the mesh
  60651. * @param options defines the options used to create the mesh
  60652. * @param scene defines the hosting scene
  60653. * @returns the ground mesh
  60654. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60655. */
  60656. MeshBuilder.CreateGround = function (name, options, scene) {
  60657. var ground = new BABYLON.GroundMesh(name, scene);
  60658. ground._setReady(false);
  60659. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  60660. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  60661. ground._width = options.width || 1;
  60662. ground._height = options.height || 1;
  60663. ground._maxX = ground._width / 2;
  60664. ground._maxZ = ground._height / 2;
  60665. ground._minX = -ground._maxX;
  60666. ground._minZ = -ground._maxZ;
  60667. var vertexData = BABYLON.VertexData.CreateGround(options);
  60668. vertexData.applyToMesh(ground, options.updatable);
  60669. ground._setReady(true);
  60670. return ground;
  60671. };
  60672. /**
  60673. * Creates a tiled ground mesh
  60674. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  60675. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  60676. * * 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
  60677. * * 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
  60678. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60679. * @param name defines the name of the mesh
  60680. * @param options defines the options used to create the mesh
  60681. * @param scene defines the hosting scene
  60682. * @returns the tiled ground mesh
  60683. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  60684. */
  60685. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  60686. var tiledGround = new BABYLON.Mesh(name, scene);
  60687. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  60688. vertexData.applyToMesh(tiledGround, options.updatable);
  60689. return tiledGround;
  60690. };
  60691. /**
  60692. * Creates a ground mesh from a height map
  60693. * * The parameter `url` sets the URL of the height map image resource.
  60694. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  60695. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  60696. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  60697. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  60698. * * 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.
  60699. * * 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).
  60700. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60701. * @param name defines the name of the mesh
  60702. * @param url defines the url to the height map
  60703. * @param options defines the options used to create the mesh
  60704. * @param scene defines the hosting scene
  60705. * @returns the ground mesh
  60706. * @see http://doc.babylonjs.com/tutorials/14._Height_Map
  60707. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  60708. */
  60709. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  60710. var width = options.width || 10.0;
  60711. var height = options.height || 10.0;
  60712. var subdivisions = options.subdivisions || 1 | 0;
  60713. var minHeight = options.minHeight || 0.0;
  60714. var maxHeight = options.maxHeight || 1.0;
  60715. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  60716. var updatable = options.updatable;
  60717. var onReady = options.onReady;
  60718. var ground = new BABYLON.GroundMesh(name, scene);
  60719. ground._subdivisionsX = subdivisions;
  60720. ground._subdivisionsY = subdivisions;
  60721. ground._width = width;
  60722. ground._height = height;
  60723. ground._maxX = ground._width / 2.0;
  60724. ground._maxZ = ground._height / 2.0;
  60725. ground._minX = -ground._maxX;
  60726. ground._minZ = -ground._maxZ;
  60727. ground._setReady(false);
  60728. var onload = function (img) {
  60729. // Getting height map data
  60730. var canvas = document.createElement("canvas");
  60731. var context = canvas.getContext("2d");
  60732. if (!context) {
  60733. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  60734. }
  60735. if (scene.isDisposed) {
  60736. return;
  60737. }
  60738. var bufferWidth = img.width;
  60739. var bufferHeight = img.height;
  60740. canvas.width = bufferWidth;
  60741. canvas.height = bufferHeight;
  60742. context.drawImage(img, 0, 0);
  60743. // Create VertexData from map data
  60744. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  60745. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  60746. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  60747. width: width, height: height,
  60748. subdivisions: subdivisions,
  60749. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  60750. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  60751. });
  60752. vertexData.applyToMesh(ground, updatable);
  60753. //execute ready callback, if set
  60754. if (onReady) {
  60755. onReady(ground);
  60756. }
  60757. ground._setReady(true);
  60758. };
  60759. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  60760. return ground;
  60761. };
  60762. /**
  60763. * Creates a polygon mesh
  60764. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  60765. * * 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
  60766. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60767. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60768. * * 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)
  60769. * * Remember you can only change the shape positions, not their number when updating a polygon
  60770. * @param name defines the name of the mesh
  60771. * @param options defines the options used to create the mesh
  60772. * @param scene defines the hosting scene
  60773. * @returns the polygon mesh
  60774. */
  60775. MeshBuilder.CreatePolygon = function (name, options, scene) {
  60776. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60777. var shape = options.shape;
  60778. var holes = options.holes || [];
  60779. var depth = options.depth || 0;
  60780. var contours = [];
  60781. var hole = [];
  60782. for (var i = 0; i < shape.length; i++) {
  60783. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  60784. }
  60785. var epsilon = 0.00000001;
  60786. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  60787. contours.pop();
  60788. }
  60789. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  60790. for (var hNb = 0; hNb < holes.length; hNb++) {
  60791. hole = [];
  60792. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  60793. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  60794. }
  60795. polygonTriangulation.addHole(hole);
  60796. }
  60797. var polygon = polygonTriangulation.build(options.updatable, depth);
  60798. polygon._originalBuilderSideOrientation = options.sideOrientation;
  60799. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  60800. vertexData.applyToMesh(polygon, options.updatable);
  60801. return polygon;
  60802. };
  60803. ;
  60804. /**
  60805. * Creates an extruded polygon mesh, with depth in the Y direction.
  60806. * * 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)
  60807. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60808. * @param name defines the name of the mesh
  60809. * @param options defines the options used to create the mesh
  60810. * @param scene defines the hosting scene
  60811. * @returns the polygon mesh
  60812. */
  60813. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  60814. return MeshBuilder.CreatePolygon(name, options, scene);
  60815. };
  60816. ;
  60817. /**
  60818. * Creates a tube mesh.
  60819. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60820. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  60821. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  60822. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  60823. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  60824. * * 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)
  60825. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  60826. * * 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
  60827. * * 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
  60828. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60829. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60830. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60831. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60832. * @param name defines the name of the mesh
  60833. * @param options defines the options used to create the mesh
  60834. * @param scene defines the hosting scene
  60835. * @returns the tube mesh
  60836. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60837. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  60838. */
  60839. MeshBuilder.CreateTube = function (name, options, scene) {
  60840. var path = options.path;
  60841. var instance = options.instance;
  60842. var radius = 1.0;
  60843. if (instance) {
  60844. radius = instance.radius;
  60845. }
  60846. if (options.radius !== undefined) {
  60847. radius = options.radius;
  60848. }
  60849. ;
  60850. var tessellation = options.tessellation || 64 | 0;
  60851. var radiusFunction = options.radiusFunction || null;
  60852. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60853. var invertUV = options.invertUV || false;
  60854. var updatable = options.updatable;
  60855. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60856. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  60857. // tube geometry
  60858. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  60859. var tangents = path3D.getTangents();
  60860. var normals = path3D.getNormals();
  60861. var distances = path3D.getDistances();
  60862. var pi2 = Math.PI * 2;
  60863. var step = pi2 / tessellation * arc;
  60864. var returnRadius = function () { return radius; };
  60865. var radiusFunctionFinal = radiusFunction || returnRadius;
  60866. var circlePath;
  60867. var rad;
  60868. var normal;
  60869. var rotated;
  60870. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  60871. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  60872. for (var i = 0; i < path.length; i++) {
  60873. rad = radiusFunctionFinal(i, distances[i]); // current radius
  60874. circlePath = Array(); // current circle array
  60875. normal = normals[i]; // current normal
  60876. for (var t = 0; t < tessellation; t++) {
  60877. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  60878. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  60879. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  60880. rotated.scaleInPlace(rad).addInPlace(path[i]);
  60881. circlePath[t] = rotated;
  60882. }
  60883. circlePaths[index] = circlePath;
  60884. index++;
  60885. }
  60886. // cap
  60887. var capPath = function (nbPoints, pathIndex) {
  60888. var pointCap = Array();
  60889. for (var i = 0; i < nbPoints; i++) {
  60890. pointCap.push(path[pathIndex]);
  60891. }
  60892. return pointCap;
  60893. };
  60894. switch (cap) {
  60895. case BABYLON.Mesh.NO_CAP:
  60896. break;
  60897. case BABYLON.Mesh.CAP_START:
  60898. circlePaths[0] = capPath(tessellation, 0);
  60899. circlePaths[1] = circlePaths[2].slice(0);
  60900. break;
  60901. case BABYLON.Mesh.CAP_END:
  60902. circlePaths[index] = circlePaths[index - 1].slice(0);
  60903. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60904. break;
  60905. case BABYLON.Mesh.CAP_ALL:
  60906. circlePaths[0] = capPath(tessellation, 0);
  60907. circlePaths[1] = circlePaths[2].slice(0);
  60908. circlePaths[index] = circlePaths[index - 1].slice(0);
  60909. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  60910. break;
  60911. default:
  60912. break;
  60913. }
  60914. return circlePaths;
  60915. };
  60916. var path3D;
  60917. var pathArray;
  60918. if (instance) { // tube update
  60919. var arc = options.arc || instance.arc;
  60920. path3D = (instance.path3D).update(path);
  60921. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  60922. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  60923. instance.path3D = path3D;
  60924. instance.pathArray = pathArray;
  60925. instance.arc = arc;
  60926. instance.radius = radius;
  60927. return instance;
  60928. }
  60929. // tube creation
  60930. path3D = new BABYLON.Path3D(path);
  60931. var newPathArray = new Array();
  60932. cap = (cap < 0 || cap > 3) ? 0 : cap;
  60933. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  60934. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60935. tube.pathArray = pathArray;
  60936. tube.path3D = path3D;
  60937. tube.tessellation = tessellation;
  60938. tube.cap = cap;
  60939. tube.arc = options.arc;
  60940. tube.radius = radius;
  60941. return tube;
  60942. };
  60943. /**
  60944. * Creates a polyhedron mesh
  60945. * * 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
  60946. * * The parameter `size` (positive float, default 1) sets the polygon size
  60947. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  60948. * * 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`
  60949. * * 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
  60950. * * 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)`)
  60951. * * 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
  60952. * * 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
  60953. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60954. * * 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/tutorials/02._Discover_Basic_Elements#side-orientation
  60955. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60956. * @param name defines the name of the mesh
  60957. * @param options defines the options used to create the mesh
  60958. * @param scene defines the hosting scene
  60959. * @returns the polyhedron mesh
  60960. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  60961. */
  60962. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  60963. var polyhedron = new BABYLON.Mesh(name, scene);
  60964. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60965. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  60966. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  60967. vertexData.applyToMesh(polyhedron, options.updatable);
  60968. return polyhedron;
  60969. };
  60970. /**
  60971. * Creates a decal mesh.
  60972. * 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
  60973. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  60974. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  60975. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  60976. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  60977. * @param name defines the name of the mesh
  60978. * @param sourceMesh defines the mesh where the decal must be applied
  60979. * @param options defines the options used to create the mesh
  60980. * @param scene defines the hosting scene
  60981. * @returns the decal mesh
  60982. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  60983. */
  60984. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  60985. var indices = sourceMesh.getIndices();
  60986. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60987. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60988. var position = options.position || BABYLON.Vector3.Zero();
  60989. var normal = options.normal || BABYLON.Vector3.Up();
  60990. var size = options.size || BABYLON.Vector3.One();
  60991. var angle = options.angle || 0;
  60992. // Getting correct rotation
  60993. if (!normal) {
  60994. var target = new BABYLON.Vector3(0, 0, 1);
  60995. var camera = sourceMesh.getScene().activeCamera;
  60996. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  60997. normal = camera.globalPosition.subtract(cameraWorldTarget);
  60998. }
  60999. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61000. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61001. var pitch = Math.atan2(normal.y, len);
  61002. // Matrix
  61003. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61004. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61005. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61006. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61007. var vertexData = new BABYLON.VertexData();
  61008. vertexData.indices = [];
  61009. vertexData.positions = [];
  61010. vertexData.normals = [];
  61011. vertexData.uvs = [];
  61012. var currentVertexDataIndex = 0;
  61013. var extractDecalVector3 = function (indexId) {
  61014. var result = new BABYLON.PositionNormalVertex();
  61015. if (!indices || !positions || !normals) {
  61016. return result;
  61017. }
  61018. var vertexId = indices[indexId];
  61019. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61020. // Send vector to decal local world
  61021. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61022. // Get normal
  61023. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61024. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61025. return result;
  61026. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61027. var clip = function (vertices, axis) {
  61028. if (vertices.length === 0) {
  61029. return vertices;
  61030. }
  61031. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61032. var clipVertices = function (v0, v1) {
  61033. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61034. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61035. };
  61036. var result = new Array();
  61037. for (var index = 0; index < vertices.length; index += 3) {
  61038. var v1Out;
  61039. var v2Out;
  61040. var v3Out;
  61041. var total = 0;
  61042. var nV1 = null;
  61043. var nV2 = null;
  61044. var nV3 = null;
  61045. var nV4 = null;
  61046. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61047. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61048. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61049. v1Out = d1 > 0;
  61050. v2Out = d2 > 0;
  61051. v3Out = d3 > 0;
  61052. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61053. switch (total) {
  61054. case 0:
  61055. result.push(vertices[index]);
  61056. result.push(vertices[index + 1]);
  61057. result.push(vertices[index + 2]);
  61058. break;
  61059. case 1:
  61060. if (v1Out) {
  61061. nV1 = vertices[index + 1];
  61062. nV2 = vertices[index + 2];
  61063. nV3 = clipVertices(vertices[index], nV1);
  61064. nV4 = clipVertices(vertices[index], nV2);
  61065. }
  61066. if (v2Out) {
  61067. nV1 = vertices[index];
  61068. nV2 = vertices[index + 2];
  61069. nV3 = clipVertices(vertices[index + 1], nV1);
  61070. nV4 = clipVertices(vertices[index + 1], nV2);
  61071. result.push(nV3);
  61072. result.push(nV2.clone());
  61073. result.push(nV1.clone());
  61074. result.push(nV2.clone());
  61075. result.push(nV3.clone());
  61076. result.push(nV4);
  61077. break;
  61078. }
  61079. if (v3Out) {
  61080. nV1 = vertices[index];
  61081. nV2 = vertices[index + 1];
  61082. nV3 = clipVertices(vertices[index + 2], nV1);
  61083. nV4 = clipVertices(vertices[index + 2], nV2);
  61084. }
  61085. if (nV1 && nV2 && nV3 && nV4) {
  61086. result.push(nV1.clone());
  61087. result.push(nV2.clone());
  61088. result.push(nV3);
  61089. result.push(nV4);
  61090. result.push(nV3.clone());
  61091. result.push(nV2.clone());
  61092. }
  61093. break;
  61094. case 2:
  61095. if (!v1Out) {
  61096. nV1 = vertices[index].clone();
  61097. nV2 = clipVertices(nV1, vertices[index + 1]);
  61098. nV3 = clipVertices(nV1, vertices[index + 2]);
  61099. result.push(nV1);
  61100. result.push(nV2);
  61101. result.push(nV3);
  61102. }
  61103. if (!v2Out) {
  61104. nV1 = vertices[index + 1].clone();
  61105. nV2 = clipVertices(nV1, vertices[index + 2]);
  61106. nV3 = clipVertices(nV1, vertices[index]);
  61107. result.push(nV1);
  61108. result.push(nV2);
  61109. result.push(nV3);
  61110. }
  61111. if (!v3Out) {
  61112. nV1 = vertices[index + 2].clone();
  61113. nV2 = clipVertices(nV1, vertices[index]);
  61114. nV3 = clipVertices(nV1, vertices[index + 1]);
  61115. result.push(nV1);
  61116. result.push(nV2);
  61117. result.push(nV3);
  61118. }
  61119. break;
  61120. case 3:
  61121. break;
  61122. }
  61123. }
  61124. return result;
  61125. };
  61126. for (var index = 0; index < indices.length; index += 3) {
  61127. var faceVertices = new Array();
  61128. faceVertices.push(extractDecalVector3(index));
  61129. faceVertices.push(extractDecalVector3(index + 1));
  61130. faceVertices.push(extractDecalVector3(index + 2));
  61131. // Clip
  61132. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61133. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61134. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61135. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61136. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61137. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61138. if (faceVertices.length === 0) {
  61139. continue;
  61140. }
  61141. // Add UVs and get back to world
  61142. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61143. var vertex = faceVertices[vIndex];
  61144. //TODO check for Int32Array | Uint32Array | Uint16Array
  61145. vertexData.indices.push(currentVertexDataIndex);
  61146. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61147. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61148. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61149. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61150. currentVertexDataIndex++;
  61151. }
  61152. }
  61153. // Return mesh
  61154. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61155. vertexData.applyToMesh(decal);
  61156. decal.position = position.clone();
  61157. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61158. return decal;
  61159. };
  61160. // Privates
  61161. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61162. // extrusion geometry
  61163. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61164. var tangents = path3D.getTangents();
  61165. var normals = path3D.getNormals();
  61166. var binormals = path3D.getBinormals();
  61167. var distances = path3D.getDistances();
  61168. var angle = 0;
  61169. var returnScale = function () { return scale !== null ? scale : 1; };
  61170. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61171. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61172. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61173. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61174. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61175. for (var i = 0; i < curve.length; i++) {
  61176. var shapePath = new Array();
  61177. var angleStep = rotate(i, distances[i]);
  61178. var scaleRatio = scl(i, distances[i]);
  61179. for (var p = 0; p < shape.length; p++) {
  61180. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61181. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61182. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61183. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61184. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61185. shapePath[p] = rotated;
  61186. }
  61187. shapePaths[index] = shapePath;
  61188. angle += angleStep;
  61189. index++;
  61190. }
  61191. // cap
  61192. var capPath = function (shapePath) {
  61193. var pointCap = Array();
  61194. var barycenter = BABYLON.Vector3.Zero();
  61195. var i;
  61196. for (i = 0; i < shapePath.length; i++) {
  61197. barycenter.addInPlace(shapePath[i]);
  61198. }
  61199. barycenter.scaleInPlace(1.0 / shapePath.length);
  61200. for (i = 0; i < shapePath.length; i++) {
  61201. pointCap.push(barycenter);
  61202. }
  61203. return pointCap;
  61204. };
  61205. switch (cap) {
  61206. case BABYLON.Mesh.NO_CAP:
  61207. break;
  61208. case BABYLON.Mesh.CAP_START:
  61209. shapePaths[0] = capPath(shapePaths[2]);
  61210. shapePaths[1] = shapePaths[2];
  61211. break;
  61212. case BABYLON.Mesh.CAP_END:
  61213. shapePaths[index] = shapePaths[index - 1];
  61214. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61215. break;
  61216. case BABYLON.Mesh.CAP_ALL:
  61217. shapePaths[0] = capPath(shapePaths[2]);
  61218. shapePaths[1] = shapePaths[2];
  61219. shapePaths[index] = shapePaths[index - 1];
  61220. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61221. break;
  61222. default:
  61223. break;
  61224. }
  61225. return shapePaths;
  61226. };
  61227. var path3D;
  61228. var pathArray;
  61229. if (instance) { // instance update
  61230. path3D = (instance.path3D).update(curve);
  61231. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61232. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61233. return instance;
  61234. }
  61235. // extruded shape creation
  61236. path3D = new BABYLON.Path3D(curve);
  61237. var newShapePaths = new Array();
  61238. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61239. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61240. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61241. extrudedGeneric.pathArray = pathArray;
  61242. extrudedGeneric.path3D = path3D;
  61243. extrudedGeneric.cap = cap;
  61244. return extrudedGeneric;
  61245. };
  61246. return MeshBuilder;
  61247. }());
  61248. BABYLON.MeshBuilder = MeshBuilder;
  61249. })(BABYLON || (BABYLON = {}));
  61250. //# sourceMappingURL=babylon.meshBuilder.js.map
  61251. var BABYLON;
  61252. (function (BABYLON) {
  61253. /**
  61254. * Draco compression (https://google.github.io/draco/)
  61255. */
  61256. var DracoCompression = /** @class */ (function () {
  61257. /**
  61258. * Constructor
  61259. */
  61260. function DracoCompression() {
  61261. }
  61262. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61263. /**
  61264. * Returns true if the decoder is available.
  61265. */
  61266. get: function () {
  61267. if (typeof DracoDecoderModule !== "undefined") {
  61268. return true;
  61269. }
  61270. var decoder = DracoCompression.Configuration.decoder;
  61271. if (decoder) {
  61272. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61273. return true;
  61274. }
  61275. if (decoder.fallbackUrl) {
  61276. return true;
  61277. }
  61278. }
  61279. return false;
  61280. },
  61281. enumerable: true,
  61282. configurable: true
  61283. });
  61284. /**
  61285. * Stop all async operations and release resources.
  61286. */
  61287. DracoCompression.prototype.dispose = function () {
  61288. };
  61289. /**
  61290. * Decode Draco compressed mesh data to vertex data.
  61291. * @param data The array buffer view for the Draco compression data
  61292. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61293. * @returns A promise that resolves with the decoded vertex data
  61294. */
  61295. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61296. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61297. var module = wrappedModule.module;
  61298. var vertexData = new BABYLON.VertexData();
  61299. var buffer = new module.DecoderBuffer();
  61300. buffer.Init(data, data.byteLength);
  61301. var decoder = new module.Decoder();
  61302. var geometry;
  61303. var status;
  61304. try {
  61305. var type = decoder.GetEncodedGeometryType(buffer);
  61306. switch (type) {
  61307. case module.TRIANGULAR_MESH:
  61308. geometry = new module.Mesh();
  61309. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61310. break;
  61311. case module.POINT_CLOUD:
  61312. geometry = new module.PointCloud();
  61313. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61314. break;
  61315. default:
  61316. throw new Error("Invalid geometry type " + type);
  61317. }
  61318. if (!status.ok() || !geometry.ptr) {
  61319. throw new Error(status.error_msg());
  61320. }
  61321. var numPoints = geometry.num_points();
  61322. if (type === module.TRIANGULAR_MESH) {
  61323. var numFaces = geometry.num_faces();
  61324. var faceIndices = new module.DracoInt32Array();
  61325. try {
  61326. var indices = new Uint32Array(numFaces * 3);
  61327. for (var i = 0; i < numFaces; i++) {
  61328. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61329. var offset = i * 3;
  61330. indices[offset + 0] = faceIndices.GetValue(0);
  61331. indices[offset + 1] = faceIndices.GetValue(1);
  61332. indices[offset + 2] = faceIndices.GetValue(2);
  61333. }
  61334. vertexData.indices = indices;
  61335. }
  61336. finally {
  61337. module.destroy(faceIndices);
  61338. }
  61339. }
  61340. for (var kind in attributes) {
  61341. var uniqueId = attributes[kind];
  61342. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61343. var dracoData = new module.DracoFloat32Array();
  61344. try {
  61345. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61346. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61347. for (var i = 0; i < babylonData.length; i++) {
  61348. babylonData[i] = dracoData.GetValue(i);
  61349. }
  61350. vertexData.set(babylonData, kind);
  61351. }
  61352. finally {
  61353. module.destroy(dracoData);
  61354. }
  61355. }
  61356. }
  61357. finally {
  61358. if (geometry) {
  61359. module.destroy(geometry);
  61360. }
  61361. module.destroy(decoder);
  61362. module.destroy(buffer);
  61363. }
  61364. return vertexData;
  61365. });
  61366. };
  61367. DracoCompression._GetDecoderModule = function () {
  61368. if (!DracoCompression._DecoderModulePromise) {
  61369. var promise = null;
  61370. var config_1 = {};
  61371. if (typeof DracoDecoderModule !== "undefined") {
  61372. promise = Promise.resolve();
  61373. }
  61374. else {
  61375. var decoder = DracoCompression.Configuration.decoder;
  61376. if (decoder) {
  61377. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61378. promise = Promise.all([
  61379. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61380. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61381. config_1.wasmBinary = data;
  61382. })
  61383. ]);
  61384. }
  61385. else if (decoder.fallbackUrl) {
  61386. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61387. }
  61388. }
  61389. }
  61390. if (!promise) {
  61391. throw new Error("Draco decoder module is not available");
  61392. }
  61393. DracoCompression._DecoderModulePromise = promise.then(function () {
  61394. return new Promise(function (resolve) {
  61395. config_1.onModuleLoaded = function (decoderModule) {
  61396. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61397. resolve({ module: decoderModule });
  61398. };
  61399. DracoDecoderModule(config_1);
  61400. });
  61401. });
  61402. }
  61403. return DracoCompression._DecoderModulePromise;
  61404. };
  61405. DracoCompression._LoadScriptAsync = function (url) {
  61406. return new Promise(function (resolve, reject) {
  61407. BABYLON.Tools.LoadScript(url, function () {
  61408. resolve();
  61409. }, function (message) {
  61410. reject(new Error(message));
  61411. });
  61412. });
  61413. };
  61414. DracoCompression._LoadFileAsync = function (url) {
  61415. return new Promise(function (resolve, reject) {
  61416. BABYLON.Tools.LoadFile(url, function (data) {
  61417. resolve(data);
  61418. }, undefined, undefined, true, function (request, exception) {
  61419. reject(exception);
  61420. });
  61421. });
  61422. };
  61423. /**
  61424. * The configuration.
  61425. */
  61426. DracoCompression.Configuration = {
  61427. decoder: {
  61428. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61429. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61430. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61431. }
  61432. };
  61433. return DracoCompression;
  61434. }());
  61435. BABYLON.DracoCompression = DracoCompression;
  61436. })(BABYLON || (BABYLON = {}));
  61437. //# sourceMappingURL=babylon.dracoCompression.js.map
  61438. var BABYLON;
  61439. (function (BABYLON) {
  61440. var AudioEngine = /** @class */ (function () {
  61441. function AudioEngine() {
  61442. this._audioContext = null;
  61443. this._audioContextInitialized = false;
  61444. this.canUseWebAudio = false;
  61445. this.WarnedWebAudioUnsupported = false;
  61446. this.unlocked = false;
  61447. this.isMP3supported = false;
  61448. this.isOGGsupported = false;
  61449. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61450. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61451. this.canUseWebAudio = true;
  61452. }
  61453. var audioElem = document.createElement('audio');
  61454. try {
  61455. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61456. this.isMP3supported = true;
  61457. }
  61458. }
  61459. catch (e) {
  61460. // protect error during capability check.
  61461. }
  61462. try {
  61463. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61464. this.isOGGsupported = true;
  61465. }
  61466. }
  61467. catch (e) {
  61468. // protect error during capability check.
  61469. }
  61470. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61471. this._unlockiOSaudio();
  61472. }
  61473. else {
  61474. this.unlocked = true;
  61475. }
  61476. }
  61477. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61478. get: function () {
  61479. if (!this._audioContextInitialized) {
  61480. this._initializeAudioContext();
  61481. }
  61482. return this._audioContext;
  61483. },
  61484. enumerable: true,
  61485. configurable: true
  61486. });
  61487. AudioEngine.prototype._unlockiOSaudio = function () {
  61488. var _this = this;
  61489. var unlockaudio = function () {
  61490. if (!_this.audioContext) {
  61491. return;
  61492. }
  61493. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61494. var source = _this.audioContext.createBufferSource();
  61495. source.buffer = buffer;
  61496. source.connect(_this.audioContext.destination);
  61497. source.start(0);
  61498. setTimeout(function () {
  61499. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61500. _this.unlocked = true;
  61501. window.removeEventListener('touchend', unlockaudio, false);
  61502. if (_this.onAudioUnlocked) {
  61503. _this.onAudioUnlocked();
  61504. }
  61505. }
  61506. }, 0);
  61507. };
  61508. window.addEventListener('touchend', unlockaudio, false);
  61509. };
  61510. AudioEngine.prototype._initializeAudioContext = function () {
  61511. try {
  61512. if (this.canUseWebAudio) {
  61513. this._audioContext = new AudioContext();
  61514. // create a global volume gain node
  61515. this.masterGain = this._audioContext.createGain();
  61516. this.masterGain.gain.value = 1;
  61517. this.masterGain.connect(this._audioContext.destination);
  61518. this._audioContextInitialized = true;
  61519. }
  61520. }
  61521. catch (e) {
  61522. this.canUseWebAudio = false;
  61523. BABYLON.Tools.Error("Web Audio: " + e.message);
  61524. }
  61525. };
  61526. AudioEngine.prototype.dispose = function () {
  61527. if (this.canUseWebAudio && this._audioContextInitialized) {
  61528. if (this._connectedAnalyser && this._audioContext) {
  61529. this._connectedAnalyser.stopDebugCanvas();
  61530. this._connectedAnalyser.dispose();
  61531. this.masterGain.disconnect();
  61532. this.masterGain.connect(this._audioContext.destination);
  61533. this._connectedAnalyser = null;
  61534. }
  61535. this.masterGain.gain.value = 1;
  61536. }
  61537. this.WarnedWebAudioUnsupported = false;
  61538. };
  61539. AudioEngine.prototype.getGlobalVolume = function () {
  61540. if (this.canUseWebAudio && this._audioContextInitialized) {
  61541. return this.masterGain.gain.value;
  61542. }
  61543. else {
  61544. return -1;
  61545. }
  61546. };
  61547. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61548. if (this.canUseWebAudio && this._audioContextInitialized) {
  61549. this.masterGain.gain.value = newVolume;
  61550. }
  61551. };
  61552. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61553. if (this._connectedAnalyser) {
  61554. this._connectedAnalyser.stopDebugCanvas();
  61555. }
  61556. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61557. this._connectedAnalyser = analyser;
  61558. this.masterGain.disconnect();
  61559. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61560. }
  61561. };
  61562. return AudioEngine;
  61563. }());
  61564. BABYLON.AudioEngine = AudioEngine;
  61565. })(BABYLON || (BABYLON = {}));
  61566. //# sourceMappingURL=babylon.audioEngine.js.map
  61567. var BABYLON;
  61568. (function (BABYLON) {
  61569. var Sound = /** @class */ (function () {
  61570. /**
  61571. * Create a sound and attach it to a scene
  61572. * @param name Name of your sound
  61573. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61574. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61575. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61576. */
  61577. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61578. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61579. var _this = this;
  61580. this.autoplay = false;
  61581. this.loop = false;
  61582. this.useCustomAttenuation = false;
  61583. this.spatialSound = false;
  61584. this.refDistance = 1;
  61585. this.rolloffFactor = 1;
  61586. this.maxDistance = 100;
  61587. this.distanceModel = "linear";
  61588. this._panningModel = "equalpower";
  61589. this._playbackRate = 1;
  61590. this._streaming = false;
  61591. this._startTime = 0;
  61592. this._startOffset = 0;
  61593. this._position = BABYLON.Vector3.Zero();
  61594. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61595. this._volume = 1;
  61596. this._isReadyToPlay = false;
  61597. this.isPlaying = false;
  61598. this.isPaused = false;
  61599. this._isDirectional = false;
  61600. // Used if you'd like to create a directional sound.
  61601. // If not set, the sound will be omnidirectional
  61602. this._coneInnerAngle = 360;
  61603. this._coneOuterAngle = 360;
  61604. this._coneOuterGain = 0;
  61605. this._isOutputConnected = false;
  61606. this._urlType = "Unknown";
  61607. this.name = name;
  61608. this._scene = scene;
  61609. this._readyToPlayCallback = readyToPlayCallback;
  61610. // Default custom attenuation function is a linear attenuation
  61611. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61612. if (currentDistance < maxDistance) {
  61613. return currentVolume * (1 - currentDistance / maxDistance);
  61614. }
  61615. else {
  61616. return 0;
  61617. }
  61618. };
  61619. if (options) {
  61620. this.autoplay = options.autoplay || false;
  61621. this.loop = options.loop || false;
  61622. // if volume === 0, we need another way to check this option
  61623. if (options.volume !== undefined) {
  61624. this._volume = options.volume;
  61625. }
  61626. this.spatialSound = options.spatialSound || false;
  61627. this.maxDistance = options.maxDistance || 100;
  61628. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61629. this.rolloffFactor = options.rolloffFactor || 1;
  61630. this.refDistance = options.refDistance || 1;
  61631. this.distanceModel = options.distanceModel || "linear";
  61632. this._playbackRate = options.playbackRate || 1;
  61633. this._streaming = options.streaming || false;
  61634. }
  61635. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61636. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61637. this._soundGain.gain.value = this._volume;
  61638. this._inputAudioNode = this._soundGain;
  61639. this._ouputAudioNode = this._soundGain;
  61640. if (this.spatialSound) {
  61641. this._createSpatialParameters();
  61642. }
  61643. this._scene.mainSoundTrack.AddSound(this);
  61644. var validParameter = true;
  61645. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61646. if (urlOrArrayBuffer) {
  61647. try {
  61648. if (typeof (urlOrArrayBuffer) === "string")
  61649. this._urlType = "String";
  61650. if (Array.isArray(urlOrArrayBuffer))
  61651. this._urlType = "Array";
  61652. if (urlOrArrayBuffer instanceof ArrayBuffer)
  61653. this._urlType = "ArrayBuffer";
  61654. var urls = [];
  61655. var codecSupportedFound = false;
  61656. switch (this._urlType) {
  61657. case "ArrayBuffer":
  61658. if (urlOrArrayBuffer.byteLength > 0) {
  61659. codecSupportedFound = true;
  61660. this._soundLoaded(urlOrArrayBuffer);
  61661. }
  61662. break;
  61663. case "String":
  61664. urls.push(urlOrArrayBuffer);
  61665. case "Array":
  61666. if (urls.length === 0)
  61667. urls = urlOrArrayBuffer;
  61668. // If we found a supported format, we load it immediately and stop the loop
  61669. for (var i = 0; i < urls.length; i++) {
  61670. var url = urls[i];
  61671. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  61672. codecSupportedFound = true;
  61673. }
  61674. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  61675. codecSupportedFound = true;
  61676. }
  61677. if (url.indexOf(".wav", url.length - 4) !== -1) {
  61678. codecSupportedFound = true;
  61679. }
  61680. if (url.indexOf("blob:") !== -1) {
  61681. codecSupportedFound = true;
  61682. }
  61683. if (codecSupportedFound) {
  61684. // Loading sound using XHR2
  61685. if (!this._streaming) {
  61686. this._scene._loadFile(url, function (data) {
  61687. _this._soundLoaded(data);
  61688. }, undefined, true, true, function (exception) {
  61689. if (exception) {
  61690. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  61691. }
  61692. BABYLON.Tools.Error("Sound creation aborted.");
  61693. _this._scene.mainSoundTrack.RemoveSound(_this);
  61694. });
  61695. }
  61696. // Streaming sound using HTML5 Audio tag
  61697. else {
  61698. this._htmlAudioElement = new Audio(url);
  61699. this._htmlAudioElement.controls = false;
  61700. this._htmlAudioElement.loop = this.loop;
  61701. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  61702. this._htmlAudioElement.preload = "auto";
  61703. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  61704. _this._isReadyToPlay = true;
  61705. if (_this.autoplay) {
  61706. _this.play();
  61707. }
  61708. if (_this._readyToPlayCallback) {
  61709. _this._readyToPlayCallback();
  61710. }
  61711. });
  61712. document.body.appendChild(this._htmlAudioElement);
  61713. }
  61714. break;
  61715. }
  61716. }
  61717. break;
  61718. default:
  61719. validParameter = false;
  61720. break;
  61721. }
  61722. if (!validParameter) {
  61723. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  61724. }
  61725. else {
  61726. if (!codecSupportedFound) {
  61727. this._isReadyToPlay = true;
  61728. // Simulating a ready to play event to avoid breaking code path
  61729. if (this._readyToPlayCallback) {
  61730. window.setTimeout(function () {
  61731. if (_this._readyToPlayCallback) {
  61732. _this._readyToPlayCallback();
  61733. }
  61734. }, 1000);
  61735. }
  61736. }
  61737. }
  61738. }
  61739. catch (ex) {
  61740. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  61741. this._scene.mainSoundTrack.RemoveSound(this);
  61742. }
  61743. }
  61744. }
  61745. else {
  61746. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  61747. this._scene.mainSoundTrack.AddSound(this);
  61748. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  61749. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  61750. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  61751. }
  61752. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  61753. if (this._readyToPlayCallback) {
  61754. window.setTimeout(function () {
  61755. if (_this._readyToPlayCallback) {
  61756. _this._readyToPlayCallback();
  61757. }
  61758. }, 1000);
  61759. }
  61760. }
  61761. }
  61762. Sound.prototype.dispose = function () {
  61763. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61764. if (this.isPlaying) {
  61765. this.stop();
  61766. }
  61767. this._isReadyToPlay = false;
  61768. if (this.soundTrackId === -1) {
  61769. this._scene.mainSoundTrack.RemoveSound(this);
  61770. }
  61771. else {
  61772. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  61773. }
  61774. if (this._soundGain) {
  61775. this._soundGain.disconnect();
  61776. this._soundGain = null;
  61777. }
  61778. if (this._soundPanner) {
  61779. this._soundPanner.disconnect();
  61780. this._soundPanner = null;
  61781. }
  61782. if (this._soundSource) {
  61783. this._soundSource.disconnect();
  61784. this._soundSource = null;
  61785. }
  61786. this._audioBuffer = null;
  61787. if (this._htmlAudioElement) {
  61788. this._htmlAudioElement.pause();
  61789. this._htmlAudioElement.src = "";
  61790. document.body.removeChild(this._htmlAudioElement);
  61791. }
  61792. if (this._connectedMesh && this._registerFunc) {
  61793. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  61794. this._connectedMesh = null;
  61795. }
  61796. }
  61797. };
  61798. Sound.prototype.isReady = function () {
  61799. return this._isReadyToPlay;
  61800. };
  61801. Sound.prototype._soundLoaded = function (audioData) {
  61802. var _this = this;
  61803. if (!BABYLON.Engine.audioEngine.audioContext) {
  61804. return;
  61805. }
  61806. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  61807. _this._audioBuffer = buffer;
  61808. _this._isReadyToPlay = true;
  61809. if (_this.autoplay) {
  61810. _this.play();
  61811. }
  61812. if (_this._readyToPlayCallback) {
  61813. _this._readyToPlayCallback();
  61814. }
  61815. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  61816. };
  61817. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  61818. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61819. this._audioBuffer = audioBuffer;
  61820. this._isReadyToPlay = true;
  61821. }
  61822. };
  61823. Sound.prototype.updateOptions = function (options) {
  61824. if (options) {
  61825. this.loop = options.loop || this.loop;
  61826. this.maxDistance = options.maxDistance || this.maxDistance;
  61827. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  61828. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  61829. this.refDistance = options.refDistance || this.refDistance;
  61830. this.distanceModel = options.distanceModel || this.distanceModel;
  61831. this._playbackRate = options.playbackRate || this._playbackRate;
  61832. this._updateSpatialParameters();
  61833. if (this.isPlaying) {
  61834. if (this._streaming) {
  61835. this._htmlAudioElement.playbackRate = this._playbackRate;
  61836. }
  61837. else {
  61838. if (this._soundSource) {
  61839. this._soundSource.playbackRate.value = this._playbackRate;
  61840. }
  61841. }
  61842. }
  61843. }
  61844. };
  61845. Sound.prototype._createSpatialParameters = function () {
  61846. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61847. if (this._scene.headphone) {
  61848. this._panningModel = "HRTF";
  61849. }
  61850. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  61851. this._updateSpatialParameters();
  61852. this._soundPanner.connect(this._ouputAudioNode);
  61853. this._inputAudioNode = this._soundPanner;
  61854. }
  61855. };
  61856. Sound.prototype._updateSpatialParameters = function () {
  61857. if (this.spatialSound && this._soundPanner) {
  61858. if (this.useCustomAttenuation) {
  61859. // Tricks to disable in a way embedded Web Audio attenuation
  61860. this._soundPanner.distanceModel = "linear";
  61861. this._soundPanner.maxDistance = Number.MAX_VALUE;
  61862. this._soundPanner.refDistance = 1;
  61863. this._soundPanner.rolloffFactor = 1;
  61864. this._soundPanner.panningModel = this._panningModel;
  61865. }
  61866. else {
  61867. this._soundPanner.distanceModel = this.distanceModel;
  61868. this._soundPanner.maxDistance = this.maxDistance;
  61869. this._soundPanner.refDistance = this.refDistance;
  61870. this._soundPanner.rolloffFactor = this.rolloffFactor;
  61871. this._soundPanner.panningModel = this._panningModel;
  61872. }
  61873. }
  61874. };
  61875. Sound.prototype.switchPanningModelToHRTF = function () {
  61876. this._panningModel = "HRTF";
  61877. this._switchPanningModel();
  61878. };
  61879. Sound.prototype.switchPanningModelToEqualPower = function () {
  61880. this._panningModel = "equalpower";
  61881. this._switchPanningModel();
  61882. };
  61883. Sound.prototype._switchPanningModel = function () {
  61884. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61885. this._soundPanner.panningModel = this._panningModel;
  61886. }
  61887. };
  61888. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  61889. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61890. if (this._isOutputConnected) {
  61891. this._ouputAudioNode.disconnect();
  61892. }
  61893. this._ouputAudioNode.connect(soundTrackAudioNode);
  61894. this._isOutputConnected = true;
  61895. }
  61896. };
  61897. /**
  61898. * Transform this sound into a directional source
  61899. * @param coneInnerAngle Size of the inner cone in degree
  61900. * @param coneOuterAngle Size of the outer cone in degree
  61901. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  61902. */
  61903. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  61904. if (coneOuterAngle < coneInnerAngle) {
  61905. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  61906. return;
  61907. }
  61908. this._coneInnerAngle = coneInnerAngle;
  61909. this._coneOuterAngle = coneOuterAngle;
  61910. this._coneOuterGain = coneOuterGain;
  61911. this._isDirectional = true;
  61912. if (this.isPlaying && this.loop) {
  61913. this.stop();
  61914. this.play();
  61915. }
  61916. };
  61917. Sound.prototype.setPosition = function (newPosition) {
  61918. this._position = newPosition;
  61919. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  61920. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61921. }
  61922. };
  61923. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  61924. this._localDirection = newLocalDirection;
  61925. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  61926. this._updateDirection();
  61927. }
  61928. };
  61929. Sound.prototype._updateDirection = function () {
  61930. if (!this._connectedMesh || !this._soundPanner) {
  61931. return;
  61932. }
  61933. var mat = this._connectedMesh.getWorldMatrix();
  61934. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  61935. direction.normalize();
  61936. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  61937. };
  61938. Sound.prototype.updateDistanceFromListener = function () {
  61939. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  61940. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  61941. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  61942. }
  61943. };
  61944. Sound.prototype.setAttenuationFunction = function (callback) {
  61945. this._customAttenuationFunction = callback;
  61946. };
  61947. /**
  61948. * Play the sound
  61949. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  61950. * @param offset (optional) Start the sound setting it at a specific time
  61951. */
  61952. Sound.prototype.play = function (time, offset) {
  61953. var _this = this;
  61954. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  61955. try {
  61956. if (this._startOffset < 0) {
  61957. time = -this._startOffset;
  61958. this._startOffset = 0;
  61959. }
  61960. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  61961. if (!this._soundSource || !this._streamingSource) {
  61962. if (this.spatialSound && this._soundPanner) {
  61963. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  61964. if (this._isDirectional) {
  61965. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  61966. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  61967. this._soundPanner.coneOuterGain = this._coneOuterGain;
  61968. if (this._connectedMesh) {
  61969. this._updateDirection();
  61970. }
  61971. else {
  61972. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  61973. }
  61974. }
  61975. }
  61976. }
  61977. if (this._streaming) {
  61978. if (!this._streamingSource) {
  61979. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  61980. this._htmlAudioElement.onended = function () { _this._onended(); };
  61981. this._htmlAudioElement.playbackRate = this._playbackRate;
  61982. }
  61983. this._streamingSource.disconnect();
  61984. this._streamingSource.connect(this._inputAudioNode);
  61985. this._htmlAudioElement.play();
  61986. }
  61987. else {
  61988. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  61989. this._soundSource.buffer = this._audioBuffer;
  61990. this._soundSource.connect(this._inputAudioNode);
  61991. this._soundSource.loop = this.loop;
  61992. this._soundSource.playbackRate.value = this._playbackRate;
  61993. this._soundSource.onended = function () { _this._onended(); };
  61994. if (this._soundSource.buffer) {
  61995. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  61996. }
  61997. }
  61998. this._startTime = startTime;
  61999. this.isPlaying = true;
  62000. this.isPaused = false;
  62001. }
  62002. catch (ex) {
  62003. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62004. }
  62005. }
  62006. };
  62007. Sound.prototype._onended = function () {
  62008. this.isPlaying = false;
  62009. if (this.onended) {
  62010. this.onended();
  62011. }
  62012. };
  62013. /**
  62014. * Stop the sound
  62015. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62016. */
  62017. Sound.prototype.stop = function (time) {
  62018. if (this.isPlaying) {
  62019. if (this._streaming) {
  62020. this._htmlAudioElement.pause();
  62021. // Test needed for Firefox or it will generate an Invalid State Error
  62022. if (this._htmlAudioElement.currentTime > 0) {
  62023. this._htmlAudioElement.currentTime = 0;
  62024. }
  62025. }
  62026. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62027. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62028. this._soundSource.stop(stopTime);
  62029. this._soundSource.onended = function () { };
  62030. if (!this.isPaused) {
  62031. this._startOffset = 0;
  62032. }
  62033. }
  62034. this.isPlaying = false;
  62035. }
  62036. };
  62037. Sound.prototype.pause = function () {
  62038. if (this.isPlaying) {
  62039. this.isPaused = true;
  62040. if (this._streaming) {
  62041. this._htmlAudioElement.pause();
  62042. }
  62043. else if (BABYLON.Engine.audioEngine.audioContext) {
  62044. this.stop(0);
  62045. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62046. }
  62047. }
  62048. };
  62049. Sound.prototype.setVolume = function (newVolume, time) {
  62050. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62051. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62052. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62053. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62054. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62055. }
  62056. else {
  62057. this._soundGain.gain.value = newVolume;
  62058. }
  62059. }
  62060. this._volume = newVolume;
  62061. };
  62062. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62063. this._playbackRate = newPlaybackRate;
  62064. if (this.isPlaying) {
  62065. if (this._streaming) {
  62066. this._htmlAudioElement.playbackRate = this._playbackRate;
  62067. }
  62068. else if (this._soundSource) {
  62069. this._soundSource.playbackRate.value = this._playbackRate;
  62070. }
  62071. }
  62072. };
  62073. Sound.prototype.getVolume = function () {
  62074. return this._volume;
  62075. };
  62076. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62077. var _this = this;
  62078. if (this._connectedMesh && this._registerFunc) {
  62079. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62080. this._registerFunc = null;
  62081. }
  62082. this._connectedMesh = meshToConnectTo;
  62083. if (!this.spatialSound) {
  62084. this.spatialSound = true;
  62085. this._createSpatialParameters();
  62086. if (this.isPlaying && this.loop) {
  62087. this.stop();
  62088. this.play();
  62089. }
  62090. }
  62091. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62092. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62093. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62094. };
  62095. Sound.prototype.detachFromMesh = function () {
  62096. if (this._connectedMesh && this._registerFunc) {
  62097. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62098. this._registerFunc = null;
  62099. this._connectedMesh = null;
  62100. }
  62101. };
  62102. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62103. if (!node.getBoundingInfo) {
  62104. return;
  62105. }
  62106. var mesh = node;
  62107. var boundingInfo = mesh.getBoundingInfo();
  62108. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62109. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62110. this._updateDirection();
  62111. }
  62112. };
  62113. Sound.prototype.clone = function () {
  62114. var _this = this;
  62115. if (!this._streaming) {
  62116. var setBufferAndRun = function () {
  62117. if (_this._isReadyToPlay) {
  62118. clonedSound._audioBuffer = _this.getAudioBuffer();
  62119. clonedSound._isReadyToPlay = true;
  62120. if (clonedSound.autoplay) {
  62121. clonedSound.play();
  62122. }
  62123. }
  62124. else {
  62125. window.setTimeout(setBufferAndRun, 300);
  62126. }
  62127. };
  62128. var currentOptions = {
  62129. autoplay: this.autoplay, loop: this.loop,
  62130. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62131. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62132. refDistance: this.refDistance, distanceModel: this.distanceModel
  62133. };
  62134. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62135. if (this.useCustomAttenuation) {
  62136. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62137. }
  62138. clonedSound.setPosition(this._position);
  62139. clonedSound.setPlaybackRate(this._playbackRate);
  62140. setBufferAndRun();
  62141. return clonedSound;
  62142. }
  62143. // Can't clone a streaming sound
  62144. else {
  62145. return null;
  62146. }
  62147. };
  62148. Sound.prototype.getAudioBuffer = function () {
  62149. return this._audioBuffer;
  62150. };
  62151. Sound.prototype.serialize = function () {
  62152. var serializationObject = {
  62153. name: this.name,
  62154. url: this.name,
  62155. autoplay: this.autoplay,
  62156. loop: this.loop,
  62157. volume: this._volume,
  62158. spatialSound: this.spatialSound,
  62159. maxDistance: this.maxDistance,
  62160. rolloffFactor: this.rolloffFactor,
  62161. refDistance: this.refDistance,
  62162. distanceModel: this.distanceModel,
  62163. playbackRate: this._playbackRate,
  62164. panningModel: this._panningModel,
  62165. soundTrackId: this.soundTrackId
  62166. };
  62167. if (this.spatialSound) {
  62168. if (this._connectedMesh)
  62169. serializationObject.connectedMeshId = this._connectedMesh.id;
  62170. serializationObject.position = this._position.asArray();
  62171. serializationObject.refDistance = this.refDistance;
  62172. serializationObject.distanceModel = this.distanceModel;
  62173. serializationObject.isDirectional = this._isDirectional;
  62174. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62175. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62176. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62177. serializationObject.coneOuterGain = this._coneOuterGain;
  62178. }
  62179. return serializationObject;
  62180. };
  62181. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62182. var soundName = parsedSound.name;
  62183. var soundUrl;
  62184. if (parsedSound.url) {
  62185. soundUrl = rootUrl + parsedSound.url;
  62186. }
  62187. else {
  62188. soundUrl = rootUrl + soundName;
  62189. }
  62190. var options = {
  62191. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62192. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62193. rolloffFactor: parsedSound.rolloffFactor,
  62194. refDistance: parsedSound.refDistance,
  62195. distanceModel: parsedSound.distanceModel,
  62196. playbackRate: parsedSound.playbackRate
  62197. };
  62198. var newSound;
  62199. if (!sourceSound) {
  62200. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62201. scene._addPendingData(newSound);
  62202. }
  62203. else {
  62204. var setBufferAndRun = function () {
  62205. if (sourceSound._isReadyToPlay) {
  62206. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62207. newSound._isReadyToPlay = true;
  62208. if (newSound.autoplay) {
  62209. newSound.play();
  62210. }
  62211. }
  62212. else {
  62213. window.setTimeout(setBufferAndRun, 300);
  62214. }
  62215. };
  62216. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62217. setBufferAndRun();
  62218. }
  62219. if (parsedSound.position) {
  62220. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62221. newSound.setPosition(soundPosition);
  62222. }
  62223. if (parsedSound.isDirectional) {
  62224. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62225. if (parsedSound.localDirectionToMesh) {
  62226. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62227. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62228. }
  62229. }
  62230. if (parsedSound.connectedMeshId) {
  62231. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62232. if (connectedMesh) {
  62233. newSound.attachToMesh(connectedMesh);
  62234. }
  62235. }
  62236. return newSound;
  62237. };
  62238. return Sound;
  62239. }());
  62240. BABYLON.Sound = Sound;
  62241. })(BABYLON || (BABYLON = {}));
  62242. //# sourceMappingURL=babylon.sound.js.map
  62243. var BABYLON;
  62244. (function (BABYLON) {
  62245. var SoundTrack = /** @class */ (function () {
  62246. function SoundTrack(scene, options) {
  62247. this.id = -1;
  62248. this._isMainTrack = false;
  62249. this._isInitialized = false;
  62250. this._scene = scene;
  62251. this.soundCollection = new Array();
  62252. this._options = options;
  62253. if (!this._isMainTrack) {
  62254. this._scene.soundTracks.push(this);
  62255. this.id = this._scene.soundTracks.length - 1;
  62256. }
  62257. }
  62258. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62259. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62260. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62261. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62262. if (this._options) {
  62263. if (this._options.volume) {
  62264. this._outputAudioNode.gain.value = this._options.volume;
  62265. }
  62266. if (this._options.mainTrack) {
  62267. this._isMainTrack = this._options.mainTrack;
  62268. }
  62269. }
  62270. this._isInitialized = true;
  62271. }
  62272. };
  62273. SoundTrack.prototype.dispose = function () {
  62274. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62275. if (this._connectedAnalyser) {
  62276. this._connectedAnalyser.stopDebugCanvas();
  62277. }
  62278. while (this.soundCollection.length) {
  62279. this.soundCollection[0].dispose();
  62280. }
  62281. if (this._outputAudioNode) {
  62282. this._outputAudioNode.disconnect();
  62283. }
  62284. this._outputAudioNode = null;
  62285. }
  62286. };
  62287. SoundTrack.prototype.AddSound = function (sound) {
  62288. if (!this._isInitialized) {
  62289. this._initializeSoundTrackAudioGraph();
  62290. }
  62291. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62292. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62293. }
  62294. if (sound.soundTrackId) {
  62295. if (sound.soundTrackId === -1) {
  62296. this._scene.mainSoundTrack.RemoveSound(sound);
  62297. }
  62298. else {
  62299. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62300. }
  62301. }
  62302. this.soundCollection.push(sound);
  62303. sound.soundTrackId = this.id;
  62304. };
  62305. SoundTrack.prototype.RemoveSound = function (sound) {
  62306. var index = this.soundCollection.indexOf(sound);
  62307. if (index !== -1) {
  62308. this.soundCollection.splice(index, 1);
  62309. }
  62310. };
  62311. SoundTrack.prototype.setVolume = function (newVolume) {
  62312. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62313. this._outputAudioNode.gain.value = newVolume;
  62314. }
  62315. };
  62316. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62317. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62318. for (var i = 0; i < this.soundCollection.length; i++) {
  62319. this.soundCollection[i].switchPanningModelToHRTF();
  62320. }
  62321. }
  62322. };
  62323. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62324. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62325. for (var i = 0; i < this.soundCollection.length; i++) {
  62326. this.soundCollection[i].switchPanningModelToEqualPower();
  62327. }
  62328. }
  62329. };
  62330. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62331. if (this._connectedAnalyser) {
  62332. this._connectedAnalyser.stopDebugCanvas();
  62333. }
  62334. this._connectedAnalyser = analyser;
  62335. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62336. this._outputAudioNode.disconnect();
  62337. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62338. }
  62339. };
  62340. return SoundTrack;
  62341. }());
  62342. BABYLON.SoundTrack = SoundTrack;
  62343. })(BABYLON || (BABYLON = {}));
  62344. //# sourceMappingURL=babylon.soundtrack.js.map
  62345. var BABYLON;
  62346. (function (BABYLON) {
  62347. var Analyser = /** @class */ (function () {
  62348. function Analyser(scene) {
  62349. this.SMOOTHING = 0.75;
  62350. this.FFT_SIZE = 512;
  62351. this.BARGRAPHAMPLITUDE = 256;
  62352. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62353. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62354. this._scene = scene;
  62355. this._audioEngine = BABYLON.Engine.audioEngine;
  62356. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62357. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62358. this._webAudioAnalyser.minDecibels = -140;
  62359. this._webAudioAnalyser.maxDecibels = 0;
  62360. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62361. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62362. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62363. }
  62364. }
  62365. Analyser.prototype.getFrequencyBinCount = function () {
  62366. if (this._audioEngine.canUseWebAudio) {
  62367. return this._webAudioAnalyser.frequencyBinCount;
  62368. }
  62369. else {
  62370. return 0;
  62371. }
  62372. };
  62373. Analyser.prototype.getByteFrequencyData = function () {
  62374. if (this._audioEngine.canUseWebAudio) {
  62375. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62376. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62377. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62378. }
  62379. return this._byteFreqs;
  62380. };
  62381. Analyser.prototype.getByteTimeDomainData = function () {
  62382. if (this._audioEngine.canUseWebAudio) {
  62383. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62384. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62385. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62386. }
  62387. return this._byteTime;
  62388. };
  62389. Analyser.prototype.getFloatFrequencyData = function () {
  62390. if (this._audioEngine.canUseWebAudio) {
  62391. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62392. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62393. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62394. }
  62395. return this._floatFreqs;
  62396. };
  62397. Analyser.prototype.drawDebugCanvas = function () {
  62398. var _this = this;
  62399. if (this._audioEngine.canUseWebAudio) {
  62400. if (!this._debugCanvas) {
  62401. this._debugCanvas = document.createElement("canvas");
  62402. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62403. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62404. this._debugCanvas.style.position = "absolute";
  62405. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62406. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62407. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62408. document.body.appendChild(this._debugCanvas);
  62409. this._registerFunc = function () {
  62410. _this.drawDebugCanvas();
  62411. };
  62412. this._scene.registerBeforeRender(this._registerFunc);
  62413. }
  62414. if (this._registerFunc && this._debugCanvasContext) {
  62415. var workingArray = this.getByteFrequencyData();
  62416. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62417. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62418. // Draw the frequency domain chart.
  62419. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62420. var value = workingArray[i];
  62421. var percent = value / this.BARGRAPHAMPLITUDE;
  62422. var height = this.DEBUGCANVASSIZE.height * percent;
  62423. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62424. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62425. var hue = i / this.getFrequencyBinCount() * 360;
  62426. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62427. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62428. }
  62429. }
  62430. }
  62431. };
  62432. Analyser.prototype.stopDebugCanvas = function () {
  62433. if (this._debugCanvas) {
  62434. if (this._registerFunc) {
  62435. this._scene.unregisterBeforeRender(this._registerFunc);
  62436. this._registerFunc = null;
  62437. }
  62438. document.body.removeChild(this._debugCanvas);
  62439. this._debugCanvas = null;
  62440. this._debugCanvasContext = null;
  62441. }
  62442. };
  62443. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62444. if (this._audioEngine.canUseWebAudio) {
  62445. inputAudioNode.connect(this._webAudioAnalyser);
  62446. this._webAudioAnalyser.connect(outputAudioNode);
  62447. }
  62448. };
  62449. Analyser.prototype.dispose = function () {
  62450. if (this._audioEngine.canUseWebAudio) {
  62451. this._webAudioAnalyser.disconnect();
  62452. }
  62453. };
  62454. return Analyser;
  62455. }());
  62456. BABYLON.Analyser = Analyser;
  62457. })(BABYLON || (BABYLON = {}));
  62458. //# sourceMappingURL=babylon.analyser.js.map
  62459. var BABYLON;
  62460. (function (BABYLON) {
  62461. var CubeTexture = /** @class */ (function (_super) {
  62462. __extends(CubeTexture, _super);
  62463. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62464. if (extensions === void 0) { extensions = null; }
  62465. if (noMipmap === void 0) { noMipmap = false; }
  62466. if (files === void 0) { files = null; }
  62467. if (onLoad === void 0) { onLoad = null; }
  62468. if (onError === void 0) { onError = null; }
  62469. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62470. if (prefiltered === void 0) { prefiltered = false; }
  62471. if (forcedExtension === void 0) { forcedExtension = null; }
  62472. var _this = _super.call(this, scene) || this;
  62473. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62474. /**
  62475. * Gets or sets the center of the bounding box associated with the cube texture
  62476. * It must define where the camera used to render the texture was set
  62477. */
  62478. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62479. _this._rotationY = 0;
  62480. _this.name = rootUrl;
  62481. _this.url = rootUrl;
  62482. _this._noMipmap = noMipmap;
  62483. _this.hasAlpha = false;
  62484. _this._format = format;
  62485. _this._prefiltered = prefiltered;
  62486. _this.isCube = true;
  62487. _this._textureMatrix = BABYLON.Matrix.Identity();
  62488. if (prefiltered) {
  62489. _this.gammaSpace = false;
  62490. }
  62491. if (!rootUrl && !files) {
  62492. return _this;
  62493. }
  62494. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62495. var lastDot = rootUrl.lastIndexOf(".");
  62496. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62497. var isDDS = (extension === ".dds");
  62498. if (!files) {
  62499. if (!isDDS && !extensions) {
  62500. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62501. }
  62502. files = [];
  62503. if (extensions) {
  62504. for (var index = 0; index < extensions.length; index++) {
  62505. files.push(rootUrl + extensions[index]);
  62506. }
  62507. }
  62508. }
  62509. _this._files = files;
  62510. if (!_this._texture) {
  62511. if (!scene.useDelayedTextureLoading) {
  62512. if (prefiltered) {
  62513. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62514. }
  62515. else {
  62516. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62517. }
  62518. }
  62519. else {
  62520. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62521. }
  62522. }
  62523. else if (onLoad) {
  62524. if (_this._texture.isReady) {
  62525. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62526. }
  62527. else {
  62528. _this._texture.onLoadedObservable.add(onLoad);
  62529. }
  62530. }
  62531. return _this;
  62532. }
  62533. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62534. get: function () {
  62535. return this._boundingBoxSize;
  62536. },
  62537. /**
  62538. * Gets or sets the size of the bounding box associated with the cube texture
  62539. * When defined, the cubemap will switch to local mode
  62540. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62541. * @example https://www.babylonjs-playground.com/#RNASML
  62542. */
  62543. set: function (value) {
  62544. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62545. return;
  62546. }
  62547. this._boundingBoxSize = value;
  62548. var scene = this.getScene();
  62549. if (scene) {
  62550. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62551. }
  62552. },
  62553. enumerable: true,
  62554. configurable: true
  62555. });
  62556. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62557. /**
  62558. * Gets texture matrix rotation angle around Y axis radians.
  62559. */
  62560. get: function () {
  62561. return this._rotationY;
  62562. },
  62563. /**
  62564. * Sets texture matrix rotation angle around Y axis in radians.
  62565. */
  62566. set: function (value) {
  62567. this._rotationY = value;
  62568. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62569. },
  62570. enumerable: true,
  62571. configurable: true
  62572. });
  62573. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62574. var rootUrlKey = "";
  62575. files.forEach(function (url) { return rootUrlKey += url; });
  62576. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62577. };
  62578. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62579. if (forcedExtension === void 0) { forcedExtension = null; }
  62580. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62581. };
  62582. // Methods
  62583. CubeTexture.prototype.delayLoad = function () {
  62584. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62585. return;
  62586. }
  62587. var scene = this.getScene();
  62588. if (!scene) {
  62589. return;
  62590. }
  62591. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  62592. this._texture = this._getFromCache(this.url, this._noMipmap);
  62593. if (!this._texture) {
  62594. if (this._prefiltered) {
  62595. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  62596. }
  62597. else {
  62598. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  62599. }
  62600. }
  62601. };
  62602. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  62603. return this._textureMatrix;
  62604. };
  62605. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  62606. this._textureMatrix = value;
  62607. };
  62608. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  62609. var texture = BABYLON.SerializationHelper.Parse(function () {
  62610. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  62611. }, parsedTexture, scene);
  62612. // Local Cubemaps
  62613. if (parsedTexture.boundingBoxPosition) {
  62614. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  62615. }
  62616. if (parsedTexture.boundingBoxSize) {
  62617. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  62618. }
  62619. // Animations
  62620. if (parsedTexture.animations) {
  62621. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  62622. var parsedAnimation = parsedTexture.animations[animationIndex];
  62623. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  62624. }
  62625. }
  62626. return texture;
  62627. };
  62628. CubeTexture.prototype.clone = function () {
  62629. var _this = this;
  62630. return BABYLON.SerializationHelper.Clone(function () {
  62631. var scene = _this.getScene();
  62632. if (!scene) {
  62633. return _this;
  62634. }
  62635. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  62636. }, this);
  62637. };
  62638. __decorate([
  62639. BABYLON.serialize("rotationY")
  62640. ], CubeTexture.prototype, "_rotationY", void 0);
  62641. return CubeTexture;
  62642. }(BABYLON.BaseTexture));
  62643. BABYLON.CubeTexture = CubeTexture;
  62644. })(BABYLON || (BABYLON = {}));
  62645. //# sourceMappingURL=babylon.cubeTexture.js.map
  62646. var BABYLON;
  62647. (function (BABYLON) {
  62648. var RenderTargetTexture = /** @class */ (function (_super) {
  62649. __extends(RenderTargetTexture, _super);
  62650. /**
  62651. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  62652. * or used a shadow, depth texture...
  62653. * @param name The friendly name of the texture
  62654. * @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)
  62655. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  62656. * @param generateMipMaps True if mip maps need to be generated after render.
  62657. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  62658. * @param type The type of the buffer in the RTT (int, half float, float...)
  62659. * @param isCube True if a cube texture needs to be created
  62660. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  62661. * @param generateDepthBuffer True to generate a depth buffer
  62662. * @param generateStencilBuffer True to generate a stencil buffer
  62663. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  62664. */
  62665. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  62666. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  62667. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  62668. if (isCube === void 0) { isCube = false; }
  62669. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  62670. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  62671. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  62672. if (isMulti === void 0) { isMulti = false; }
  62673. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  62674. _this.isCube = isCube;
  62675. /**
  62676. * Use this list to define the list of mesh you want to render.
  62677. */
  62678. _this.renderList = new Array();
  62679. _this.renderParticles = true;
  62680. _this.renderSprites = false;
  62681. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  62682. _this.ignoreCameraViewport = false;
  62683. // Events
  62684. /**
  62685. * An event triggered when the texture is unbind.
  62686. */
  62687. _this.onBeforeBindObservable = new BABYLON.Observable();
  62688. /**
  62689. * An event triggered when the texture is unbind.
  62690. */
  62691. _this.onAfterUnbindObservable = new BABYLON.Observable();
  62692. /**
  62693. * An event triggered before rendering the texture
  62694. */
  62695. _this.onBeforeRenderObservable = new BABYLON.Observable();
  62696. /**
  62697. * An event triggered after rendering the texture
  62698. */
  62699. _this.onAfterRenderObservable = new BABYLON.Observable();
  62700. /**
  62701. * An event triggered after the texture clear
  62702. */
  62703. _this.onClearObservable = new BABYLON.Observable();
  62704. _this._currentRefreshId = -1;
  62705. _this._refreshRate = 1;
  62706. _this._samples = 1;
  62707. /**
  62708. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  62709. * It must define where the camera used to render the texture is set
  62710. */
  62711. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62712. scene = _this.getScene();
  62713. if (!scene) {
  62714. return _this;
  62715. }
  62716. _this._engine = scene.getEngine();
  62717. _this.name = name;
  62718. _this.isRenderTarget = true;
  62719. _this._initialSizeParameter = size;
  62720. _this._processSizeParameter(size);
  62721. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  62722. });
  62723. _this._generateMipMaps = generateMipMaps ? true : false;
  62724. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  62725. // Rendering groups
  62726. _this._renderingManager = new BABYLON.RenderingManager(scene);
  62727. if (isMulti) {
  62728. return _this;
  62729. }
  62730. _this._renderTargetOptions = {
  62731. generateMipMaps: generateMipMaps,
  62732. type: type,
  62733. samplingMode: samplingMode,
  62734. generateDepthBuffer: generateDepthBuffer,
  62735. generateStencilBuffer: generateStencilBuffer
  62736. };
  62737. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  62738. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62739. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  62740. }
  62741. if (isCube) {
  62742. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  62743. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  62744. _this._textureMatrix = BABYLON.Matrix.Identity();
  62745. }
  62746. else {
  62747. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  62748. }
  62749. return _this;
  62750. }
  62751. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  62752. get: function () {
  62753. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  62754. },
  62755. enumerable: true,
  62756. configurable: true
  62757. });
  62758. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  62759. get: function () {
  62760. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  62761. },
  62762. enumerable: true,
  62763. configurable: true
  62764. });
  62765. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  62766. get: function () {
  62767. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  62768. },
  62769. enumerable: true,
  62770. configurable: true
  62771. });
  62772. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  62773. set: function (callback) {
  62774. if (this._onAfterUnbindObserver) {
  62775. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  62776. }
  62777. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  62778. },
  62779. enumerable: true,
  62780. configurable: true
  62781. });
  62782. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  62783. set: function (callback) {
  62784. if (this._onBeforeRenderObserver) {
  62785. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  62786. }
  62787. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  62788. },
  62789. enumerable: true,
  62790. configurable: true
  62791. });
  62792. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  62793. set: function (callback) {
  62794. if (this._onAfterRenderObserver) {
  62795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  62796. }
  62797. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  62798. },
  62799. enumerable: true,
  62800. configurable: true
  62801. });
  62802. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  62803. set: function (callback) {
  62804. if (this._onClearObserver) {
  62805. this.onClearObservable.remove(this._onClearObserver);
  62806. }
  62807. this._onClearObserver = this.onClearObservable.add(callback);
  62808. },
  62809. enumerable: true,
  62810. configurable: true
  62811. });
  62812. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  62813. get: function () {
  62814. return this._renderTargetOptions;
  62815. },
  62816. enumerable: true,
  62817. configurable: true
  62818. });
  62819. RenderTargetTexture.prototype._onRatioRescale = function () {
  62820. if (this._sizeRatio) {
  62821. this.resize(this._initialSizeParameter);
  62822. }
  62823. };
  62824. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  62825. get: function () {
  62826. return this._boundingBoxSize;
  62827. },
  62828. /**
  62829. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  62830. * When defined, the cubemap will switch to local mode
  62831. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62832. * @example https://www.babylonjs-playground.com/#RNASML
  62833. */
  62834. set: function (value) {
  62835. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62836. return;
  62837. }
  62838. this._boundingBoxSize = value;
  62839. var scene = this.getScene();
  62840. if (scene) {
  62841. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62842. }
  62843. },
  62844. enumerable: true,
  62845. configurable: true
  62846. });
  62847. /**
  62848. * Creates a depth stencil texture.
  62849. * This is only available in WebGL 2 or with the depth texture extension available.
  62850. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  62851. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  62852. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  62853. */
  62854. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  62855. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  62856. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  62857. if (generateStencil === void 0) { generateStencil = false; }
  62858. if (!this.getScene()) {
  62859. return;
  62860. }
  62861. var engine = this.getScene().getEngine();
  62862. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  62863. bilinearFiltering: bilinearFiltering,
  62864. comparisonFunction: comparisonFunction,
  62865. generateStencil: generateStencil,
  62866. isCube: this.isCube
  62867. });
  62868. engine.setFrameBufferDepthStencilTexture(this);
  62869. };
  62870. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  62871. if (size.ratio) {
  62872. this._sizeRatio = size.ratio;
  62873. this._size = {
  62874. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  62875. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  62876. };
  62877. }
  62878. else {
  62879. this._size = size;
  62880. }
  62881. };
  62882. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  62883. get: function () {
  62884. return this._samples;
  62885. },
  62886. set: function (value) {
  62887. if (this._samples === value) {
  62888. return;
  62889. }
  62890. var scene = this.getScene();
  62891. if (!scene) {
  62892. return;
  62893. }
  62894. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  62895. },
  62896. enumerable: true,
  62897. configurable: true
  62898. });
  62899. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  62900. this._currentRefreshId = -1;
  62901. };
  62902. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  62903. get: function () {
  62904. return this._refreshRate;
  62905. },
  62906. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  62907. set: function (value) {
  62908. this._refreshRate = value;
  62909. this.resetRefreshCounter();
  62910. },
  62911. enumerable: true,
  62912. configurable: true
  62913. });
  62914. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  62915. if (!this._postProcessManager) {
  62916. var scene = this.getScene();
  62917. if (!scene) {
  62918. return;
  62919. }
  62920. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  62921. this._postProcesses = new Array();
  62922. }
  62923. this._postProcesses.push(postProcess);
  62924. this._postProcesses[0].autoClear = false;
  62925. };
  62926. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  62927. if (!this._postProcesses) {
  62928. return;
  62929. }
  62930. if (dispose) {
  62931. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  62932. var postProcess = _a[_i];
  62933. postProcess.dispose();
  62934. }
  62935. }
  62936. this._postProcesses = [];
  62937. };
  62938. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  62939. if (!this._postProcesses) {
  62940. return;
  62941. }
  62942. var index = this._postProcesses.indexOf(postProcess);
  62943. if (index === -1) {
  62944. return;
  62945. }
  62946. this._postProcesses.splice(index, 1);
  62947. if (this._postProcesses.length > 0) {
  62948. this._postProcesses[0].autoClear = false;
  62949. }
  62950. };
  62951. RenderTargetTexture.prototype._shouldRender = function () {
  62952. if (this._currentRefreshId === -1) { // At least render once
  62953. this._currentRefreshId = 1;
  62954. return true;
  62955. }
  62956. if (this.refreshRate === this._currentRefreshId) {
  62957. this._currentRefreshId = 1;
  62958. return true;
  62959. }
  62960. this._currentRefreshId++;
  62961. return false;
  62962. };
  62963. RenderTargetTexture.prototype.getRenderSize = function () {
  62964. if (this._size.width) {
  62965. return this._size.width;
  62966. }
  62967. return this._size;
  62968. };
  62969. RenderTargetTexture.prototype.getRenderWidth = function () {
  62970. if (this._size.width) {
  62971. return this._size.width;
  62972. }
  62973. return this._size;
  62974. };
  62975. RenderTargetTexture.prototype.getRenderHeight = function () {
  62976. if (this._size.width) {
  62977. return this._size.height;
  62978. }
  62979. return this._size;
  62980. };
  62981. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  62982. get: function () {
  62983. return true;
  62984. },
  62985. enumerable: true,
  62986. configurable: true
  62987. });
  62988. RenderTargetTexture.prototype.scale = function (ratio) {
  62989. var newSize = this.getRenderSize() * ratio;
  62990. this.resize(newSize);
  62991. };
  62992. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  62993. if (this.isCube) {
  62994. return this._textureMatrix;
  62995. }
  62996. return _super.prototype.getReflectionTextureMatrix.call(this);
  62997. };
  62998. RenderTargetTexture.prototype.resize = function (size) {
  62999. this.releaseInternalTexture();
  63000. var scene = this.getScene();
  63001. if (!scene) {
  63002. return;
  63003. }
  63004. this._processSizeParameter(size);
  63005. if (this.isCube) {
  63006. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63007. }
  63008. else {
  63009. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63010. }
  63011. };
  63012. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63013. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63014. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63015. var scene = this.getScene();
  63016. if (!scene) {
  63017. return;
  63018. }
  63019. var engine = scene.getEngine();
  63020. if (this.useCameraPostProcesses !== undefined) {
  63021. useCameraPostProcess = this.useCameraPostProcesses;
  63022. }
  63023. if (this._waitingRenderList) {
  63024. this.renderList = [];
  63025. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63026. var id = this._waitingRenderList[index];
  63027. var mesh_1 = scene.getMeshByID(id);
  63028. if (mesh_1) {
  63029. this.renderList.push(mesh_1);
  63030. }
  63031. }
  63032. delete this._waitingRenderList;
  63033. }
  63034. // Is predicate defined?
  63035. if (this.renderListPredicate) {
  63036. if (this.renderList) {
  63037. this.renderList.splice(0); // Clear previous renderList
  63038. }
  63039. else {
  63040. this.renderList = [];
  63041. }
  63042. var scene = this.getScene();
  63043. if (!scene) {
  63044. return;
  63045. }
  63046. var sceneMeshes = scene.meshes;
  63047. for (var index = 0; index < sceneMeshes.length; index++) {
  63048. var mesh = sceneMeshes[index];
  63049. if (this.renderListPredicate(mesh)) {
  63050. this.renderList.push(mesh);
  63051. }
  63052. }
  63053. }
  63054. this.onBeforeBindObservable.notifyObservers(this);
  63055. // Set custom projection.
  63056. // Needs to be before binding to prevent changing the aspect ratio.
  63057. var camera;
  63058. if (this.activeCamera) {
  63059. camera = this.activeCamera;
  63060. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63061. if (this.activeCamera !== scene.activeCamera) {
  63062. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63063. }
  63064. }
  63065. else {
  63066. camera = scene.activeCamera;
  63067. if (camera) {
  63068. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63069. }
  63070. }
  63071. // Prepare renderingManager
  63072. this._renderingManager.reset();
  63073. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63074. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63075. var sceneRenderId = scene.getRenderId();
  63076. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63077. var mesh = currentRenderList[meshIndex];
  63078. if (mesh) {
  63079. if (!mesh.isReady(this.refreshRate === 0)) {
  63080. this.resetRefreshCounter();
  63081. continue;
  63082. }
  63083. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63084. var isMasked = void 0;
  63085. if (!this.renderList && camera) {
  63086. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63087. }
  63088. else {
  63089. isMasked = false;
  63090. }
  63091. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63092. mesh._activate(sceneRenderId);
  63093. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63094. var subMesh = mesh.subMeshes[subIndex];
  63095. scene._activeIndices.addCount(subMesh.indexCount, false);
  63096. this._renderingManager.dispatch(subMesh, mesh);
  63097. }
  63098. }
  63099. }
  63100. }
  63101. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63102. var particleSystem = scene.particleSystems[particleIndex];
  63103. var emitter = particleSystem.emitter;
  63104. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63105. continue;
  63106. }
  63107. if (currentRenderList.indexOf(emitter) >= 0) {
  63108. this._renderingManager.dispatchParticles(particleSystem);
  63109. }
  63110. }
  63111. if (this.isCube) {
  63112. for (var face = 0; face < 6; face++) {
  63113. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63114. scene.incrementRenderId();
  63115. scene.resetCachedMaterial();
  63116. }
  63117. }
  63118. else {
  63119. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63120. }
  63121. this.onAfterUnbindObservable.notifyObservers(this);
  63122. if (scene.activeCamera) {
  63123. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63124. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63125. }
  63126. engine.setViewport(scene.activeCamera.viewport);
  63127. }
  63128. scene.resetCachedMaterial();
  63129. };
  63130. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63131. var minimum = 128;
  63132. var x = renderDimension * scale;
  63133. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63134. // Ensure we don't exceed the render dimension (while staying POT)
  63135. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63136. };
  63137. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63138. var _this = this;
  63139. if (!this._texture) {
  63140. return;
  63141. }
  63142. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63143. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63144. });
  63145. };
  63146. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63147. var scene = this.getScene();
  63148. if (!scene) {
  63149. return;
  63150. }
  63151. var engine = scene.getEngine();
  63152. if (!this._texture) {
  63153. return;
  63154. }
  63155. // Bind
  63156. if (this._postProcessManager) {
  63157. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63158. }
  63159. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63160. if (this._texture) {
  63161. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63162. }
  63163. }
  63164. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63165. // Clear
  63166. if (this.onClearObservable.hasObservers()) {
  63167. this.onClearObservable.notifyObservers(engine);
  63168. }
  63169. else {
  63170. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63171. }
  63172. if (!this._doNotChangeAspectRatio) {
  63173. scene.updateTransformMatrix(true);
  63174. }
  63175. // Render
  63176. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63177. if (this._postProcessManager) {
  63178. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63179. }
  63180. else if (useCameraPostProcess) {
  63181. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63182. }
  63183. if (!this._doNotChangeAspectRatio) {
  63184. scene.updateTransformMatrix(true);
  63185. }
  63186. // Dump ?
  63187. if (dumpForDebug) {
  63188. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63189. }
  63190. // Unbind
  63191. if (!this.isCube || faceIndex === 5) {
  63192. if (this.isCube) {
  63193. if (faceIndex === 5) {
  63194. engine.generateMipMapsForCubemap(this._texture);
  63195. }
  63196. }
  63197. this.unbindFrameBuffer(engine, faceIndex);
  63198. }
  63199. else {
  63200. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63201. }
  63202. };
  63203. /**
  63204. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63205. * This allowed control for front to back rendering or reversly depending of the special needs.
  63206. *
  63207. * @param renderingGroupId The rendering group id corresponding to its index
  63208. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63209. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63210. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63211. */
  63212. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63213. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63214. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63215. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63216. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63217. };
  63218. /**
  63219. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63220. *
  63221. * @param renderingGroupId The rendering group id corresponding to its index
  63222. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63223. */
  63224. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63225. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63226. };
  63227. RenderTargetTexture.prototype.clone = function () {
  63228. var textureSize = this.getSize();
  63229. 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);
  63230. // Base texture
  63231. newTexture.hasAlpha = this.hasAlpha;
  63232. newTexture.level = this.level;
  63233. // RenderTarget Texture
  63234. newTexture.coordinatesMode = this.coordinatesMode;
  63235. if (this.renderList) {
  63236. newTexture.renderList = this.renderList.slice(0);
  63237. }
  63238. return newTexture;
  63239. };
  63240. RenderTargetTexture.prototype.serialize = function () {
  63241. if (!this.name) {
  63242. return null;
  63243. }
  63244. var serializationObject = _super.prototype.serialize.call(this);
  63245. serializationObject.renderTargetSize = this.getRenderSize();
  63246. serializationObject.renderList = [];
  63247. if (this.renderList) {
  63248. for (var index = 0; index < this.renderList.length; index++) {
  63249. serializationObject.renderList.push(this.renderList[index].id);
  63250. }
  63251. }
  63252. return serializationObject;
  63253. };
  63254. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63255. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63256. var objBuffer = this.getInternalTexture();
  63257. var scene = this.getScene();
  63258. if (objBuffer && scene) {
  63259. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63260. }
  63261. };
  63262. RenderTargetTexture.prototype.dispose = function () {
  63263. if (this._postProcessManager) {
  63264. this._postProcessManager.dispose();
  63265. this._postProcessManager = null;
  63266. }
  63267. this.clearPostProcesses(true);
  63268. if (this._resizeObserver) {
  63269. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63270. this._resizeObserver = null;
  63271. }
  63272. this.renderList = null;
  63273. // Remove from custom render targets
  63274. var scene = this.getScene();
  63275. if (!scene) {
  63276. return;
  63277. }
  63278. var index = scene.customRenderTargets.indexOf(this);
  63279. if (index >= 0) {
  63280. scene.customRenderTargets.splice(index, 1);
  63281. }
  63282. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63283. var camera = _a[_i];
  63284. index = camera.customRenderTargets.indexOf(this);
  63285. if (index >= 0) {
  63286. camera.customRenderTargets.splice(index, 1);
  63287. }
  63288. }
  63289. _super.prototype.dispose.call(this);
  63290. };
  63291. RenderTargetTexture.prototype._rebuild = function () {
  63292. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63293. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63294. }
  63295. if (this._postProcessManager) {
  63296. this._postProcessManager._rebuild();
  63297. }
  63298. };
  63299. /**
  63300. * Clear the info related to rendering groups preventing retention point in material dispose.
  63301. */
  63302. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63303. if (this._renderingManager) {
  63304. this._renderingManager.freeRenderingGroups();
  63305. }
  63306. };
  63307. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63308. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63309. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63310. return RenderTargetTexture;
  63311. }(BABYLON.Texture));
  63312. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63313. })(BABYLON || (BABYLON = {}));
  63314. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63315. var BABYLON;
  63316. (function (BABYLON) {
  63317. ;
  63318. var MultiRenderTarget = /** @class */ (function (_super) {
  63319. __extends(MultiRenderTarget, _super);
  63320. function MultiRenderTarget(name, size, count, scene, options) {
  63321. var _this = this;
  63322. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63323. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63324. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63325. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63326. _this._engine = scene.getEngine();
  63327. if (!_this.isSupported) {
  63328. _this.dispose();
  63329. return;
  63330. }
  63331. var types = [];
  63332. var samplingModes = [];
  63333. for (var i = 0; i < count; i++) {
  63334. if (options && options.types && options.types[i] !== undefined) {
  63335. types.push(options.types[i]);
  63336. }
  63337. else {
  63338. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63339. }
  63340. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63341. samplingModes.push(options.samplingModes[i]);
  63342. }
  63343. else {
  63344. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63345. }
  63346. }
  63347. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63348. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63349. _this._size = size;
  63350. _this._multiRenderTargetOptions = {
  63351. samplingModes: samplingModes,
  63352. generateMipMaps: generateMipMaps,
  63353. generateDepthBuffer: generateDepthBuffer,
  63354. generateStencilBuffer: generateStencilBuffer,
  63355. generateDepthTexture: generateDepthTexture,
  63356. types: types,
  63357. textureCount: count
  63358. };
  63359. _this._createInternalTextures();
  63360. _this._createTextures();
  63361. return _this;
  63362. }
  63363. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63364. get: function () {
  63365. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63366. },
  63367. enumerable: true,
  63368. configurable: true
  63369. });
  63370. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63371. get: function () {
  63372. return this._textures;
  63373. },
  63374. enumerable: true,
  63375. configurable: true
  63376. });
  63377. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63378. get: function () {
  63379. return this._textures[this._textures.length - 1];
  63380. },
  63381. enumerable: true,
  63382. configurable: true
  63383. });
  63384. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63385. set: function (wrap) {
  63386. if (this._textures) {
  63387. for (var i = 0; i < this._textures.length; i++) {
  63388. this._textures[i].wrapU = wrap;
  63389. }
  63390. }
  63391. },
  63392. enumerable: true,
  63393. configurable: true
  63394. });
  63395. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63396. set: function (wrap) {
  63397. if (this._textures) {
  63398. for (var i = 0; i < this._textures.length; i++) {
  63399. this._textures[i].wrapV = wrap;
  63400. }
  63401. }
  63402. },
  63403. enumerable: true,
  63404. configurable: true
  63405. });
  63406. MultiRenderTarget.prototype._rebuild = function () {
  63407. this.releaseInternalTextures();
  63408. this._createInternalTextures();
  63409. for (var i = 0; i < this._internalTextures.length; i++) {
  63410. var texture = this._textures[i];
  63411. texture._texture = this._internalTextures[i];
  63412. }
  63413. // Keeps references to frame buffer and stencil/depth buffer
  63414. this._texture = this._internalTextures[0];
  63415. };
  63416. MultiRenderTarget.prototype._createInternalTextures = function () {
  63417. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63418. };
  63419. MultiRenderTarget.prototype._createTextures = function () {
  63420. this._textures = [];
  63421. for (var i = 0; i < this._internalTextures.length; i++) {
  63422. var texture = new BABYLON.Texture(null, this.getScene());
  63423. texture._texture = this._internalTextures[i];
  63424. this._textures.push(texture);
  63425. }
  63426. // Keeps references to frame buffer and stencil/depth buffer
  63427. this._texture = this._internalTextures[0];
  63428. };
  63429. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63430. get: function () {
  63431. return this._samples;
  63432. },
  63433. set: function (value) {
  63434. if (this._samples === value) {
  63435. return;
  63436. }
  63437. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63438. },
  63439. enumerable: true,
  63440. configurable: true
  63441. });
  63442. MultiRenderTarget.prototype.resize = function (size) {
  63443. this.releaseInternalTextures();
  63444. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63445. this._createInternalTextures();
  63446. };
  63447. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63448. var _this = this;
  63449. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63450. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63451. });
  63452. };
  63453. MultiRenderTarget.prototype.dispose = function () {
  63454. this.releaseInternalTextures();
  63455. _super.prototype.dispose.call(this);
  63456. };
  63457. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63458. if (!this._internalTextures) {
  63459. return;
  63460. }
  63461. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63462. if (this._internalTextures[i] !== undefined) {
  63463. this._internalTextures[i].dispose();
  63464. this._internalTextures.splice(i, 1);
  63465. }
  63466. }
  63467. };
  63468. return MultiRenderTarget;
  63469. }(BABYLON.RenderTargetTexture));
  63470. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63471. })(BABYLON || (BABYLON = {}));
  63472. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63473. var BABYLON;
  63474. (function (BABYLON) {
  63475. var MirrorTexture = /** @class */ (function (_super) {
  63476. __extends(MirrorTexture, _super);
  63477. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63478. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63480. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63481. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63482. _this.scene = scene;
  63483. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63484. _this._transformMatrix = BABYLON.Matrix.Zero();
  63485. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63486. _this._adaptiveBlurKernel = 0;
  63487. _this._blurKernelX = 0;
  63488. _this._blurKernelY = 0;
  63489. _this._blurRatio = 1.0;
  63490. _this.ignoreCameraViewport = true;
  63491. _this._updateGammaSpace();
  63492. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63493. _this._updateGammaSpace;
  63494. });
  63495. _this.onBeforeRenderObservable.add(function () {
  63496. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63497. _this._savedViewMatrix = scene.getViewMatrix();
  63498. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63499. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63500. scene.clipPlane = _this.mirrorPlane;
  63501. scene.getEngine().cullBackFaces = false;
  63502. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63503. });
  63504. _this.onAfterRenderObservable.add(function () {
  63505. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63506. scene.getEngine().cullBackFaces = true;
  63507. scene._mirroredCameraPosition = null;
  63508. delete scene.clipPlane;
  63509. });
  63510. return _this;
  63511. }
  63512. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63513. get: function () {
  63514. return this._blurRatio;
  63515. },
  63516. set: function (value) {
  63517. if (this._blurRatio === value) {
  63518. return;
  63519. }
  63520. this._blurRatio = value;
  63521. this._preparePostProcesses();
  63522. },
  63523. enumerable: true,
  63524. configurable: true
  63525. });
  63526. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63527. set: function (value) {
  63528. this._adaptiveBlurKernel = value;
  63529. this._autoComputeBlurKernel();
  63530. },
  63531. enumerable: true,
  63532. configurable: true
  63533. });
  63534. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63535. set: function (value) {
  63536. this.blurKernelX = value;
  63537. this.blurKernelY = value;
  63538. },
  63539. enumerable: true,
  63540. configurable: true
  63541. });
  63542. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63543. get: function () {
  63544. return this._blurKernelX;
  63545. },
  63546. set: function (value) {
  63547. if (this._blurKernelX === value) {
  63548. return;
  63549. }
  63550. this._blurKernelX = value;
  63551. this._preparePostProcesses();
  63552. },
  63553. enumerable: true,
  63554. configurable: true
  63555. });
  63556. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63557. get: function () {
  63558. return this._blurKernelY;
  63559. },
  63560. set: function (value) {
  63561. if (this._blurKernelY === value) {
  63562. return;
  63563. }
  63564. this._blurKernelY = value;
  63565. this._preparePostProcesses();
  63566. },
  63567. enumerable: true,
  63568. configurable: true
  63569. });
  63570. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63571. var engine = this.getScene().getEngine();
  63572. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63573. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63574. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63575. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63576. };
  63577. MirrorTexture.prototype._onRatioRescale = function () {
  63578. if (this._sizeRatio) {
  63579. this.resize(this._initialSizeParameter);
  63580. if (!this._adaptiveBlurKernel) {
  63581. this._preparePostProcesses();
  63582. }
  63583. }
  63584. if (this._adaptiveBlurKernel) {
  63585. this._autoComputeBlurKernel();
  63586. }
  63587. };
  63588. MirrorTexture.prototype._updateGammaSpace = function () {
  63589. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  63590. };
  63591. MirrorTexture.prototype._preparePostProcesses = function () {
  63592. this.clearPostProcesses(true);
  63593. if (this._blurKernelX && this._blurKernelY) {
  63594. var engine = this.getScene().getEngine();
  63595. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  63596. 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);
  63597. this._blurX.autoClear = false;
  63598. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  63599. this._blurX.inputTexture = this._texture;
  63600. }
  63601. else {
  63602. this._blurX.alwaysForcePOT = true;
  63603. }
  63604. 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);
  63605. this._blurY.autoClear = false;
  63606. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  63607. this.addPostProcess(this._blurX);
  63608. this.addPostProcess(this._blurY);
  63609. }
  63610. else {
  63611. if (this._blurY) {
  63612. this.removePostProcess(this._blurY);
  63613. this._blurY.dispose();
  63614. this._blurY = null;
  63615. }
  63616. if (this._blurX) {
  63617. this.removePostProcess(this._blurX);
  63618. this._blurX.dispose();
  63619. this._blurX = null;
  63620. }
  63621. }
  63622. };
  63623. MirrorTexture.prototype.clone = function () {
  63624. var scene = this.getScene();
  63625. if (!scene) {
  63626. return this;
  63627. }
  63628. var textureSize = this.getSize();
  63629. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  63630. // Base texture
  63631. newTexture.hasAlpha = this.hasAlpha;
  63632. newTexture.level = this.level;
  63633. // Mirror Texture
  63634. newTexture.mirrorPlane = this.mirrorPlane.clone();
  63635. if (this.renderList) {
  63636. newTexture.renderList = this.renderList.slice(0);
  63637. }
  63638. return newTexture;
  63639. };
  63640. MirrorTexture.prototype.serialize = function () {
  63641. if (!this.name) {
  63642. return null;
  63643. }
  63644. var serializationObject = _super.prototype.serialize.call(this);
  63645. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  63646. return serializationObject;
  63647. };
  63648. MirrorTexture.prototype.dispose = function () {
  63649. _super.prototype.dispose.call(this);
  63650. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  63651. };
  63652. return MirrorTexture;
  63653. }(BABYLON.RenderTargetTexture));
  63654. BABYLON.MirrorTexture = MirrorTexture;
  63655. })(BABYLON || (BABYLON = {}));
  63656. //# sourceMappingURL=babylon.mirrorTexture.js.map
  63657. var BABYLON;
  63658. (function (BABYLON) {
  63659. /**
  63660. * Creates a refraction texture used by refraction channel of the standard material.
  63661. * @param name the texture name
  63662. * @param size size of the underlying texture
  63663. * @param scene root scene
  63664. */
  63665. var RefractionTexture = /** @class */ (function (_super) {
  63666. __extends(RefractionTexture, _super);
  63667. function RefractionTexture(name, size, scene, generateMipMaps) {
  63668. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  63669. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  63670. _this.depth = 2.0;
  63671. _this.onBeforeRenderObservable.add(function () {
  63672. scene.clipPlane = _this.refractionPlane;
  63673. });
  63674. _this.onAfterRenderObservable.add(function () {
  63675. delete scene.clipPlane;
  63676. });
  63677. return _this;
  63678. }
  63679. RefractionTexture.prototype.clone = function () {
  63680. var scene = this.getScene();
  63681. if (!scene) {
  63682. return this;
  63683. }
  63684. var textureSize = this.getSize();
  63685. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  63686. // Base texture
  63687. newTexture.hasAlpha = this.hasAlpha;
  63688. newTexture.level = this.level;
  63689. // Refraction Texture
  63690. newTexture.refractionPlane = this.refractionPlane.clone();
  63691. if (this.renderList) {
  63692. newTexture.renderList = this.renderList.slice(0);
  63693. }
  63694. newTexture.depth = this.depth;
  63695. return newTexture;
  63696. };
  63697. RefractionTexture.prototype.serialize = function () {
  63698. if (!this.name) {
  63699. return null;
  63700. }
  63701. var serializationObject = _super.prototype.serialize.call(this);
  63702. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  63703. serializationObject.depth = this.depth;
  63704. return serializationObject;
  63705. };
  63706. return RefractionTexture;
  63707. }(BABYLON.RenderTargetTexture));
  63708. BABYLON.RefractionTexture = RefractionTexture;
  63709. })(BABYLON || (BABYLON = {}));
  63710. //# sourceMappingURL=babylon.refractionTexture.js.map
  63711. var BABYLON;
  63712. (function (BABYLON) {
  63713. /**
  63714. * A class extending {BABYLON.Texture} allowing drawing on a texture
  63715. * @see http://doc.babylonjs.com/how_to/dynamictexture
  63716. */
  63717. var DynamicTexture = /** @class */ (function (_super) {
  63718. __extends(DynamicTexture, _super);
  63719. /**
  63720. * Creates a {BABYLON.DynamicTexture}
  63721. * @param name defines the name of the texture
  63722. * @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
  63723. * @param scene defines the scene where you want the texture
  63724. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  63725. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  63726. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  63727. */
  63728. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  63729. if (scene === void 0) { scene = null; }
  63730. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63731. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63732. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  63733. _this.name = name;
  63734. _this._engine = _this.getScene().getEngine();
  63735. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63736. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63737. _this._generateMipMaps = generateMipMaps;
  63738. if (options.getContext) {
  63739. _this._canvas = options;
  63740. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63741. }
  63742. else {
  63743. _this._canvas = document.createElement("canvas");
  63744. if (options.width) {
  63745. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  63746. }
  63747. else {
  63748. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  63749. }
  63750. }
  63751. var textureSize = _this.getSize();
  63752. _this._canvas.width = textureSize.width;
  63753. _this._canvas.height = textureSize.height;
  63754. _this._context = _this._canvas.getContext("2d");
  63755. return _this;
  63756. }
  63757. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  63758. /**
  63759. * Gets the current state of canRescale
  63760. */
  63761. get: function () {
  63762. return true;
  63763. },
  63764. enumerable: true,
  63765. configurable: true
  63766. });
  63767. DynamicTexture.prototype._recreate = function (textureSize) {
  63768. this._canvas.width = textureSize.width;
  63769. this._canvas.height = textureSize.height;
  63770. this.releaseInternalTexture();
  63771. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  63772. };
  63773. /**
  63774. * Scales the texture
  63775. * @param ratio the scale factor to apply to both width and height
  63776. */
  63777. DynamicTexture.prototype.scale = function (ratio) {
  63778. var textureSize = this.getSize();
  63779. textureSize.width *= ratio;
  63780. textureSize.height *= ratio;
  63781. this._recreate(textureSize);
  63782. };
  63783. /**
  63784. * Resizes the texture
  63785. * @param width the new width
  63786. * @param height the new height
  63787. */
  63788. DynamicTexture.prototype.scaleTo = function (width, height) {
  63789. var textureSize = this.getSize();
  63790. textureSize.width = width;
  63791. textureSize.height = height;
  63792. this._recreate(textureSize);
  63793. };
  63794. /**
  63795. * Gets the context of the canvas used by the texture
  63796. * @returns the canvas context of the dynamic texture
  63797. */
  63798. DynamicTexture.prototype.getContext = function () {
  63799. return this._context;
  63800. };
  63801. /**
  63802. * Clears the texture
  63803. */
  63804. DynamicTexture.prototype.clear = function () {
  63805. var size = this.getSize();
  63806. this._context.fillRect(0, 0, size.width, size.height);
  63807. };
  63808. /**
  63809. * Updates the texture
  63810. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63811. */
  63812. DynamicTexture.prototype.update = function (invertY) {
  63813. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  63814. };
  63815. /**
  63816. * Draws text onto the texture
  63817. * @param text defines the text to be drawn
  63818. * @param x defines the placement of the text from the left
  63819. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  63820. * @param font defines the font to be used with font-style, font-size, font-name
  63821. * @param color defines the color used for the text
  63822. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  63823. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  63824. * @param update defines whether texture is immediately update (default is true)
  63825. */
  63826. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  63827. if (update === void 0) { update = true; }
  63828. var size = this.getSize();
  63829. if (clearColor) {
  63830. this._context.fillStyle = clearColor;
  63831. this._context.fillRect(0, 0, size.width, size.height);
  63832. }
  63833. this._context.font = font;
  63834. if (x === null || x === undefined) {
  63835. var textSize = this._context.measureText(text);
  63836. x = (size.width - textSize.width) / 2;
  63837. }
  63838. if (y === null || y === undefined) {
  63839. var fontSize = parseInt((font.replace(/\D/g, '')));
  63840. ;
  63841. y = (size.height / 2) + (fontSize / 3.65);
  63842. }
  63843. this._context.fillStyle = color;
  63844. this._context.fillText(text, x, y);
  63845. if (update) {
  63846. this.update(invertY);
  63847. }
  63848. };
  63849. /**
  63850. * Clones the texture
  63851. * @returns the clone of the texture.
  63852. */
  63853. DynamicTexture.prototype.clone = function () {
  63854. var scene = this.getScene();
  63855. if (!scene) {
  63856. return this;
  63857. }
  63858. var textureSize = this.getSize();
  63859. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  63860. // Base texture
  63861. newTexture.hasAlpha = this.hasAlpha;
  63862. newTexture.level = this.level;
  63863. // Dynamic Texture
  63864. newTexture.wrapU = this.wrapU;
  63865. newTexture.wrapV = this.wrapV;
  63866. return newTexture;
  63867. };
  63868. /** @ignore */
  63869. DynamicTexture.prototype._rebuild = function () {
  63870. this.update();
  63871. };
  63872. return DynamicTexture;
  63873. }(BABYLON.Texture));
  63874. BABYLON.DynamicTexture = DynamicTexture;
  63875. })(BABYLON || (BABYLON = {}));
  63876. //# sourceMappingURL=babylon.dynamicTexture.js.map
  63877. var BABYLON;
  63878. (function (BABYLON) {
  63879. var VideoTexture = /** @class */ (function (_super) {
  63880. __extends(VideoTexture, _super);
  63881. /**
  63882. * Creates a video texture.
  63883. * Sample : https://doc.babylonjs.com/how_to/video_texture
  63884. * @param {string | null} name optional name, will detect from video source, if not defined
  63885. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  63886. * @param {BABYLON.Scene} scene is obviously the current scene.
  63887. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  63888. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  63889. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  63890. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  63891. */
  63892. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  63893. if (generateMipMaps === void 0) { generateMipMaps = false; }
  63894. if (invertY === void 0) { invertY = false; }
  63895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63896. if (settings === void 0) { settings = {
  63897. autoPlay: true,
  63898. loop: true,
  63899. autoUpdateTexture: true,
  63900. }; }
  63901. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  63902. _this._createInternalTexture = function () {
  63903. if (_this._texture != null) {
  63904. return;
  63905. }
  63906. if (!_this._engine.needPOTTextures ||
  63907. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  63908. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  63909. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  63910. }
  63911. else {
  63912. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63913. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63914. _this._generateMipMaps = false;
  63915. }
  63916. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  63917. _this._texture.isReady = true;
  63918. _this._updateInternalTexture();
  63919. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  63920. _this.onLoadObservable.notifyObservers(_this);
  63921. }
  63922. };
  63923. _this.reset = function () {
  63924. if (_this._texture == null) {
  63925. return;
  63926. }
  63927. _this._texture.dispose();
  63928. _this._texture = null;
  63929. };
  63930. _this._updateInternalTexture = function (e) {
  63931. if (_this._texture == null || !_this._texture.isReady) {
  63932. return;
  63933. }
  63934. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  63935. return;
  63936. }
  63937. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  63938. };
  63939. _this._engine = _this.getScene().getEngine();
  63940. _this._generateMipMaps = generateMipMaps;
  63941. _this._samplingMode = samplingMode;
  63942. _this.autoUpdateTexture = settings.autoUpdateTexture;
  63943. _this.name = name || _this._getName(src);
  63944. _this.video = _this._getVideo(src);
  63945. if (settings.autoPlay !== undefined) {
  63946. _this.video.autoplay = settings.autoPlay;
  63947. }
  63948. if (settings.loop !== undefined) {
  63949. _this.video.loop = settings.loop;
  63950. }
  63951. _this.video.addEventListener("canplay", _this._createInternalTexture);
  63952. _this.video.addEventListener("paused", _this._updateInternalTexture);
  63953. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  63954. _this.video.addEventListener("emptied", _this.reset);
  63955. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  63956. _this._createInternalTexture();
  63957. }
  63958. return _this;
  63959. }
  63960. VideoTexture.prototype._getName = function (src) {
  63961. if (src instanceof HTMLVideoElement) {
  63962. return src.currentSrc;
  63963. }
  63964. if (typeof src === "object") {
  63965. return src.toString();
  63966. }
  63967. return src;
  63968. };
  63969. ;
  63970. VideoTexture.prototype._getVideo = function (src) {
  63971. if (src instanceof HTMLVideoElement) {
  63972. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  63973. return src;
  63974. }
  63975. var video = document.createElement("video");
  63976. if (typeof src === "string") {
  63977. BABYLON.Tools.SetCorsBehavior(src, video);
  63978. video.src = src;
  63979. }
  63980. else {
  63981. BABYLON.Tools.SetCorsBehavior(src[0], video);
  63982. src.forEach(function (url) {
  63983. var source = document.createElement("source");
  63984. source.src = url;
  63985. video.appendChild(source);
  63986. });
  63987. }
  63988. return video;
  63989. };
  63990. ;
  63991. /**
  63992. * Internal method to initiate `update`.
  63993. */
  63994. VideoTexture.prototype._rebuild = function () {
  63995. this.update();
  63996. };
  63997. /**
  63998. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  63999. */
  64000. VideoTexture.prototype.update = function () {
  64001. if (!this.autoUpdateTexture) {
  64002. // Expecting user to call `updateTexture` manually
  64003. return;
  64004. }
  64005. this.updateTexture(true);
  64006. };
  64007. /**
  64008. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64009. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64010. */
  64011. VideoTexture.prototype.updateTexture = function (isVisible) {
  64012. if (!isVisible) {
  64013. return;
  64014. }
  64015. if (this.video.paused) {
  64016. return;
  64017. }
  64018. this._updateInternalTexture();
  64019. };
  64020. /**
  64021. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64022. * @param url New url.
  64023. */
  64024. VideoTexture.prototype.updateURL = function (url) {
  64025. this.video.src = url;
  64026. };
  64027. VideoTexture.prototype.dispose = function () {
  64028. _super.prototype.dispose.call(this);
  64029. this.video.removeEventListener("canplay", this._createInternalTexture);
  64030. this.video.removeEventListener("paused", this._updateInternalTexture);
  64031. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64032. this.video.removeEventListener("emptied", this.reset);
  64033. this.video.pause();
  64034. };
  64035. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64036. var video = document.createElement("video");
  64037. var constraintsDeviceId;
  64038. if (constraints && constraints.deviceId) {
  64039. constraintsDeviceId = {
  64040. exact: constraints.deviceId,
  64041. };
  64042. }
  64043. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64044. if (navigator.mediaDevices) {
  64045. navigator.mediaDevices.getUserMedia({ video: constraints })
  64046. .then(function (stream) {
  64047. if (video.mozSrcObject !== undefined) {
  64048. // hack for Firefox < 19
  64049. video.mozSrcObject = stream;
  64050. }
  64051. else {
  64052. video.srcObject = stream;
  64053. }
  64054. var onPlaying = function () {
  64055. if (onReady) {
  64056. onReady(new VideoTexture("video", video, scene, true, true));
  64057. }
  64058. video.removeEventListener("playing", onPlaying);
  64059. };
  64060. video.addEventListener("playing", onPlaying);
  64061. video.play();
  64062. })
  64063. .catch(function (err) {
  64064. BABYLON.Tools.Error(err.name);
  64065. });
  64066. }
  64067. else {
  64068. navigator.getUserMedia =
  64069. navigator.getUserMedia ||
  64070. navigator.webkitGetUserMedia ||
  64071. navigator.mozGetUserMedia ||
  64072. navigator.msGetUserMedia;
  64073. if (navigator.getUserMedia) {
  64074. navigator.getUserMedia({
  64075. video: {
  64076. deviceId: constraintsDeviceId,
  64077. width: {
  64078. min: (constraints && constraints.minWidth) || 256,
  64079. max: (constraints && constraints.maxWidth) || 640,
  64080. },
  64081. height: {
  64082. min: (constraints && constraints.minHeight) || 256,
  64083. max: (constraints && constraints.maxHeight) || 480,
  64084. },
  64085. },
  64086. }, function (stream) {
  64087. if (video.mozSrcObject !== undefined) {
  64088. // hack for Firefox < 19
  64089. video.mozSrcObject = stream;
  64090. }
  64091. else {
  64092. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64093. }
  64094. video.play();
  64095. if (onReady) {
  64096. onReady(new VideoTexture("video", video, scene, true, true));
  64097. }
  64098. }, function (e) {
  64099. BABYLON.Tools.Error(e.name);
  64100. });
  64101. }
  64102. }
  64103. };
  64104. return VideoTexture;
  64105. }(BABYLON.Texture));
  64106. BABYLON.VideoTexture = VideoTexture;
  64107. })(BABYLON || (BABYLON = {}));
  64108. //# sourceMappingURL=babylon.videoTexture.js.map
  64109. var BABYLON;
  64110. (function (BABYLON) {
  64111. var RawTexture = /** @class */ (function (_super) {
  64112. __extends(RawTexture, _super);
  64113. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64114. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64115. if (invertY === void 0) { invertY = false; }
  64116. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64117. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64118. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64119. _this.format = format;
  64120. _this._engine = scene.getEngine();
  64121. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64122. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64123. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64124. return _this;
  64125. }
  64126. RawTexture.prototype.update = function (data) {
  64127. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64128. };
  64129. // Statics
  64130. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64131. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64132. if (invertY === void 0) { invertY = false; }
  64133. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64134. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64135. };
  64136. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64137. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64138. if (invertY === void 0) { invertY = false; }
  64139. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64140. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64141. };
  64142. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64143. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64144. if (invertY === void 0) { invertY = false; }
  64145. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64146. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64147. };
  64148. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64149. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64150. if (invertY === void 0) { invertY = false; }
  64151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64152. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64153. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64154. };
  64155. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64156. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64157. if (invertY === void 0) { invertY = false; }
  64158. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64159. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64160. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64161. };
  64162. return RawTexture;
  64163. }(BABYLON.Texture));
  64164. BABYLON.RawTexture = RawTexture;
  64165. })(BABYLON || (BABYLON = {}));
  64166. //# sourceMappingURL=babylon.rawTexture.js.map
  64167. var BABYLON;
  64168. (function (BABYLON) {
  64169. /**
  64170. * Class used to store 3D textures containing user data
  64171. */
  64172. var RawTexture3D = /** @class */ (function (_super) {
  64173. __extends(RawTexture3D, _super);
  64174. /**
  64175. * Create a new RawTexture3D
  64176. * @param data defines the data of the texture
  64177. * @param width defines the width of the texture
  64178. * @param height defines the height of the texture
  64179. * @param depth defines the depth of the texture
  64180. * @param format defines the texture format to use
  64181. * @param scene defines the hosting scene
  64182. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64183. * @param invertY defines if texture must be stored with Y axis inverted
  64184. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64185. */
  64186. function RawTexture3D(data, width, height, depth,
  64187. /** Gets or sets the texture format to use*/
  64188. format, scene, generateMipMaps, invertY, samplingMode) {
  64189. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64190. if (invertY === void 0) { invertY = false; }
  64191. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64192. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64193. _this.format = format;
  64194. _this._engine = scene.getEngine();
  64195. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64196. _this.is3D = true;
  64197. return _this;
  64198. }
  64199. /**
  64200. * Update the texture with new data
  64201. * @param data defines the data to store in the texture
  64202. */
  64203. RawTexture3D.prototype.update = function (data) {
  64204. if (!this._texture) {
  64205. return;
  64206. }
  64207. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64208. };
  64209. return RawTexture3D;
  64210. }(BABYLON.Texture));
  64211. BABYLON.RawTexture3D = RawTexture3D;
  64212. })(BABYLON || (BABYLON = {}));
  64213. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64214. var BABYLON;
  64215. (function (BABYLON) {
  64216. /**
  64217. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64218. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64219. */
  64220. var PostProcess = /** @class */ (function () {
  64221. /**
  64222. * Creates a new instance PostProcess
  64223. * @param name The name of the PostProcess.
  64224. * @param fragmentUrl The url of the fragment shader to be used.
  64225. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64226. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64227. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64228. * @param camera The camera to apply the render pass to.
  64229. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64230. * @param engine The engine which the post process will be applied. (default: current engine)
  64231. * @param reusable If the post process can be reused on the same frame. (default: false)
  64232. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64233. * @param textureType Type of textures used when performing the post process. (default: 0)
  64234. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64235. * @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
  64236. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64237. */
  64238. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64239. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64240. if (defines === void 0) { defines = null; }
  64241. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64242. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64243. if (blockCompilation === void 0) { blockCompilation = false; }
  64244. this.name = name;
  64245. /**
  64246. * Width of the texture to apply the post process on
  64247. */
  64248. this.width = -1;
  64249. /**
  64250. * Height of the texture to apply the post process on
  64251. */
  64252. this.height = -1;
  64253. /**
  64254. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64255. */
  64256. this._outputTexture = null;
  64257. /**
  64258. * If the buffer needs to be cleared before applying the post process. (default: true)
  64259. * Should be set to false if shader will overwrite all previous pixels.
  64260. */
  64261. this.autoClear = true;
  64262. /**
  64263. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64264. */
  64265. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64266. /**
  64267. * Animations to be used for the post processing
  64268. */
  64269. this.animations = new Array();
  64270. /**
  64271. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64272. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64273. */
  64274. this.enablePixelPerfectMode = false;
  64275. /**
  64276. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64277. */
  64278. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64279. /**
  64280. * Force textures to be a power of two (default: false)
  64281. */
  64282. this.alwaysForcePOT = false;
  64283. /**
  64284. * Number of sample textures (default: 1)
  64285. */
  64286. this.samples = 1;
  64287. /**
  64288. * Modify the scale of the post process to be the same as the viewport (default: false)
  64289. */
  64290. this.adaptScaleToCurrentViewport = false;
  64291. this._reusable = false;
  64292. /**
  64293. * Smart array of input and output textures for the post process.
  64294. */
  64295. this._textures = new BABYLON.SmartArray(2);
  64296. /**
  64297. * The index in _textures that corresponds to the output texture.
  64298. */
  64299. this._currentRenderTextureInd = 0;
  64300. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64301. this._texelSize = BABYLON.Vector2.Zero();
  64302. // Events
  64303. /**
  64304. * An event triggered when the postprocess is activated.
  64305. */
  64306. this.onActivateObservable = new BABYLON.Observable();
  64307. /**
  64308. * An event triggered when the postprocess changes its size.
  64309. */
  64310. this.onSizeChangedObservable = new BABYLON.Observable();
  64311. /**
  64312. * An event triggered when the postprocess applies its effect.
  64313. */
  64314. this.onApplyObservable = new BABYLON.Observable();
  64315. /**
  64316. * An event triggered before rendering the postprocess
  64317. */
  64318. this.onBeforeRenderObservable = new BABYLON.Observable();
  64319. /**
  64320. * An event triggered after rendering the postprocess
  64321. */
  64322. this.onAfterRenderObservable = new BABYLON.Observable();
  64323. if (camera != null) {
  64324. this._camera = camera;
  64325. this._scene = camera.getScene();
  64326. camera.attachPostProcess(this);
  64327. this._engine = this._scene.getEngine();
  64328. this._scene.postProcesses.push(this);
  64329. }
  64330. else if (engine) {
  64331. this._engine = engine;
  64332. this._engine.postProcesses.push(this);
  64333. }
  64334. this._options = options;
  64335. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64336. this._reusable = reusable || false;
  64337. this._textureType = textureType;
  64338. this._samplers = samplers || [];
  64339. this._samplers.push("textureSampler");
  64340. this._fragmentUrl = fragmentUrl;
  64341. this._vertexUrl = vertexUrl;
  64342. this._parameters = parameters || [];
  64343. this._parameters.push("scale");
  64344. this._indexParameters = indexParameters;
  64345. if (!blockCompilation) {
  64346. this.updateEffect(defines);
  64347. }
  64348. }
  64349. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64350. /**
  64351. * A function that is added to the onActivateObservable
  64352. */
  64353. set: function (callback) {
  64354. if (this._onActivateObserver) {
  64355. this.onActivateObservable.remove(this._onActivateObserver);
  64356. }
  64357. if (callback) {
  64358. this._onActivateObserver = this.onActivateObservable.add(callback);
  64359. }
  64360. },
  64361. enumerable: true,
  64362. configurable: true
  64363. });
  64364. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64365. /**
  64366. * A function that is added to the onSizeChangedObservable
  64367. */
  64368. set: function (callback) {
  64369. if (this._onSizeChangedObserver) {
  64370. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64371. }
  64372. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64373. },
  64374. enumerable: true,
  64375. configurable: true
  64376. });
  64377. Object.defineProperty(PostProcess.prototype, "onApply", {
  64378. /**
  64379. * A function that is added to the onApplyObservable
  64380. */
  64381. set: function (callback) {
  64382. if (this._onApplyObserver) {
  64383. this.onApplyObservable.remove(this._onApplyObserver);
  64384. }
  64385. this._onApplyObserver = this.onApplyObservable.add(callback);
  64386. },
  64387. enumerable: true,
  64388. configurable: true
  64389. });
  64390. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64391. /**
  64392. * A function that is added to the onBeforeRenderObservable
  64393. */
  64394. set: function (callback) {
  64395. if (this._onBeforeRenderObserver) {
  64396. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64397. }
  64398. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64399. },
  64400. enumerable: true,
  64401. configurable: true
  64402. });
  64403. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64404. /**
  64405. * A function that is added to the onAfterRenderObservable
  64406. */
  64407. set: function (callback) {
  64408. if (this._onAfterRenderObserver) {
  64409. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64410. }
  64411. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64412. },
  64413. enumerable: true,
  64414. configurable: true
  64415. });
  64416. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64417. /**
  64418. * 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
  64419. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64420. */
  64421. get: function () {
  64422. return this._textures.data[this._currentRenderTextureInd];
  64423. },
  64424. set: function (value) {
  64425. this._forcedOutputTexture = value;
  64426. },
  64427. enumerable: true,
  64428. configurable: true
  64429. });
  64430. /**
  64431. * Gets the camera which post process is applied to.
  64432. * @returns The camera the post process is applied to.
  64433. */
  64434. PostProcess.prototype.getCamera = function () {
  64435. return this._camera;
  64436. };
  64437. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64438. /**
  64439. * Gets the texel size of the postprocess.
  64440. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64441. */
  64442. get: function () {
  64443. if (this._shareOutputWithPostProcess) {
  64444. return this._shareOutputWithPostProcess.texelSize;
  64445. }
  64446. if (this._forcedOutputTexture) {
  64447. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64448. }
  64449. return this._texelSize;
  64450. },
  64451. enumerable: true,
  64452. configurable: true
  64453. });
  64454. /**
  64455. * Gets the engine which this post process belongs to.
  64456. * @returns The engine the post process was enabled with.
  64457. */
  64458. PostProcess.prototype.getEngine = function () {
  64459. return this._engine;
  64460. };
  64461. /**
  64462. * The effect that is created when initializing the post process.
  64463. * @returns The created effect corrisponding the the postprocess.
  64464. */
  64465. PostProcess.prototype.getEffect = function () {
  64466. return this._effect;
  64467. };
  64468. /**
  64469. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64470. * @param postProcess The post process to share the output with.
  64471. * @returns This post process.
  64472. */
  64473. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64474. this._disposeTextures();
  64475. this._shareOutputWithPostProcess = postProcess;
  64476. return this;
  64477. };
  64478. /**
  64479. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64480. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64481. */
  64482. PostProcess.prototype.useOwnOutput = function () {
  64483. if (this._textures.length == 0) {
  64484. this._textures = new BABYLON.SmartArray(2);
  64485. }
  64486. this._shareOutputWithPostProcess = null;
  64487. };
  64488. /**
  64489. * Updates the effect with the current post process compile time values and recompiles the shader.
  64490. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64491. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64492. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64493. * @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
  64494. * @param onCompiled Called when the shader has been compiled.
  64495. * @param onError Called if there is an error when compiling a shader.
  64496. */
  64497. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64498. if (defines === void 0) { defines = null; }
  64499. if (uniforms === void 0) { uniforms = null; }
  64500. if (samplers === void 0) { samplers = null; }
  64501. 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);
  64502. };
  64503. /**
  64504. * The post process is reusable if it can be used multiple times within one frame.
  64505. * @returns If the post process is reusable
  64506. */
  64507. PostProcess.prototype.isReusable = function () {
  64508. return this._reusable;
  64509. };
  64510. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64511. PostProcess.prototype.markTextureDirty = function () {
  64512. this.width = -1;
  64513. };
  64514. /**
  64515. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64516. * 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.
  64517. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64518. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64519. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64520. * @returns The target texture that was bound to be written to.
  64521. */
  64522. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64523. var _this = this;
  64524. if (sourceTexture === void 0) { sourceTexture = null; }
  64525. camera = camera || this._camera;
  64526. var scene = camera.getScene();
  64527. var engine = scene.getEngine();
  64528. var maxSize = engine.getCaps().maxTextureSize;
  64529. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64530. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64531. // 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
  64532. var webVRCamera = camera.parent;
  64533. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64534. requiredWidth /= 2;
  64535. }
  64536. var desiredWidth = (this._options.width || requiredWidth);
  64537. var desiredHeight = this._options.height || requiredHeight;
  64538. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64539. if (this.adaptScaleToCurrentViewport) {
  64540. var currentViewport = engine.currentViewport;
  64541. if (currentViewport) {
  64542. desiredWidth *= currentViewport.width;
  64543. desiredHeight *= currentViewport.height;
  64544. }
  64545. }
  64546. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64547. if (!this._options.width) {
  64548. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64549. }
  64550. if (!this._options.height) {
  64551. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64552. }
  64553. }
  64554. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64555. if (this._textures.length > 0) {
  64556. for (var i = 0; i < this._textures.length; i++) {
  64557. this._engine._releaseTexture(this._textures.data[i]);
  64558. }
  64559. this._textures.reset();
  64560. }
  64561. this.width = desiredWidth;
  64562. this.height = desiredHeight;
  64563. var textureSize = { width: this.width, height: this.height };
  64564. var textureOptions = {
  64565. generateMipMaps: false,
  64566. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  64567. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  64568. samplingMode: this.renderTargetSamplingMode,
  64569. type: this._textureType
  64570. };
  64571. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64572. if (this._reusable) {
  64573. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  64574. }
  64575. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  64576. this.onSizeChangedObservable.notifyObservers(this);
  64577. }
  64578. this._textures.forEach(function (texture) {
  64579. if (texture.samples !== _this.samples) {
  64580. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  64581. }
  64582. });
  64583. }
  64584. var target;
  64585. if (this._shareOutputWithPostProcess) {
  64586. target = this._shareOutputWithPostProcess.inputTexture;
  64587. }
  64588. else if (this._forcedOutputTexture) {
  64589. target = this._forcedOutputTexture;
  64590. this.width = this._forcedOutputTexture.width;
  64591. this.height = this._forcedOutputTexture.height;
  64592. }
  64593. else {
  64594. target = this.inputTexture;
  64595. }
  64596. // Bind the input of this post process to be used as the output of the previous post process.
  64597. if (this.enablePixelPerfectMode) {
  64598. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  64599. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  64600. }
  64601. else {
  64602. this._scaleRatio.copyFromFloats(1, 1);
  64603. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  64604. }
  64605. this.onActivateObservable.notifyObservers(camera);
  64606. // Clear
  64607. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  64608. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  64609. }
  64610. if (this._reusable) {
  64611. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  64612. }
  64613. return target;
  64614. };
  64615. Object.defineProperty(PostProcess.prototype, "isSupported", {
  64616. /**
  64617. * If the post process is supported.
  64618. */
  64619. get: function () {
  64620. return this._effect.isSupported;
  64621. },
  64622. enumerable: true,
  64623. configurable: true
  64624. });
  64625. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  64626. /**
  64627. * The aspect ratio of the output texture.
  64628. */
  64629. get: function () {
  64630. if (this._shareOutputWithPostProcess) {
  64631. return this._shareOutputWithPostProcess.aspectRatio;
  64632. }
  64633. if (this._forcedOutputTexture) {
  64634. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  64635. }
  64636. return this.width / this.height;
  64637. },
  64638. enumerable: true,
  64639. configurable: true
  64640. });
  64641. /**
  64642. * Get a value indicating if the post-process is ready to be used
  64643. * @returns true if the post-process is ready (shader is compiled)
  64644. */
  64645. PostProcess.prototype.isReady = function () {
  64646. return this._effect && this._effect.isReady();
  64647. };
  64648. /**
  64649. * Binds all textures and uniforms to the shader, this will be run on every pass.
  64650. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  64651. */
  64652. PostProcess.prototype.apply = function () {
  64653. // Check
  64654. if (!this._effect || !this._effect.isReady())
  64655. return null;
  64656. // States
  64657. this._engine.enableEffect(this._effect);
  64658. this._engine.setState(false);
  64659. this._engine.setDepthBuffer(false);
  64660. this._engine.setDepthWrite(false);
  64661. // Alpha
  64662. this._engine.setAlphaMode(this.alphaMode);
  64663. if (this.alphaConstants) {
  64664. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  64665. }
  64666. // Bind the output texture of the preivous post process as the input to this post process.
  64667. var source;
  64668. if (this._shareOutputWithPostProcess) {
  64669. source = this._shareOutputWithPostProcess.inputTexture;
  64670. }
  64671. else if (this._forcedOutputTexture) {
  64672. source = this._forcedOutputTexture;
  64673. }
  64674. else {
  64675. source = this.inputTexture;
  64676. }
  64677. this._effect._bindTexture("textureSampler", source);
  64678. // Parameters
  64679. this._effect.setVector2("scale", this._scaleRatio);
  64680. this.onApplyObservable.notifyObservers(this._effect);
  64681. return this._effect;
  64682. };
  64683. PostProcess.prototype._disposeTextures = function () {
  64684. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  64685. return;
  64686. }
  64687. if (this._textures.length > 0) {
  64688. for (var i = 0; i < this._textures.length; i++) {
  64689. this._engine._releaseTexture(this._textures.data[i]);
  64690. }
  64691. }
  64692. this._textures.dispose();
  64693. };
  64694. /**
  64695. * Disposes the post process.
  64696. * @param camera The camera to dispose the post process on.
  64697. */
  64698. PostProcess.prototype.dispose = function (camera) {
  64699. camera = camera || this._camera;
  64700. this._disposeTextures();
  64701. if (this._scene) {
  64702. var index_1 = this._scene.postProcesses.indexOf(this);
  64703. if (index_1 !== -1) {
  64704. this._scene.postProcesses.splice(index_1, 1);
  64705. }
  64706. }
  64707. else {
  64708. var index_2 = this._engine.postProcesses.indexOf(this);
  64709. if (index_2 !== -1) {
  64710. this._engine.postProcesses.splice(index_2, 1);
  64711. }
  64712. }
  64713. if (!camera) {
  64714. return;
  64715. }
  64716. camera.detachPostProcess(this);
  64717. var index = camera._postProcesses.indexOf(this);
  64718. if (index === 0 && camera._postProcesses.length > 0) {
  64719. var firstPostProcess = this._camera._getFirstPostProcess();
  64720. if (firstPostProcess) {
  64721. firstPostProcess.markTextureDirty();
  64722. }
  64723. }
  64724. this.onActivateObservable.clear();
  64725. this.onAfterRenderObservable.clear();
  64726. this.onApplyObservable.clear();
  64727. this.onBeforeRenderObservable.clear();
  64728. this.onSizeChangedObservable.clear();
  64729. };
  64730. return PostProcess;
  64731. }());
  64732. BABYLON.PostProcess = PostProcess;
  64733. })(BABYLON || (BABYLON = {}));
  64734. //# sourceMappingURL=babylon.postProcess.js.map
  64735. var BABYLON;
  64736. (function (BABYLON) {
  64737. var PassPostProcess = /** @class */ (function (_super) {
  64738. __extends(PassPostProcess, _super);
  64739. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  64740. if (camera === void 0) { camera = null; }
  64741. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64742. if (blockCompilation === void 0) { blockCompilation = false; }
  64743. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  64744. }
  64745. return PassPostProcess;
  64746. }(BABYLON.PostProcess));
  64747. BABYLON.PassPostProcess = PassPostProcess;
  64748. })(BABYLON || (BABYLON = {}));
  64749. //# sourceMappingURL=babylon.passPostProcess.js.map
  64750. var __assign = (this && this.__assign) || Object.assign || function(t) {
  64751. for (var s, i = 1, n = arguments.length; i < n; i++) {
  64752. s = arguments[i];
  64753. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  64754. t[p] = s[p];
  64755. }
  64756. return t;
  64757. };
  64758. var BABYLON;
  64759. (function (BABYLON) {
  64760. /**
  64761. * Default implementation IShadowGenerator.
  64762. * This is the main object responsible of generating shadows in the framework.
  64763. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  64764. */
  64765. var ShadowGenerator = /** @class */ (function () {
  64766. /**
  64767. * Creates a ShadowGenerator object.
  64768. * A ShadowGenerator is the required tool to use the shadows.
  64769. * Each light casting shadows needs to use its own ShadowGenerator.
  64770. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  64771. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  64772. * @param light The light object generating the shadows.
  64773. * @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.
  64774. */
  64775. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  64776. this._bias = 0.00005;
  64777. this._normalBias = 0;
  64778. this._blurBoxOffset = 1;
  64779. this._blurScale = 2;
  64780. this._blurKernel = 1;
  64781. this._useKernelBlur = false;
  64782. this._filter = ShadowGenerator.FILTER_NONE;
  64783. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  64784. this._contactHardeningLightSizeUVRatio = 0.1;
  64785. this._darkness = 0;
  64786. this._transparencyShadow = false;
  64787. /**
  64788. * Controls the extent to which the shadows fade out at the edge of the frustum
  64789. * Used only by directionals and spots
  64790. */
  64791. this.frustumEdgeFalloff = 0;
  64792. /**
  64793. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  64794. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  64795. * It might on the other hand introduce peter panning.
  64796. */
  64797. this.forceBackFacesOnly = false;
  64798. this._lightDirection = BABYLON.Vector3.Zero();
  64799. this._viewMatrix = BABYLON.Matrix.Zero();
  64800. this._projectionMatrix = BABYLON.Matrix.Zero();
  64801. this._transformMatrix = BABYLON.Matrix.Zero();
  64802. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64803. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  64804. this._currentFaceIndex = 0;
  64805. this._currentFaceIndexCache = 0;
  64806. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  64807. this._mapSize = mapSize;
  64808. this._light = light;
  64809. this._scene = light.getScene();
  64810. light._shadowGenerator = this;
  64811. // Texture type fallback from float to int if not supported.
  64812. var caps = this._scene.getEngine().getCaps();
  64813. if (!useFullFloatFirst) {
  64814. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64815. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64816. }
  64817. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64818. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64819. }
  64820. else {
  64821. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64822. }
  64823. }
  64824. else {
  64825. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  64826. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  64827. }
  64828. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  64829. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64830. }
  64831. else {
  64832. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  64833. }
  64834. }
  64835. this._initializeGenerator();
  64836. this._applyFilterValues();
  64837. }
  64838. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  64839. /**
  64840. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  64841. */
  64842. get: function () {
  64843. return this._bias;
  64844. },
  64845. /**
  64846. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  64847. */
  64848. set: function (bias) {
  64849. this._bias = bias;
  64850. },
  64851. enumerable: true,
  64852. configurable: true
  64853. });
  64854. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  64855. /**
  64856. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64857. */
  64858. get: function () {
  64859. return this._normalBias;
  64860. },
  64861. /**
  64862. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  64863. */
  64864. set: function (normalBias) {
  64865. this._normalBias = normalBias;
  64866. },
  64867. enumerable: true,
  64868. configurable: true
  64869. });
  64870. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  64871. /**
  64872. * Gets the blur box offset: offset applied during the blur pass.
  64873. * Only usefull if useKernelBlur = false
  64874. */
  64875. get: function () {
  64876. return this._blurBoxOffset;
  64877. },
  64878. /**
  64879. * Sets the blur box offset: offset applied during the blur pass.
  64880. * Only usefull if useKernelBlur = false
  64881. */
  64882. set: function (value) {
  64883. if (this._blurBoxOffset === value) {
  64884. return;
  64885. }
  64886. this._blurBoxOffset = value;
  64887. this._disposeBlurPostProcesses();
  64888. },
  64889. enumerable: true,
  64890. configurable: true
  64891. });
  64892. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  64893. /**
  64894. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  64895. * 2 means half of the size.
  64896. */
  64897. get: function () {
  64898. return this._blurScale;
  64899. },
  64900. /**
  64901. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  64902. * 2 means half of the size.
  64903. */
  64904. set: function (value) {
  64905. if (this._blurScale === value) {
  64906. return;
  64907. }
  64908. this._blurScale = value;
  64909. this._disposeBlurPostProcesses();
  64910. },
  64911. enumerable: true,
  64912. configurable: true
  64913. });
  64914. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  64915. /**
  64916. * Gets the blur kernel: kernel size of the blur pass.
  64917. * Only usefull if useKernelBlur = true
  64918. */
  64919. get: function () {
  64920. return this._blurKernel;
  64921. },
  64922. /**
  64923. * Sets the blur kernel: kernel size of the blur pass.
  64924. * Only usefull if useKernelBlur = true
  64925. */
  64926. set: function (value) {
  64927. if (this._blurKernel === value) {
  64928. return;
  64929. }
  64930. this._blurKernel = value;
  64931. this._disposeBlurPostProcesses();
  64932. },
  64933. enumerable: true,
  64934. configurable: true
  64935. });
  64936. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  64937. /**
  64938. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  64939. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64940. */
  64941. get: function () {
  64942. return this._useKernelBlur;
  64943. },
  64944. /**
  64945. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  64946. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  64947. */
  64948. set: function (value) {
  64949. if (this._useKernelBlur === value) {
  64950. return;
  64951. }
  64952. this._useKernelBlur = value;
  64953. this._disposeBlurPostProcesses();
  64954. },
  64955. enumerable: true,
  64956. configurable: true
  64957. });
  64958. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  64959. /**
  64960. * Gets the depth scale used in ESM mode.
  64961. */
  64962. get: function () {
  64963. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  64964. },
  64965. /**
  64966. * Sets the depth scale used in ESM mode.
  64967. * This can override the scale stored on the light.
  64968. */
  64969. set: function (value) {
  64970. this._depthScale = value;
  64971. },
  64972. enumerable: true,
  64973. configurable: true
  64974. });
  64975. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  64976. /**
  64977. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  64978. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64979. */
  64980. get: function () {
  64981. return this._filter;
  64982. },
  64983. /**
  64984. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  64985. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  64986. */
  64987. set: function (value) {
  64988. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  64989. if (this._light.needCube()) {
  64990. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  64991. this.useExponentialShadowMap = true;
  64992. return;
  64993. }
  64994. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  64995. this.useCloseExponentialShadowMap = true;
  64996. return;
  64997. }
  64998. // PCF on cubemap would also be expensive
  64999. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65000. this.usePoissonSampling = true;
  65001. return;
  65002. }
  65003. }
  65004. // Weblg1 fallback for PCF.
  65005. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65006. if (this._scene.getEngine().webGLVersion === 1) {
  65007. this.usePoissonSampling = true;
  65008. return;
  65009. }
  65010. }
  65011. if (this._filter === value) {
  65012. return;
  65013. }
  65014. this._filter = value;
  65015. this._disposeBlurPostProcesses();
  65016. this._applyFilterValues();
  65017. this._light._markMeshesAsLightDirty();
  65018. },
  65019. enumerable: true,
  65020. configurable: true
  65021. });
  65022. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65023. /**
  65024. * Gets if the current filter is set to Poisson Sampling.
  65025. */
  65026. get: function () {
  65027. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65028. },
  65029. /**
  65030. * Sets the current filter to Poisson Sampling.
  65031. */
  65032. set: function (value) {
  65033. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65034. return;
  65035. }
  65036. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65037. },
  65038. enumerable: true,
  65039. configurable: true
  65040. });
  65041. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65042. /**
  65043. * Gets if the current filter is set to VSM.
  65044. * DEPRECATED. Should use useExponentialShadowMap instead.
  65045. */
  65046. get: function () {
  65047. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65048. return this.useExponentialShadowMap;
  65049. },
  65050. /**
  65051. * Sets the current filter is to VSM.
  65052. * DEPRECATED. Should use useExponentialShadowMap instead.
  65053. */
  65054. set: function (value) {
  65055. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65056. this.useExponentialShadowMap = value;
  65057. },
  65058. enumerable: true,
  65059. configurable: true
  65060. });
  65061. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65062. /**
  65063. * Gets if the current filter is set to blurred VSM.
  65064. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65065. */
  65066. get: function () {
  65067. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65068. return this.useBlurExponentialShadowMap;
  65069. },
  65070. /**
  65071. * Sets the current filter is to blurred VSM.
  65072. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65073. */
  65074. set: function (value) {
  65075. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65076. this.useBlurExponentialShadowMap = value;
  65077. },
  65078. enumerable: true,
  65079. configurable: true
  65080. });
  65081. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65082. /**
  65083. * Gets if the current filter is set to ESM.
  65084. */
  65085. get: function () {
  65086. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65087. },
  65088. /**
  65089. * Sets the current filter is to ESM.
  65090. */
  65091. set: function (value) {
  65092. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65093. return;
  65094. }
  65095. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65096. },
  65097. enumerable: true,
  65098. configurable: true
  65099. });
  65100. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65101. /**
  65102. * Gets if the current filter is set to filtered ESM.
  65103. */
  65104. get: function () {
  65105. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65106. },
  65107. /**
  65108. * Gets if the current filter is set to filtered ESM.
  65109. */
  65110. set: function (value) {
  65111. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65112. return;
  65113. }
  65114. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65115. },
  65116. enumerable: true,
  65117. configurable: true
  65118. });
  65119. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65120. /**
  65121. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65122. * exponential to prevent steep falloff artifacts).
  65123. */
  65124. get: function () {
  65125. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65126. },
  65127. /**
  65128. * Sets the current filter to "close ESM" (using the inverse of the
  65129. * exponential to prevent steep falloff artifacts).
  65130. */
  65131. set: function (value) {
  65132. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65133. return;
  65134. }
  65135. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65136. },
  65137. enumerable: true,
  65138. configurable: true
  65139. });
  65140. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65141. /**
  65142. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65143. * exponential to prevent steep falloff artifacts).
  65144. */
  65145. get: function () {
  65146. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65147. },
  65148. /**
  65149. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65150. * exponential to prevent steep falloff artifacts).
  65151. */
  65152. set: function (value) {
  65153. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65154. return;
  65155. }
  65156. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65157. },
  65158. enumerable: true,
  65159. configurable: true
  65160. });
  65161. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65162. /**
  65163. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65164. */
  65165. get: function () {
  65166. return this.filter === ShadowGenerator.FILTER_PCF;
  65167. },
  65168. /**
  65169. * Sets the current filter to "PCF" (percentage closer filtering).
  65170. */
  65171. set: function (value) {
  65172. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65173. return;
  65174. }
  65175. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65176. },
  65177. enumerable: true,
  65178. configurable: true
  65179. });
  65180. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65181. /**
  65182. * Gets the PCF or PCSS Quality.
  65183. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65184. */
  65185. get: function () {
  65186. return this._filteringQuality;
  65187. },
  65188. /**
  65189. * Sets the PCF or PCSS Quality.
  65190. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65191. */
  65192. set: function (filteringQuality) {
  65193. this._filteringQuality = filteringQuality;
  65194. },
  65195. enumerable: true,
  65196. configurable: true
  65197. });
  65198. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65199. /**
  65200. * Gets if the current filter is set to "PCSS" (contact hardening).
  65201. */
  65202. get: function () {
  65203. return this.filter === ShadowGenerator.FILTER_PCSS;
  65204. },
  65205. /**
  65206. * Sets the current filter to "PCSS" (contact hardening).
  65207. */
  65208. set: function (value) {
  65209. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65210. return;
  65211. }
  65212. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65213. },
  65214. enumerable: true,
  65215. configurable: true
  65216. });
  65217. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65218. /**
  65219. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65220. * Using a ratio helps keeping shape stability independently of the map size.
  65221. *
  65222. * It does not account for the light projection as it was having too much
  65223. * instability during the light setup or during light position changes.
  65224. *
  65225. * Only valid if useContactHardeningShadow is true.
  65226. */
  65227. get: function () {
  65228. return this._contactHardeningLightSizeUVRatio;
  65229. },
  65230. /**
  65231. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65232. * Using a ratio helps keeping shape stability independently of the map size.
  65233. *
  65234. * It does not account for the light projection as it was having too much
  65235. * instability during the light setup or during light position changes.
  65236. *
  65237. * Only valid if useContactHardeningShadow is true.
  65238. */
  65239. set: function (contactHardeningLightSizeUVRatio) {
  65240. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65241. },
  65242. enumerable: true,
  65243. configurable: true
  65244. });
  65245. /**
  65246. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65247. * 0 means strongest and 1 would means no shadow.
  65248. * @returns the darkness.
  65249. */
  65250. ShadowGenerator.prototype.getDarkness = function () {
  65251. return this._darkness;
  65252. };
  65253. /**
  65254. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65255. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65256. * @returns the shadow generator allowing fluent coding.
  65257. */
  65258. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65259. if (darkness >= 1.0)
  65260. this._darkness = 1.0;
  65261. else if (darkness <= 0.0)
  65262. this._darkness = 0.0;
  65263. else
  65264. this._darkness = darkness;
  65265. return this;
  65266. };
  65267. /**
  65268. * Sets the ability to have transparent shadow (boolean).
  65269. * @param transparent True if transparent else False
  65270. * @returns the shadow generator allowing fluent coding
  65271. */
  65272. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65273. this._transparencyShadow = transparent;
  65274. return this;
  65275. };
  65276. /**
  65277. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65278. * @returns The render target texture if present otherwise, null
  65279. */
  65280. ShadowGenerator.prototype.getShadowMap = function () {
  65281. return this._shadowMap;
  65282. };
  65283. /**
  65284. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65285. * @returns The render target texture if the shadow map is present otherwise, null
  65286. */
  65287. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65288. if (this._shadowMap2) {
  65289. return this._shadowMap2;
  65290. }
  65291. return this._shadowMap;
  65292. };
  65293. /**
  65294. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65295. * @param mesh Mesh to add
  65296. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65297. * @returns the Shadow Generator itself
  65298. */
  65299. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65300. if (includeDescendants === void 0) { includeDescendants = true; }
  65301. if (!this._shadowMap) {
  65302. return this;
  65303. }
  65304. if (!this._shadowMap.renderList) {
  65305. this._shadowMap.renderList = [];
  65306. }
  65307. this._shadowMap.renderList.push(mesh);
  65308. if (includeDescendants) {
  65309. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65310. }
  65311. return this;
  65312. var _a;
  65313. };
  65314. /**
  65315. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65316. * @param mesh Mesh to remove
  65317. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65318. * @returns the Shadow Generator itself
  65319. */
  65320. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65321. if (includeDescendants === void 0) { includeDescendants = true; }
  65322. if (!this._shadowMap || !this._shadowMap.renderList) {
  65323. return this;
  65324. }
  65325. var index = this._shadowMap.renderList.indexOf(mesh);
  65326. if (index !== -1) {
  65327. this._shadowMap.renderList.splice(index, 1);
  65328. }
  65329. if (includeDescendants) {
  65330. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65331. var child = _a[_i];
  65332. this.removeShadowCaster(child);
  65333. }
  65334. }
  65335. return this;
  65336. };
  65337. /**
  65338. * Returns the associated light object.
  65339. * @returns the light generating the shadow
  65340. */
  65341. ShadowGenerator.prototype.getLight = function () {
  65342. return this._light;
  65343. };
  65344. ShadowGenerator.prototype._initializeGenerator = function () {
  65345. this._light._markMeshesAsLightDirty();
  65346. this._initializeShadowMap();
  65347. };
  65348. ShadowGenerator.prototype._initializeShadowMap = function () {
  65349. var _this = this;
  65350. // Render target
  65351. var engine = this._scene.getEngine();
  65352. if (engine.webGLVersion > 1) {
  65353. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65354. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65355. }
  65356. else {
  65357. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65358. }
  65359. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65360. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65361. this._shadowMap.anisotropicFilteringLevel = 1;
  65362. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65363. this._shadowMap.renderParticles = false;
  65364. this._shadowMap.ignoreCameraViewport = true;
  65365. // Record Face Index before render.
  65366. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65367. _this._currentFaceIndex = faceIndex;
  65368. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65369. engine.setColorWrite(false);
  65370. }
  65371. });
  65372. // Custom render function.
  65373. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65374. // Blur if required afer render.
  65375. this._shadowMap.onAfterUnbindObservable.add(function () {
  65376. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65377. engine.setColorWrite(true);
  65378. }
  65379. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65380. return;
  65381. }
  65382. var shadowMap = _this.getShadowMapForRendering();
  65383. if (shadowMap) {
  65384. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65385. }
  65386. });
  65387. // Clear according to the chosen filter.
  65388. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65389. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65390. this._shadowMap.onClearObservable.add(function (engine) {
  65391. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65392. engine.clear(clearOne, false, true, false);
  65393. }
  65394. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65395. engine.clear(clearZero, true, true, false);
  65396. }
  65397. else {
  65398. engine.clear(clearOne, true, true, false);
  65399. }
  65400. });
  65401. };
  65402. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65403. var _this = this;
  65404. var engine = this._scene.getEngine();
  65405. var targetSize = this._mapSize / this.blurScale;
  65406. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65407. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65408. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65409. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65410. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65411. }
  65412. if (this.useKernelBlur) {
  65413. 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);
  65414. this._kernelBlurXPostprocess.width = targetSize;
  65415. this._kernelBlurXPostprocess.height = targetSize;
  65416. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65417. effect.setTexture("textureSampler", _this._shadowMap);
  65418. });
  65419. 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);
  65420. this._kernelBlurXPostprocess.autoClear = false;
  65421. this._kernelBlurYPostprocess.autoClear = false;
  65422. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65423. this._kernelBlurXPostprocess.packedFloat = true;
  65424. this._kernelBlurYPostprocess.packedFloat = true;
  65425. }
  65426. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65427. }
  65428. else {
  65429. 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);
  65430. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65431. effect.setFloat2("screenSize", targetSize, targetSize);
  65432. effect.setTexture("textureSampler", _this._shadowMap);
  65433. });
  65434. this._boxBlurPostprocess.autoClear = false;
  65435. this._blurPostProcesses = [this._boxBlurPostprocess];
  65436. }
  65437. };
  65438. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65439. var index;
  65440. var engine = this._scene.getEngine();
  65441. if (depthOnlySubMeshes.length) {
  65442. engine.setColorWrite(false);
  65443. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65444. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65445. }
  65446. engine.setColorWrite(true);
  65447. }
  65448. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65449. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65450. }
  65451. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65452. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65453. }
  65454. if (this._transparencyShadow) {
  65455. for (index = 0; index < transparentSubMeshes.length; index++) {
  65456. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65457. }
  65458. }
  65459. };
  65460. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65461. var _this = this;
  65462. var mesh = subMesh.getRenderingMesh();
  65463. var scene = this._scene;
  65464. var engine = scene.getEngine();
  65465. var material = subMesh.getMaterial();
  65466. if (!material) {
  65467. return;
  65468. }
  65469. // Culling
  65470. engine.setState(material.backFaceCulling);
  65471. // Managing instances
  65472. var batch = mesh._getInstancesRenderList(subMesh._id);
  65473. if (batch.mustReturn) {
  65474. return;
  65475. }
  65476. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65477. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65478. engine.enableEffect(this._effect);
  65479. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65480. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65481. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65482. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65483. this._effect.setVector3("lightData", this._cachedDirection);
  65484. }
  65485. else {
  65486. this._effect.setVector3("lightData", this._cachedPosition);
  65487. }
  65488. if (scene.activeCamera) {
  65489. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65490. }
  65491. // Alpha test
  65492. if (material && material.needAlphaTesting()) {
  65493. var alphaTexture = material.getAlphaTestTexture();
  65494. if (alphaTexture) {
  65495. this._effect.setTexture("diffuseSampler", alphaTexture);
  65496. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65497. }
  65498. }
  65499. // Bones
  65500. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65501. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65502. }
  65503. // Morph targets
  65504. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65505. if (this.forceBackFacesOnly) {
  65506. engine.setState(true, 0, false, true);
  65507. }
  65508. // Draw
  65509. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65510. if (this.forceBackFacesOnly) {
  65511. engine.setState(true, 0, false, false);
  65512. }
  65513. }
  65514. else {
  65515. // Need to reset refresh rate of the shadowMap
  65516. if (this._shadowMap) {
  65517. this._shadowMap.resetRefreshCounter();
  65518. }
  65519. }
  65520. };
  65521. ShadowGenerator.prototype._applyFilterValues = function () {
  65522. if (!this._shadowMap) {
  65523. return;
  65524. }
  65525. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65526. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65527. }
  65528. else {
  65529. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65530. }
  65531. };
  65532. /**
  65533. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65534. * @param onCompiled Callback triggered at the and of the effects compilation
  65535. * @param options Sets of optional options forcing the compilation with different modes
  65536. */
  65537. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65538. var _this = this;
  65539. var localOptions = __assign({ useInstances: false }, options);
  65540. var shadowMap = this.getShadowMap();
  65541. if (!shadowMap) {
  65542. if (onCompiled) {
  65543. onCompiled(this);
  65544. }
  65545. return;
  65546. }
  65547. var renderList = shadowMap.renderList;
  65548. if (!renderList) {
  65549. if (onCompiled) {
  65550. onCompiled(this);
  65551. }
  65552. return;
  65553. }
  65554. var subMeshes = new Array();
  65555. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65556. var mesh = renderList_1[_i];
  65557. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65558. }
  65559. if (subMeshes.length === 0) {
  65560. if (onCompiled) {
  65561. onCompiled(this);
  65562. }
  65563. return;
  65564. }
  65565. var currentIndex = 0;
  65566. var checkReady = function () {
  65567. if (!_this._scene || !_this._scene.getEngine()) {
  65568. return;
  65569. }
  65570. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  65571. currentIndex++;
  65572. if (currentIndex >= subMeshes.length) {
  65573. if (onCompiled) {
  65574. onCompiled(_this);
  65575. }
  65576. return;
  65577. }
  65578. }
  65579. setTimeout(checkReady, 16);
  65580. };
  65581. checkReady();
  65582. };
  65583. /**
  65584. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65585. * @param options Sets of optional options forcing the compilation with different modes
  65586. * @returns A promise that resolves when the compilation completes
  65587. */
  65588. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  65589. var _this = this;
  65590. return new Promise(function (resolve) {
  65591. _this.forceCompilation(function () {
  65592. resolve();
  65593. }, options);
  65594. });
  65595. };
  65596. /**
  65597. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  65598. * @param subMesh The submesh we want to render in the shadow map
  65599. * @param useInstances Defines wether will draw in the map using instances
  65600. * @returns true if ready otherwise, false
  65601. */
  65602. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  65603. var defines = [];
  65604. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65605. defines.push("#define FLOAT");
  65606. }
  65607. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65608. defines.push("#define ESM");
  65609. }
  65610. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  65611. defines.push("#define DEPTHTEXTURE");
  65612. }
  65613. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65614. var mesh = subMesh.getMesh();
  65615. var material = subMesh.getMaterial();
  65616. // Normal bias.
  65617. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  65618. attribs.push(BABYLON.VertexBuffer.NormalKind);
  65619. defines.push("#define NORMAL");
  65620. if (mesh.nonUniformScaling) {
  65621. defines.push("#define NONUNIFORMSCALING");
  65622. }
  65623. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65624. defines.push("#define DIRECTIONINLIGHTDATA");
  65625. }
  65626. }
  65627. // Alpha test
  65628. if (material && material.needAlphaTesting()) {
  65629. var alphaTexture = material.getAlphaTestTexture();
  65630. if (alphaTexture) {
  65631. defines.push("#define ALPHATEST");
  65632. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65633. attribs.push(BABYLON.VertexBuffer.UVKind);
  65634. defines.push("#define UV1");
  65635. }
  65636. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65637. if (alphaTexture.coordinatesIndex === 1) {
  65638. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65639. defines.push("#define UV2");
  65640. }
  65641. }
  65642. }
  65643. }
  65644. // Bones
  65645. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65646. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65647. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65648. if (mesh.numBoneInfluencers > 4) {
  65649. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65650. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65651. }
  65652. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65653. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  65654. }
  65655. else {
  65656. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65657. }
  65658. // Morph targets
  65659. var manager = mesh.morphTargetManager;
  65660. var morphInfluencers = 0;
  65661. if (manager) {
  65662. if (manager.numInfluencers > 0) {
  65663. defines.push("#define MORPHTARGETS");
  65664. morphInfluencers = manager.numInfluencers;
  65665. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  65666. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  65667. }
  65668. }
  65669. // Instances
  65670. if (useInstances) {
  65671. defines.push("#define INSTANCES");
  65672. attribs.push("world0");
  65673. attribs.push("world1");
  65674. attribs.push("world2");
  65675. attribs.push("world3");
  65676. }
  65677. // Get correct effect
  65678. var join = defines.join("\n");
  65679. if (this._cachedDefines !== join) {
  65680. this._cachedDefines = join;
  65681. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  65682. }
  65683. if (!this._effect.isReady()) {
  65684. return false;
  65685. }
  65686. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65687. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  65688. this._initializeBlurRTTAndPostProcesses();
  65689. }
  65690. }
  65691. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  65692. return false;
  65693. }
  65694. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  65695. return false;
  65696. }
  65697. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  65698. return false;
  65699. }
  65700. return true;
  65701. };
  65702. /**
  65703. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  65704. * @param defines Defines of the material we want to update
  65705. * @param lightIndex Index of the light in the enabled light list of the material
  65706. */
  65707. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  65708. var scene = this._scene;
  65709. var light = this._light;
  65710. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65711. return;
  65712. }
  65713. defines["SHADOW" + lightIndex] = true;
  65714. if (this.useContactHardeningShadow) {
  65715. defines["SHADOWPCSS" + lightIndex] = true;
  65716. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65717. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65718. }
  65719. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65720. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65721. }
  65722. // else default to high.
  65723. }
  65724. if (this.usePercentageCloserFiltering) {
  65725. defines["SHADOWPCF" + lightIndex] = true;
  65726. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  65727. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  65728. }
  65729. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  65730. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  65731. }
  65732. // else default to high.
  65733. }
  65734. else if (this.usePoissonSampling) {
  65735. defines["SHADOWPOISSON" + lightIndex] = true;
  65736. }
  65737. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  65738. defines["SHADOWESM" + lightIndex] = true;
  65739. }
  65740. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  65741. defines["SHADOWCLOSEESM" + lightIndex] = true;
  65742. }
  65743. if (light.needCube()) {
  65744. defines["SHADOWCUBE" + lightIndex] = true;
  65745. }
  65746. };
  65747. /**
  65748. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  65749. * defined in the generator but impacting the effect).
  65750. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  65751. * @param effect The effect we are binfing the information for
  65752. */
  65753. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  65754. var light = this._light;
  65755. var scene = this._scene;
  65756. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  65757. return;
  65758. }
  65759. var camera = scene.activeCamera;
  65760. if (!camera) {
  65761. return;
  65762. }
  65763. var shadowMap = this.getShadowMap();
  65764. if (!shadowMap) {
  65765. return;
  65766. }
  65767. if (!light.needCube()) {
  65768. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  65769. }
  65770. // Only PCF uses depth stencil texture.
  65771. if (this._filter === ShadowGenerator.FILTER_PCF) {
  65772. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65773. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65774. }
  65775. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  65776. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65777. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  65778. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  65779. }
  65780. else {
  65781. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  65782. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  65783. }
  65784. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  65785. };
  65786. /**
  65787. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  65788. * (eq to shadow prjection matrix * light transform matrix)
  65789. * @returns The transform matrix used to create the shadow map
  65790. */
  65791. ShadowGenerator.prototype.getTransformMatrix = function () {
  65792. var scene = this._scene;
  65793. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  65794. return this._transformMatrix;
  65795. }
  65796. this._currentRenderID = scene.getRenderId();
  65797. this._currentFaceIndexCache = this._currentFaceIndex;
  65798. var lightPosition = this._light.position;
  65799. if (this._light.computeTransformedInformation()) {
  65800. lightPosition = this._light.transformedPosition;
  65801. }
  65802. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  65803. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  65804. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  65805. }
  65806. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  65807. this._cachedPosition.copyFrom(lightPosition);
  65808. this._cachedDirection.copyFrom(this._lightDirection);
  65809. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  65810. var shadowMap = this.getShadowMap();
  65811. if (shadowMap) {
  65812. var renderList = shadowMap.renderList;
  65813. if (renderList) {
  65814. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  65815. }
  65816. }
  65817. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  65818. }
  65819. return this._transformMatrix;
  65820. };
  65821. /**
  65822. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  65823. * Cube and 2D textures for instance.
  65824. */
  65825. ShadowGenerator.prototype.recreateShadowMap = function () {
  65826. var shadowMap = this._shadowMap;
  65827. if (!shadowMap) {
  65828. return;
  65829. }
  65830. // Track render list.
  65831. var renderList = shadowMap.renderList;
  65832. // Clean up existing data.
  65833. this._disposeRTTandPostProcesses();
  65834. // Reinitializes.
  65835. this._initializeGenerator();
  65836. // Reaffect the filter to ensure a correct fallback if necessary.
  65837. this.filter = this.filter;
  65838. // Reaffect the filter.
  65839. this._applyFilterValues();
  65840. // Reaffect Render List.
  65841. this._shadowMap.renderList = renderList;
  65842. };
  65843. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  65844. if (this._shadowMap2) {
  65845. this._shadowMap2.dispose();
  65846. this._shadowMap2 = null;
  65847. }
  65848. if (this._boxBlurPostprocess) {
  65849. this._boxBlurPostprocess.dispose();
  65850. this._boxBlurPostprocess = null;
  65851. }
  65852. if (this._kernelBlurXPostprocess) {
  65853. this._kernelBlurXPostprocess.dispose();
  65854. this._kernelBlurXPostprocess = null;
  65855. }
  65856. if (this._kernelBlurYPostprocess) {
  65857. this._kernelBlurYPostprocess.dispose();
  65858. this._kernelBlurYPostprocess = null;
  65859. }
  65860. this._blurPostProcesses = [];
  65861. };
  65862. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  65863. if (this._shadowMap) {
  65864. this._shadowMap.dispose();
  65865. this._shadowMap = null;
  65866. }
  65867. this._disposeBlurPostProcesses();
  65868. };
  65869. /**
  65870. * Disposes the ShadowGenerator.
  65871. * Returns nothing.
  65872. */
  65873. ShadowGenerator.prototype.dispose = function () {
  65874. this._disposeRTTandPostProcesses();
  65875. if (this._light) {
  65876. this._light._shadowGenerator = null;
  65877. this._light._markMeshesAsLightDirty();
  65878. }
  65879. };
  65880. /**
  65881. * Serializes the shadow generator setup to a json object.
  65882. * @returns The serialized JSON object
  65883. */
  65884. ShadowGenerator.prototype.serialize = function () {
  65885. var serializationObject = {};
  65886. var shadowMap = this.getShadowMap();
  65887. if (!shadowMap) {
  65888. return serializationObject;
  65889. }
  65890. serializationObject.lightId = this._light.id;
  65891. serializationObject.mapSize = shadowMap.getRenderSize();
  65892. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  65893. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  65894. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65895. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  65896. serializationObject.usePoissonSampling = this.usePoissonSampling;
  65897. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  65898. serializationObject.depthScale = this.depthScale;
  65899. serializationObject.darkness = this.getDarkness();
  65900. serializationObject.blurBoxOffset = this.blurBoxOffset;
  65901. serializationObject.blurKernel = this.blurKernel;
  65902. serializationObject.blurScale = this.blurScale;
  65903. serializationObject.useKernelBlur = this.useKernelBlur;
  65904. serializationObject.transparencyShadow = this._transparencyShadow;
  65905. serializationObject.bias = this.bias;
  65906. serializationObject.normalBias = this.normalBias;
  65907. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  65908. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  65909. serializationObject.filteringQuality = this.filteringQuality;
  65910. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  65911. serializationObject.renderList = [];
  65912. if (shadowMap.renderList) {
  65913. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  65914. var mesh = shadowMap.renderList[meshIndex];
  65915. serializationObject.renderList.push(mesh.id);
  65916. }
  65917. }
  65918. return serializationObject;
  65919. };
  65920. /**
  65921. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  65922. * @param parsedShadowGenerator The JSON object to parse
  65923. * @param scene The scene to create the shadow map for
  65924. * @returns The parsed shadow generator
  65925. */
  65926. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  65927. //casting to point light, as light is missing the position attr and typescript complains.
  65928. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  65929. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  65930. var shadowMap = shadowGenerator.getShadowMap();
  65931. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  65932. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  65933. meshes.forEach(function (mesh) {
  65934. if (!shadowMap) {
  65935. return;
  65936. }
  65937. if (!shadowMap.renderList) {
  65938. shadowMap.renderList = [];
  65939. }
  65940. shadowMap.renderList.push(mesh);
  65941. });
  65942. }
  65943. if (parsedShadowGenerator.usePoissonSampling) {
  65944. shadowGenerator.usePoissonSampling = true;
  65945. }
  65946. else if (parsedShadowGenerator.useExponentialShadowMap) {
  65947. shadowGenerator.useExponentialShadowMap = true;
  65948. }
  65949. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  65950. shadowGenerator.useBlurExponentialShadowMap = true;
  65951. }
  65952. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  65953. shadowGenerator.useCloseExponentialShadowMap = true;
  65954. }
  65955. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  65956. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  65957. }
  65958. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  65959. shadowGenerator.usePercentageCloserFiltering = true;
  65960. }
  65961. else if (parsedShadowGenerator.useContactHardeningShadow) {
  65962. shadowGenerator.useContactHardeningShadow = true;
  65963. }
  65964. if (parsedShadowGenerator.filteringQuality) {
  65965. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  65966. }
  65967. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  65968. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  65969. }
  65970. // Backward compat
  65971. else if (parsedShadowGenerator.useVarianceShadowMap) {
  65972. shadowGenerator.useExponentialShadowMap = true;
  65973. }
  65974. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  65975. shadowGenerator.useBlurExponentialShadowMap = true;
  65976. }
  65977. if (parsedShadowGenerator.depthScale) {
  65978. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  65979. }
  65980. if (parsedShadowGenerator.blurScale) {
  65981. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  65982. }
  65983. if (parsedShadowGenerator.blurBoxOffset) {
  65984. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  65985. }
  65986. if (parsedShadowGenerator.useKernelBlur) {
  65987. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  65988. }
  65989. if (parsedShadowGenerator.blurKernel) {
  65990. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  65991. }
  65992. if (parsedShadowGenerator.bias !== undefined) {
  65993. shadowGenerator.bias = parsedShadowGenerator.bias;
  65994. }
  65995. if (parsedShadowGenerator.normalBias !== undefined) {
  65996. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  65997. }
  65998. if (parsedShadowGenerator.darkness) {
  65999. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66000. }
  66001. if (parsedShadowGenerator.transparencyShadow) {
  66002. shadowGenerator.setTransparencyShadow(true);
  66003. }
  66004. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66005. return shadowGenerator;
  66006. };
  66007. /**
  66008. * Shadow generator mode None: no filtering applied.
  66009. */
  66010. ShadowGenerator.FILTER_NONE = 0;
  66011. /**
  66012. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66013. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66014. */
  66015. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66016. /**
  66017. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66018. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66019. */
  66020. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66021. /**
  66022. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66023. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66024. */
  66025. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66026. /**
  66027. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66028. * edge artifacts on steep falloff.
  66029. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66030. */
  66031. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66032. /**
  66033. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66034. * edge artifacts on steep falloff.
  66035. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66036. */
  66037. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66038. /**
  66039. * Shadow generator mode PCF: Percentage Closer Filtering
  66040. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66041. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66042. */
  66043. ShadowGenerator.FILTER_PCF = 6;
  66044. /**
  66045. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66046. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66047. * Contact Hardening
  66048. */
  66049. ShadowGenerator.FILTER_PCSS = 7;
  66050. /**
  66051. * Reserved for PCF and PCSS
  66052. * Highest Quality.
  66053. *
  66054. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66055. *
  66056. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66057. */
  66058. ShadowGenerator.QUALITY_HIGH = 0;
  66059. /**
  66060. * Reserved for PCF and PCSS
  66061. * Good tradeoff for quality/perf cross devices
  66062. *
  66063. * Execute PCF on a 3*3 kernel.
  66064. *
  66065. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66066. */
  66067. ShadowGenerator.QUALITY_MEDIUM = 1;
  66068. /**
  66069. * Reserved for PCF and PCSS
  66070. * The lowest quality but the fastest.
  66071. *
  66072. * Execute PCF on a 1*1 kernel.
  66073. *
  66074. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66075. */
  66076. ShadowGenerator.QUALITY_LOW = 2;
  66077. return ShadowGenerator;
  66078. }());
  66079. BABYLON.ShadowGenerator = ShadowGenerator;
  66080. })(BABYLON || (BABYLON = {}));
  66081. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66082. var BABYLON;
  66083. (function (BABYLON) {
  66084. var DefaultLoadingScreen = /** @class */ (function () {
  66085. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66086. if (_loadingText === void 0) { _loadingText = ""; }
  66087. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66088. var _this = this;
  66089. this._renderingCanvas = _renderingCanvas;
  66090. this._loadingText = _loadingText;
  66091. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66092. // Resize
  66093. this._resizeLoadingUI = function () {
  66094. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66095. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66096. if (!_this._loadingDiv) {
  66097. return;
  66098. }
  66099. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66100. _this._loadingDiv.style.left = canvasRect.left + "px";
  66101. _this._loadingDiv.style.top = canvasRect.top + "px";
  66102. _this._loadingDiv.style.width = canvasRect.width + "px";
  66103. _this._loadingDiv.style.height = canvasRect.height + "px";
  66104. };
  66105. }
  66106. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66107. if (this._loadingDiv) {
  66108. // Do not add a loading screen if there is already one
  66109. return;
  66110. }
  66111. this._loadingDiv = document.createElement("div");
  66112. this._loadingDiv.id = "babylonjsLoadingDiv";
  66113. this._loadingDiv.style.opacity = "0";
  66114. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66115. this._loadingDiv.style.pointerEvents = "none";
  66116. // Loading text
  66117. this._loadingTextDiv = document.createElement("div");
  66118. this._loadingTextDiv.style.position = "absolute";
  66119. this._loadingTextDiv.style.left = "0";
  66120. this._loadingTextDiv.style.top = "50%";
  66121. this._loadingTextDiv.style.marginTop = "80px";
  66122. this._loadingTextDiv.style.width = "100%";
  66123. this._loadingTextDiv.style.height = "20px";
  66124. this._loadingTextDiv.style.fontFamily = "Arial";
  66125. this._loadingTextDiv.style.fontSize = "14px";
  66126. this._loadingTextDiv.style.color = "white";
  66127. this._loadingTextDiv.style.textAlign = "center";
  66128. this._loadingTextDiv.innerHTML = "Loading";
  66129. this._loadingDiv.appendChild(this._loadingTextDiv);
  66130. //set the predefined text
  66131. this._loadingTextDiv.innerHTML = this._loadingText;
  66132. // Generating keyframes
  66133. var style = document.createElement('style');
  66134. style.type = 'text/css';
  66135. 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 }";
  66136. style.innerHTML = keyFrames;
  66137. document.getElementsByTagName('head')[0].appendChild(style);
  66138. // Loading img
  66139. var imgBack = new Image();
  66140. 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";
  66141. imgBack.style.position = "absolute";
  66142. imgBack.style.left = "50%";
  66143. imgBack.style.top = "50%";
  66144. imgBack.style.marginLeft = "-60px";
  66145. imgBack.style.marginTop = "-60px";
  66146. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66147. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66148. imgBack.style.transformOrigin = "50% 50%";
  66149. imgBack.style.webkitTransformOrigin = "50% 50%";
  66150. this._loadingDiv.appendChild(imgBack);
  66151. this._resizeLoadingUI();
  66152. window.addEventListener("resize", this._resizeLoadingUI);
  66153. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66154. document.body.appendChild(this._loadingDiv);
  66155. this._loadingDiv.style.opacity = "1";
  66156. };
  66157. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66158. var _this = this;
  66159. if (!this._loadingDiv) {
  66160. return;
  66161. }
  66162. var onTransitionEnd = function () {
  66163. if (!_this._loadingDiv) {
  66164. return;
  66165. }
  66166. document.body.removeChild(_this._loadingDiv);
  66167. window.removeEventListener("resize", _this._resizeLoadingUI);
  66168. _this._loadingDiv = null;
  66169. };
  66170. this._loadingDiv.style.opacity = "0";
  66171. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66172. };
  66173. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66174. set: function (text) {
  66175. this._loadingText = text;
  66176. if (this._loadingTextDiv) {
  66177. this._loadingTextDiv.innerHTML = this._loadingText;
  66178. }
  66179. },
  66180. enumerable: true,
  66181. configurable: true
  66182. });
  66183. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66184. get: function () {
  66185. return this._loadingDivBackgroundColor;
  66186. },
  66187. set: function (color) {
  66188. this._loadingDivBackgroundColor = color;
  66189. if (!this._loadingDiv) {
  66190. return;
  66191. }
  66192. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66193. },
  66194. enumerable: true,
  66195. configurable: true
  66196. });
  66197. return DefaultLoadingScreen;
  66198. }());
  66199. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66200. })(BABYLON || (BABYLON = {}));
  66201. //# sourceMappingURL=babylon.loadingScreen.js.map
  66202. var BABYLON;
  66203. (function (BABYLON) {
  66204. var SceneLoaderProgressEvent = /** @class */ (function () {
  66205. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66206. this.lengthComputable = lengthComputable;
  66207. this.loaded = loaded;
  66208. this.total = total;
  66209. }
  66210. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66211. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66212. };
  66213. return SceneLoaderProgressEvent;
  66214. }());
  66215. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66216. var SceneLoader = /** @class */ (function () {
  66217. function SceneLoader() {
  66218. }
  66219. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66220. get: function () {
  66221. return 0;
  66222. },
  66223. enumerable: true,
  66224. configurable: true
  66225. });
  66226. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66227. get: function () {
  66228. return 1;
  66229. },
  66230. enumerable: true,
  66231. configurable: true
  66232. });
  66233. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66234. get: function () {
  66235. return 2;
  66236. },
  66237. enumerable: true,
  66238. configurable: true
  66239. });
  66240. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66241. get: function () {
  66242. return 3;
  66243. },
  66244. enumerable: true,
  66245. configurable: true
  66246. });
  66247. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66248. get: function () {
  66249. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66250. },
  66251. set: function (value) {
  66252. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66253. },
  66254. enumerable: true,
  66255. configurable: true
  66256. });
  66257. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66258. get: function () {
  66259. return SceneLoader._ShowLoadingScreen;
  66260. },
  66261. set: function (value) {
  66262. SceneLoader._ShowLoadingScreen = value;
  66263. },
  66264. enumerable: true,
  66265. configurable: true
  66266. });
  66267. Object.defineProperty(SceneLoader, "loggingLevel", {
  66268. get: function () {
  66269. return SceneLoader._loggingLevel;
  66270. },
  66271. set: function (value) {
  66272. SceneLoader._loggingLevel = value;
  66273. },
  66274. enumerable: true,
  66275. configurable: true
  66276. });
  66277. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66278. get: function () {
  66279. return SceneLoader._CleanBoneMatrixWeights;
  66280. },
  66281. set: function (value) {
  66282. SceneLoader._CleanBoneMatrixWeights = value;
  66283. },
  66284. enumerable: true,
  66285. configurable: true
  66286. });
  66287. SceneLoader._getDefaultPlugin = function () {
  66288. return SceneLoader._registeredPlugins[".babylon"];
  66289. };
  66290. SceneLoader._getPluginForExtension = function (extension) {
  66291. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66292. if (registeredPlugin) {
  66293. return registeredPlugin;
  66294. }
  66295. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66296. return SceneLoader._getDefaultPlugin();
  66297. };
  66298. SceneLoader._getPluginForDirectLoad = function (data) {
  66299. for (var extension in SceneLoader._registeredPlugins) {
  66300. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66301. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66302. return SceneLoader._registeredPlugins[extension];
  66303. }
  66304. }
  66305. return SceneLoader._getDefaultPlugin();
  66306. };
  66307. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66308. if (sceneFilename.name) {
  66309. sceneFilename = sceneFilename.name;
  66310. }
  66311. var queryStringPosition = sceneFilename.indexOf("?");
  66312. if (queryStringPosition !== -1) {
  66313. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66314. }
  66315. var dotPosition = sceneFilename.lastIndexOf(".");
  66316. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66317. return SceneLoader._getPluginForExtension(extension);
  66318. };
  66319. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66320. SceneLoader._getDirectLoad = function (sceneFilename) {
  66321. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66322. return sceneFilename.substr(5);
  66323. }
  66324. return null;
  66325. };
  66326. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66327. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66328. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66329. var plugin;
  66330. if (registeredPlugin.plugin.createPlugin) {
  66331. plugin = registeredPlugin.plugin.createPlugin();
  66332. }
  66333. else {
  66334. plugin = registeredPlugin.plugin;
  66335. }
  66336. var useArrayBuffer = registeredPlugin.isBinary;
  66337. var database;
  66338. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66339. var dataCallback = function (data, responseURL) {
  66340. if (scene.isDisposed) {
  66341. onError("Scene has been disposed");
  66342. return;
  66343. }
  66344. scene.database = database;
  66345. onSuccess(plugin, data, responseURL);
  66346. };
  66347. var request = null;
  66348. var pluginDisposed = false;
  66349. var onDisposeObservable = plugin.onDisposeObservable;
  66350. if (onDisposeObservable) {
  66351. onDisposeObservable.add(function () {
  66352. pluginDisposed = true;
  66353. if (request) {
  66354. request.abort();
  66355. request = null;
  66356. }
  66357. onDispose();
  66358. });
  66359. }
  66360. var manifestChecked = function () {
  66361. if (pluginDisposed) {
  66362. return;
  66363. }
  66364. var url = rootUrl + sceneFilename;
  66365. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66366. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66367. } : undefined, database, useArrayBuffer, function (request, exception) {
  66368. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66369. });
  66370. };
  66371. if (directLoad) {
  66372. dataCallback(directLoad);
  66373. return plugin;
  66374. }
  66375. if (rootUrl.indexOf("file:") === -1) {
  66376. var canUseOfflineSupport = scene.getEngine().enableOfflineSupport;
  66377. if (canUseOfflineSupport) {
  66378. // Also check for exceptions
  66379. var exceptionFound = false;
  66380. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66381. var regex = _a[_i];
  66382. if (regex.test(rootUrl + sceneFilename)) {
  66383. exceptionFound = true;
  66384. break;
  66385. }
  66386. }
  66387. canUseOfflineSupport = !exceptionFound;
  66388. }
  66389. if (canUseOfflineSupport) {
  66390. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66391. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  66392. }
  66393. else {
  66394. manifestChecked();
  66395. }
  66396. }
  66397. // Loading file from disk via input file or drag'n'drop
  66398. else {
  66399. var fileOrString = sceneFilename;
  66400. if (fileOrString.name) { // File
  66401. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66402. }
  66403. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66404. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66405. }
  66406. else {
  66407. onError("Unable to find file named " + sceneFilename);
  66408. }
  66409. }
  66410. return plugin;
  66411. };
  66412. // Public functions
  66413. SceneLoader.GetPluginForExtension = function (extension) {
  66414. return SceneLoader._getPluginForExtension(extension).plugin;
  66415. };
  66416. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66417. return !!SceneLoader._registeredPlugins[extension];
  66418. };
  66419. SceneLoader.RegisterPlugin = function (plugin) {
  66420. if (typeof plugin.extensions === "string") {
  66421. var extension = plugin.extensions;
  66422. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66423. plugin: plugin,
  66424. isBinary: false
  66425. };
  66426. }
  66427. else {
  66428. var extensions = plugin.extensions;
  66429. Object.keys(extensions).forEach(function (extension) {
  66430. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66431. plugin: plugin,
  66432. isBinary: extensions[extension].isBinary
  66433. };
  66434. });
  66435. }
  66436. };
  66437. /**
  66438. * Import meshes into a scene
  66439. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66440. * @param rootUrl a string that defines the root url for scene and resources
  66441. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66442. * @param scene the instance of BABYLON.Scene to append to
  66443. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66444. * @param onProgress a callback with a progress event for each file being loaded
  66445. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66446. * @param pluginExtension the extension used to determine the plugin
  66447. * @returns The loaded plugin
  66448. */
  66449. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66450. if (onSuccess === void 0) { onSuccess = null; }
  66451. if (onProgress === void 0) { onProgress = null; }
  66452. if (onError === void 0) { onError = null; }
  66453. if (pluginExtension === void 0) { pluginExtension = null; }
  66454. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66455. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66456. return null;
  66457. }
  66458. var loadingToken = {};
  66459. scene._addPendingData(loadingToken);
  66460. var disposeHandler = function () {
  66461. scene._removePendingData(loadingToken);
  66462. };
  66463. var errorHandler = function (message, exception) {
  66464. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66465. if (onError) {
  66466. onError(scene, errorMessage, exception);
  66467. }
  66468. else {
  66469. BABYLON.Tools.Error(errorMessage);
  66470. // should the exception be thrown?
  66471. }
  66472. disposeHandler();
  66473. };
  66474. var progressHandler = onProgress ? function (event) {
  66475. try {
  66476. onProgress(event);
  66477. }
  66478. catch (e) {
  66479. errorHandler("Error in onProgress callback", e);
  66480. }
  66481. } : undefined;
  66482. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66483. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66484. if (onSuccess) {
  66485. try {
  66486. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66487. }
  66488. catch (e) {
  66489. errorHandler("Error in onSuccess callback", e);
  66490. }
  66491. }
  66492. scene._removePendingData(loadingToken);
  66493. };
  66494. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66495. if (plugin.rewriteRootURL) {
  66496. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66497. }
  66498. if (sceneFilename === "") {
  66499. if (sceneFilename === "") {
  66500. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66501. }
  66502. }
  66503. if (plugin.importMesh) {
  66504. var syncedPlugin = plugin;
  66505. var meshes = new Array();
  66506. var particleSystems = new Array();
  66507. var skeletons = new Array();
  66508. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66509. return;
  66510. }
  66511. scene.loadingPluginName = plugin.name;
  66512. successHandler(meshes, particleSystems, skeletons, []);
  66513. }
  66514. else {
  66515. var asyncedPlugin = plugin;
  66516. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66517. scene.loadingPluginName = plugin.name;
  66518. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66519. }).catch(function (error) {
  66520. errorHandler(error.message, error);
  66521. });
  66522. }
  66523. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66524. };
  66525. /**
  66526. * Import meshes into a scene
  66527. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66528. * @param rootUrl a string that defines the root url for scene and resources
  66529. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66530. * @param scene the instance of BABYLON.Scene to append to
  66531. * @param onProgress a callback with a progress event for each file being loaded
  66532. * @param pluginExtension the extension used to determine the plugin
  66533. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66534. */
  66535. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66536. if (onProgress === void 0) { onProgress = null; }
  66537. if (pluginExtension === void 0) { pluginExtension = null; }
  66538. return new Promise(function (resolve, reject) {
  66539. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66540. resolve({
  66541. meshes: meshes,
  66542. particleSystems: particleSystems,
  66543. skeletons: skeletons,
  66544. animationGroups: animationGroups
  66545. });
  66546. }, onProgress, function (scene, message, exception) {
  66547. reject(exception || new Error(message));
  66548. });
  66549. });
  66550. };
  66551. /**
  66552. * Load a scene
  66553. * @param rootUrl a string that defines the root url for scene and resources
  66554. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66555. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66556. * @param onSuccess a callback with the scene when import succeeds
  66557. * @param onProgress a callback with a progress event for each file being loaded
  66558. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66559. * @param pluginExtension the extension used to determine the plugin
  66560. * @returns The loaded plugin
  66561. */
  66562. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66563. if (onSuccess === void 0) { onSuccess = null; }
  66564. if (onProgress === void 0) { onProgress = null; }
  66565. if (onError === void 0) { onError = null; }
  66566. if (pluginExtension === void 0) { pluginExtension = null; }
  66567. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  66568. };
  66569. /**
  66570. * Load a scene
  66571. * @param rootUrl a string that defines the root url for scene and resources
  66572. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66573. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66574. * @param onProgress a callback with a progress event for each file being loaded
  66575. * @param pluginExtension the extension used to determine the plugin
  66576. * @returns The loaded scene
  66577. */
  66578. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  66579. if (onProgress === void 0) { onProgress = null; }
  66580. if (pluginExtension === void 0) { pluginExtension = null; }
  66581. return new Promise(function (resolve, reject) {
  66582. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  66583. resolve(scene);
  66584. }, onProgress, function (scene, message, exception) {
  66585. reject(exception || new Error(message));
  66586. }, pluginExtension);
  66587. });
  66588. };
  66589. /**
  66590. * Append a scene
  66591. * @param rootUrl a string that defines the root url for scene and resources
  66592. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66593. * @param scene is the instance of BABYLON.Scene to append to
  66594. * @param onSuccess a callback with the scene when import succeeds
  66595. * @param onProgress a callback with a progress event for each file being loaded
  66596. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66597. * @param pluginExtension the extension used to determine the plugin
  66598. * @returns The loaded plugin
  66599. */
  66600. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66601. if (onSuccess === void 0) { onSuccess = null; }
  66602. if (onProgress === void 0) { onProgress = null; }
  66603. if (onError === void 0) { onError = null; }
  66604. if (pluginExtension === void 0) { pluginExtension = null; }
  66605. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66606. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66607. return null;
  66608. }
  66609. if (SceneLoader.ShowLoadingScreen) {
  66610. scene.getEngine().displayLoadingUI();
  66611. }
  66612. var loadingToken = {};
  66613. scene._addPendingData(loadingToken);
  66614. var disposeHandler = function () {
  66615. scene._removePendingData(loadingToken);
  66616. scene.getEngine().hideLoadingUI();
  66617. };
  66618. var errorHandler = function (message, exception) {
  66619. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66620. if (onError) {
  66621. onError(scene, errorMessage, exception);
  66622. }
  66623. else {
  66624. BABYLON.Tools.Error(errorMessage);
  66625. // should the exception be thrown?
  66626. }
  66627. disposeHandler();
  66628. };
  66629. var progressHandler = onProgress ? function (event) {
  66630. try {
  66631. onProgress(event);
  66632. }
  66633. catch (e) {
  66634. errorHandler("Error in onProgress callback", e);
  66635. }
  66636. } : undefined;
  66637. var successHandler = function () {
  66638. if (onSuccess) {
  66639. try {
  66640. onSuccess(scene);
  66641. }
  66642. catch (e) {
  66643. errorHandler("Error in onSuccess callback", e);
  66644. }
  66645. }
  66646. scene._removePendingData(loadingToken);
  66647. };
  66648. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66649. if (sceneFilename === "") {
  66650. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66651. }
  66652. if (plugin.load) {
  66653. var syncedPlugin = plugin;
  66654. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  66655. return;
  66656. }
  66657. scene.loadingPluginName = plugin.name;
  66658. successHandler();
  66659. }
  66660. else {
  66661. var asyncedPlugin = plugin;
  66662. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  66663. scene.loadingPluginName = plugin.name;
  66664. successHandler();
  66665. }).catch(function (error) {
  66666. errorHandler(error.message, error);
  66667. });
  66668. }
  66669. if (SceneLoader.ShowLoadingScreen) {
  66670. scene.executeWhenReady(function () {
  66671. scene.getEngine().hideLoadingUI();
  66672. });
  66673. }
  66674. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66675. };
  66676. /**
  66677. * Append a scene
  66678. * @param rootUrl a string that defines the root url for scene and resources
  66679. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66680. * @param scene is the instance of BABYLON.Scene to append to
  66681. * @param onProgress a callback with a progress event for each file being loaded
  66682. * @param pluginExtension the extension used to determine the plugin
  66683. * @returns The given scene
  66684. */
  66685. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66686. if (onProgress === void 0) { onProgress = null; }
  66687. if (pluginExtension === void 0) { pluginExtension = null; }
  66688. return new Promise(function (resolve, reject) {
  66689. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  66690. resolve(scene);
  66691. }, onProgress, function (scene, message, exception) {
  66692. reject(exception || new Error(message));
  66693. }, pluginExtension);
  66694. });
  66695. };
  66696. /**
  66697. * Load a scene into an asset container
  66698. * @param rootUrl a string that defines the root url for scene and resources
  66699. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66700. * @param scene is the instance of BABYLON.Scene to append to
  66701. * @param onSuccess a callback with the scene when import succeeds
  66702. * @param onProgress a callback with a progress event for each file being loaded
  66703. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66704. * @param pluginExtension the extension used to determine the plugin
  66705. * @returns The loaded plugin
  66706. */
  66707. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66708. if (onSuccess === void 0) { onSuccess = null; }
  66709. if (onProgress === void 0) { onProgress = null; }
  66710. if (onError === void 0) { onError = null; }
  66711. if (pluginExtension === void 0) { pluginExtension = null; }
  66712. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66713. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66714. return null;
  66715. }
  66716. var loadingToken = {};
  66717. scene._addPendingData(loadingToken);
  66718. var disposeHandler = function () {
  66719. scene._removePendingData(loadingToken);
  66720. };
  66721. var errorHandler = function (message, exception) {
  66722. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  66723. if (onError) {
  66724. onError(scene, errorMessage, exception);
  66725. }
  66726. else {
  66727. BABYLON.Tools.Error(errorMessage);
  66728. // should the exception be thrown?
  66729. }
  66730. disposeHandler();
  66731. };
  66732. var progressHandler = onProgress ? function (event) {
  66733. try {
  66734. onProgress(event);
  66735. }
  66736. catch (e) {
  66737. errorHandler("Error in onProgress callback", e);
  66738. }
  66739. } : undefined;
  66740. var successHandler = function (assets) {
  66741. if (onSuccess) {
  66742. try {
  66743. onSuccess(assets);
  66744. }
  66745. catch (e) {
  66746. errorHandler("Error in onSuccess callback", e);
  66747. }
  66748. }
  66749. scene._removePendingData(loadingToken);
  66750. };
  66751. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66752. if (plugin.loadAssetContainer) {
  66753. var syncedPlugin = plugin;
  66754. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  66755. if (!assetContainer) {
  66756. return;
  66757. }
  66758. scene.loadingPluginName = plugin.name;
  66759. successHandler(assetContainer);
  66760. }
  66761. else if (plugin.loadAssetContainerAsync) {
  66762. var asyncedPlugin = plugin;
  66763. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  66764. scene.loadingPluginName = plugin.name;
  66765. successHandler(assetContainer);
  66766. }).catch(function (error) {
  66767. errorHandler(error.message, error);
  66768. });
  66769. }
  66770. else {
  66771. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  66772. }
  66773. if (SceneLoader.ShowLoadingScreen) {
  66774. scene.executeWhenReady(function () {
  66775. scene.getEngine().hideLoadingUI();
  66776. });
  66777. }
  66778. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66779. };
  66780. /**
  66781. * Load a scene into an asset container
  66782. * @param rootUrl a string that defines the root url for scene and resources
  66783. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66784. * @param scene is the instance of BABYLON.Scene to append to
  66785. * @param onProgress a callback with a progress event for each file being loaded
  66786. * @param pluginExtension the extension used to determine the plugin
  66787. * @returns The loaded asset container
  66788. */
  66789. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66790. if (onProgress === void 0) { onProgress = null; }
  66791. if (pluginExtension === void 0) { pluginExtension = null; }
  66792. return new Promise(function (resolve, reject) {
  66793. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  66794. resolve(assetContainer);
  66795. }, onProgress, function (scene, message, exception) {
  66796. reject(exception || new Error(message));
  66797. }, pluginExtension);
  66798. });
  66799. };
  66800. // Flags
  66801. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  66802. SceneLoader._ShowLoadingScreen = true;
  66803. SceneLoader._CleanBoneMatrixWeights = false;
  66804. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  66805. // Members
  66806. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  66807. SceneLoader._registeredPlugins = {};
  66808. return SceneLoader;
  66809. }());
  66810. BABYLON.SceneLoader = SceneLoader;
  66811. ;
  66812. })(BABYLON || (BABYLON = {}));
  66813. //# sourceMappingURL=babylon.sceneLoader.js.map
  66814. var BABYLON;
  66815. (function (BABYLON) {
  66816. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  66817. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66818. var parsedMaterial = parsedData.materials[index];
  66819. if (parsedMaterial.id === id) {
  66820. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66821. }
  66822. }
  66823. return null;
  66824. };
  66825. var isDescendantOf = function (mesh, names, hierarchyIds) {
  66826. for (var i in names) {
  66827. if (mesh.name === names[i]) {
  66828. hierarchyIds.push(mesh.id);
  66829. return true;
  66830. }
  66831. }
  66832. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  66833. hierarchyIds.push(mesh.id);
  66834. return true;
  66835. }
  66836. return false;
  66837. };
  66838. var logOperation = function (operation, producer) {
  66839. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  66840. };
  66841. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  66842. if (addToScene === void 0) { addToScene = false; }
  66843. var container = new BABYLON.AssetContainer(scene);
  66844. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  66845. // when SceneLoader.debugLogging = true (default), or exception encountered.
  66846. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  66847. // and avoid problems with multiple concurrent .babylon loads.
  66848. var log = "importScene has failed JSON parse";
  66849. try {
  66850. var parsedData = JSON.parse(data);
  66851. log = "";
  66852. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  66853. var index;
  66854. var cache;
  66855. // Lights
  66856. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  66857. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  66858. var parsedLight = parsedData.lights[index];
  66859. var light = BABYLON.Light.Parse(parsedLight, scene);
  66860. if (light) {
  66861. container.lights.push(light);
  66862. log += (index === 0 ? "\n\tLights:" : "");
  66863. log += "\n\t\t" + light.toString(fullDetails);
  66864. }
  66865. }
  66866. }
  66867. // Animations
  66868. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  66869. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  66870. var parsedAnimation = parsedData.animations[index];
  66871. var animation = BABYLON.Animation.Parse(parsedAnimation);
  66872. scene.animations.push(animation);
  66873. container.animations.push(animation);
  66874. log += (index === 0 ? "\n\tAnimations:" : "");
  66875. log += "\n\t\t" + animation.toString(fullDetails);
  66876. }
  66877. }
  66878. // Materials
  66879. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  66880. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  66881. var parsedMaterial = parsedData.materials[index];
  66882. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  66883. container.materials.push(mat);
  66884. log += (index === 0 ? "\n\tMaterials:" : "");
  66885. log += "\n\t\t" + mat.toString(fullDetails);
  66886. }
  66887. }
  66888. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  66889. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  66890. var parsedMultiMaterial = parsedData.multiMaterials[index];
  66891. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  66892. container.multiMaterials.push(mmat);
  66893. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  66894. log += "\n\t\t" + mmat.toString(fullDetails);
  66895. }
  66896. }
  66897. // Morph targets
  66898. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  66899. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  66900. var managerData = _a[_i];
  66901. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  66902. }
  66903. }
  66904. // Skeletons
  66905. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  66906. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  66907. var parsedSkeleton = parsedData.skeletons[index];
  66908. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  66909. container.skeletons.push(skeleton);
  66910. log += (index === 0 ? "\n\tSkeletons:" : "");
  66911. log += "\n\t\t" + skeleton.toString(fullDetails);
  66912. }
  66913. }
  66914. // Geometries
  66915. var geometries = parsedData.geometries;
  66916. if (geometries !== undefined && geometries !== null) {
  66917. var addedGeometry = new Array();
  66918. // Boxes
  66919. var boxes = geometries.boxes;
  66920. if (boxes !== undefined && boxes !== null) {
  66921. for (index = 0, cache = boxes.length; index < cache; index++) {
  66922. var parsedBox = boxes[index];
  66923. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  66924. }
  66925. }
  66926. // Spheres
  66927. var spheres = geometries.spheres;
  66928. if (spheres !== undefined && spheres !== null) {
  66929. for (index = 0, cache = spheres.length; index < cache; index++) {
  66930. var parsedSphere = spheres[index];
  66931. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  66932. }
  66933. }
  66934. // Cylinders
  66935. var cylinders = geometries.cylinders;
  66936. if (cylinders !== undefined && cylinders !== null) {
  66937. for (index = 0, cache = cylinders.length; index < cache; index++) {
  66938. var parsedCylinder = cylinders[index];
  66939. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  66940. }
  66941. }
  66942. // Toruses
  66943. var toruses = geometries.toruses;
  66944. if (toruses !== undefined && toruses !== null) {
  66945. for (index = 0, cache = toruses.length; index < cache; index++) {
  66946. var parsedTorus = toruses[index];
  66947. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  66948. }
  66949. }
  66950. // Grounds
  66951. var grounds = geometries.grounds;
  66952. if (grounds !== undefined && grounds !== null) {
  66953. for (index = 0, cache = grounds.length; index < cache; index++) {
  66954. var parsedGround = grounds[index];
  66955. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  66956. }
  66957. }
  66958. // Planes
  66959. var planes = geometries.planes;
  66960. if (planes !== undefined && planes !== null) {
  66961. for (index = 0, cache = planes.length; index < cache; index++) {
  66962. var parsedPlane = planes[index];
  66963. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  66964. }
  66965. }
  66966. // TorusKnots
  66967. var torusKnots = geometries.torusKnots;
  66968. if (torusKnots !== undefined && torusKnots !== null) {
  66969. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  66970. var parsedTorusKnot = torusKnots[index];
  66971. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  66972. }
  66973. }
  66974. // VertexData
  66975. var vertexData = geometries.vertexData;
  66976. if (vertexData !== undefined && vertexData !== null) {
  66977. for (index = 0, cache = vertexData.length; index < cache; index++) {
  66978. var parsedVertexData = vertexData[index];
  66979. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  66980. }
  66981. }
  66982. addedGeometry.forEach(function (g) {
  66983. if (g) {
  66984. container.geometries.push(g);
  66985. }
  66986. });
  66987. }
  66988. // Transform nodes
  66989. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  66990. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  66991. var parsedTransformNode = parsedData.transformNodes[index];
  66992. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  66993. container.transformNodes.push(node);
  66994. }
  66995. }
  66996. // Meshes
  66997. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  66998. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  66999. var parsedMesh = parsedData.meshes[index];
  67000. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67001. container.meshes.push(mesh);
  67002. log += (index === 0 ? "\n\tMeshes:" : "");
  67003. log += "\n\t\t" + mesh.toString(fullDetails);
  67004. }
  67005. }
  67006. // Cameras
  67007. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67008. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67009. var parsedCamera = parsedData.cameras[index];
  67010. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67011. container.cameras.push(camera);
  67012. log += (index === 0 ? "\n\tCameras:" : "");
  67013. log += "\n\t\t" + camera.toString(fullDetails);
  67014. }
  67015. }
  67016. // Browsing all the graph to connect the dots
  67017. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67018. var camera = scene.cameras[index];
  67019. if (camera._waitingParentId) {
  67020. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67021. camera._waitingParentId = null;
  67022. }
  67023. }
  67024. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67025. var light_1 = scene.lights[index];
  67026. if (light_1 && light_1._waitingParentId) {
  67027. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67028. light_1._waitingParentId = null;
  67029. }
  67030. }
  67031. // Sounds
  67032. // TODO: add sound
  67033. var loadedSounds = [];
  67034. var loadedSound;
  67035. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67036. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67037. var parsedSound = parsedData.sounds[index];
  67038. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67039. if (!parsedSound.url)
  67040. parsedSound.url = parsedSound.name;
  67041. if (!loadedSounds[parsedSound.url]) {
  67042. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67043. loadedSounds[parsedSound.url] = loadedSound;
  67044. container.sounds.push(loadedSound);
  67045. }
  67046. else {
  67047. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67048. }
  67049. }
  67050. else {
  67051. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67052. }
  67053. }
  67054. }
  67055. loadedSounds = [];
  67056. // Connect parents & children and parse actions
  67057. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67058. var transformNode = scene.transformNodes[index];
  67059. if (transformNode._waitingParentId) {
  67060. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67061. transformNode._waitingParentId = null;
  67062. }
  67063. }
  67064. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67065. var mesh = scene.meshes[index];
  67066. if (mesh._waitingParentId) {
  67067. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67068. mesh._waitingParentId = null;
  67069. }
  67070. if (mesh._waitingActions) {
  67071. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67072. mesh._waitingActions = null;
  67073. }
  67074. }
  67075. // freeze world matrix application
  67076. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67077. var currentMesh = scene.meshes[index];
  67078. if (currentMesh._waitingFreezeWorldMatrix) {
  67079. currentMesh.freezeWorldMatrix();
  67080. currentMesh._waitingFreezeWorldMatrix = null;
  67081. }
  67082. else {
  67083. currentMesh.computeWorldMatrix(true);
  67084. }
  67085. }
  67086. // Particles Systems
  67087. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67088. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67089. var parsedParticleSystem = parsedData.particleSystems[index];
  67090. if (parsedParticleSystem.activeParticleCount) {
  67091. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67092. container.particleSystems.push(ps);
  67093. }
  67094. else {
  67095. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67096. container.particleSystems.push(ps);
  67097. }
  67098. }
  67099. }
  67100. // Lens flares
  67101. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67102. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67103. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67104. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67105. container.lensFlareSystems.push(lf);
  67106. }
  67107. }
  67108. // Shadows
  67109. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67110. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67111. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67112. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67113. container.shadowGenerators.push(sg);
  67114. }
  67115. }
  67116. // Lights exclusions / inclusions
  67117. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67118. var light_2 = scene.lights[index];
  67119. // Excluded check
  67120. if (light_2._excludedMeshesIds.length > 0) {
  67121. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67122. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67123. if (excludedMesh) {
  67124. light_2.excludedMeshes.push(excludedMesh);
  67125. }
  67126. }
  67127. light_2._excludedMeshesIds = [];
  67128. }
  67129. // Included check
  67130. if (light_2._includedOnlyMeshesIds.length > 0) {
  67131. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67132. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67133. if (includedOnlyMesh) {
  67134. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67135. }
  67136. }
  67137. light_2._includedOnlyMeshesIds = [];
  67138. }
  67139. }
  67140. // Effect layers
  67141. if (parsedData.effectLayers) {
  67142. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67143. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67144. container.effectLayers.push(effectLayer);
  67145. }
  67146. }
  67147. // Actions (scene)
  67148. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67149. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67150. }
  67151. if (!addToScene) {
  67152. container.removeAllFromScene();
  67153. }
  67154. }
  67155. catch (err) {
  67156. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67157. if (onError) {
  67158. onError(msg, err);
  67159. }
  67160. else {
  67161. BABYLON.Tools.Log(msg);
  67162. throw err;
  67163. }
  67164. }
  67165. finally {
  67166. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67167. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67168. }
  67169. }
  67170. return container;
  67171. };
  67172. BABYLON.SceneLoader.RegisterPlugin({
  67173. name: "babylon.js",
  67174. extensions: ".babylon",
  67175. canDirectLoad: function (data) {
  67176. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67177. return true;
  67178. }
  67179. return false;
  67180. },
  67181. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67182. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67183. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67184. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67185. // and avoid problems with multiple concurrent .babylon loads.
  67186. var log = "importMesh has failed JSON parse";
  67187. try {
  67188. var parsedData = JSON.parse(data);
  67189. log = "";
  67190. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67191. if (!meshesNames) {
  67192. meshesNames = null;
  67193. }
  67194. else if (!Array.isArray(meshesNames)) {
  67195. meshesNames = [meshesNames];
  67196. }
  67197. var hierarchyIds = new Array();
  67198. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67199. var loadedSkeletonsIds = [];
  67200. var loadedMaterialsIds = [];
  67201. var index;
  67202. var cache;
  67203. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67204. var parsedMesh = parsedData.meshes[index];
  67205. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67206. if (meshesNames !== null) {
  67207. // Remove found mesh name from list.
  67208. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67209. }
  67210. //Geometry?
  67211. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67212. //does the file contain geometries?
  67213. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67214. //find the correct geometry and add it to the scene
  67215. var found = false;
  67216. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67217. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67218. return;
  67219. }
  67220. else {
  67221. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67222. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67223. switch (geometryType) {
  67224. case "boxes":
  67225. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67226. break;
  67227. case "spheres":
  67228. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67229. break;
  67230. case "cylinders":
  67231. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67232. break;
  67233. case "toruses":
  67234. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67235. break;
  67236. case "grounds":
  67237. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67238. break;
  67239. case "planes":
  67240. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67241. break;
  67242. case "torusKnots":
  67243. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67244. break;
  67245. case "vertexData":
  67246. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67247. break;
  67248. }
  67249. found = true;
  67250. }
  67251. });
  67252. }
  67253. });
  67254. if (found === false) {
  67255. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67256. }
  67257. }
  67258. }
  67259. // Material ?
  67260. if (parsedMesh.materialId) {
  67261. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67262. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67263. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67264. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67265. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67266. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67267. var subMatId = parsedMultiMaterial.materials[matIndex];
  67268. loadedMaterialsIds.push(subMatId);
  67269. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67270. if (mat) {
  67271. log += "\n\tMaterial " + mat.toString(fullDetails);
  67272. }
  67273. }
  67274. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67275. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67276. if (mmat) {
  67277. materialFound = true;
  67278. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67279. }
  67280. break;
  67281. }
  67282. }
  67283. }
  67284. if (materialFound === false) {
  67285. loadedMaterialsIds.push(parsedMesh.materialId);
  67286. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67287. if (!mat) {
  67288. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67289. }
  67290. else {
  67291. log += "\n\tMaterial " + mat.toString(fullDetails);
  67292. }
  67293. }
  67294. }
  67295. // Skeleton ?
  67296. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67297. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67298. if (skeletonAlreadyLoaded === false) {
  67299. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67300. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67301. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67302. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67303. skeletons.push(skeleton);
  67304. loadedSkeletonsIds.push(parsedSkeleton.id);
  67305. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67306. }
  67307. }
  67308. }
  67309. }
  67310. // Morph targets ?
  67311. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67312. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67313. var managerData = _a[_i];
  67314. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67315. }
  67316. }
  67317. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67318. meshes.push(mesh);
  67319. log += "\n\tMesh " + mesh.toString(fullDetails);
  67320. }
  67321. }
  67322. // Connecting parents
  67323. var currentMesh;
  67324. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67325. currentMesh = scene.meshes[index];
  67326. if (currentMesh._waitingParentId) {
  67327. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67328. currentMesh._waitingParentId = null;
  67329. }
  67330. }
  67331. // freeze and compute world matrix application
  67332. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67333. currentMesh = scene.meshes[index];
  67334. if (currentMesh._waitingFreezeWorldMatrix) {
  67335. currentMesh.freezeWorldMatrix();
  67336. currentMesh._waitingFreezeWorldMatrix = null;
  67337. }
  67338. else {
  67339. currentMesh.computeWorldMatrix(true);
  67340. }
  67341. }
  67342. }
  67343. // Particles
  67344. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67345. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67346. var parsedParticleSystem = parsedData.particleSystems[index];
  67347. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67348. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67349. }
  67350. }
  67351. }
  67352. return true;
  67353. }
  67354. catch (err) {
  67355. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67356. if (onError) {
  67357. onError(msg, err);
  67358. }
  67359. else {
  67360. BABYLON.Tools.Log(msg);
  67361. throw err;
  67362. }
  67363. }
  67364. finally {
  67365. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67366. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67367. }
  67368. }
  67369. return false;
  67370. },
  67371. load: function (scene, data, rootUrl, onError) {
  67372. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67373. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67374. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67375. // and avoid problems with multiple concurrent .babylon loads.
  67376. var log = "importScene has failed JSON parse";
  67377. try {
  67378. var parsedData = JSON.parse(data);
  67379. log = "";
  67380. // Scene
  67381. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67382. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67383. }
  67384. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67385. scene.autoClear = parsedData.autoClear;
  67386. }
  67387. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67388. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67389. }
  67390. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67391. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67392. }
  67393. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67394. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67395. }
  67396. // Fog
  67397. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67398. scene.fogMode = parsedData.fogMode;
  67399. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67400. scene.fogStart = parsedData.fogStart;
  67401. scene.fogEnd = parsedData.fogEnd;
  67402. scene.fogDensity = parsedData.fogDensity;
  67403. log += "\tFog mode for scene: ";
  67404. switch (scene.fogMode) {
  67405. // getters not compiling, so using hardcoded
  67406. case 1:
  67407. log += "exp\n";
  67408. break;
  67409. case 2:
  67410. log += "exp2\n";
  67411. break;
  67412. case 3:
  67413. log += "linear\n";
  67414. break;
  67415. }
  67416. }
  67417. //Physics
  67418. if (parsedData.physicsEnabled) {
  67419. var physicsPlugin;
  67420. if (parsedData.physicsEngine === "cannon") {
  67421. physicsPlugin = new BABYLON.CannonJSPlugin();
  67422. }
  67423. else if (parsedData.physicsEngine === "oimo") {
  67424. physicsPlugin = new BABYLON.OimoJSPlugin();
  67425. }
  67426. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67427. //else - default engine, which is currently oimo
  67428. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67429. scene.enablePhysics(physicsGravity, physicsPlugin);
  67430. }
  67431. // Metadata
  67432. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67433. scene.metadata = parsedData.metadata;
  67434. }
  67435. //collisions, if defined. otherwise, default is true
  67436. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67437. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67438. }
  67439. scene.workerCollisions = !!parsedData.workerCollisions;
  67440. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67441. if (!container) {
  67442. return false;
  67443. }
  67444. if (parsedData.autoAnimate) {
  67445. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67446. }
  67447. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67448. scene.setActiveCameraByID(parsedData.activeCameraID);
  67449. }
  67450. // Environment texture
  67451. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67452. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67453. if (parsedData.createDefaultSkybox === true) {
  67454. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67455. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67456. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67457. }
  67458. }
  67459. // Finish
  67460. return true;
  67461. }
  67462. catch (err) {
  67463. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67464. if (onError) {
  67465. onError(msg, err);
  67466. }
  67467. else {
  67468. BABYLON.Tools.Log(msg);
  67469. throw err;
  67470. }
  67471. }
  67472. finally {
  67473. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67474. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67475. }
  67476. }
  67477. return false;
  67478. },
  67479. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67480. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67481. return container;
  67482. }
  67483. });
  67484. })(BABYLON || (BABYLON = {}));
  67485. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67486. var BABYLON;
  67487. (function (BABYLON) {
  67488. var FilesInput = /** @class */ (function () {
  67489. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67490. this.onProcessFileCallback = function () { return true; };
  67491. this._engine = engine;
  67492. this._currentScene = scene;
  67493. this._sceneLoadedCallback = sceneLoadedCallback;
  67494. this._progressCallback = progressCallback;
  67495. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67496. this._textureLoadingCallback = textureLoadingCallback;
  67497. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67498. this._onReloadCallback = onReloadCallback;
  67499. this._errorCallback = errorCallback;
  67500. }
  67501. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67502. var _this = this;
  67503. if (elementToMonitor) {
  67504. this._elementToMonitor = elementToMonitor;
  67505. this._dragEnterHandler = function (e) { _this.drag(e); };
  67506. this._dragOverHandler = function (e) { _this.drag(e); };
  67507. this._dropHandler = function (e) { _this.drop(e); };
  67508. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67509. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67510. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67511. }
  67512. };
  67513. FilesInput.prototype.dispose = function () {
  67514. if (!this._elementToMonitor) {
  67515. return;
  67516. }
  67517. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67518. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67519. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67520. };
  67521. FilesInput.prototype.renderFunction = function () {
  67522. if (this._additionalRenderLoopLogicCallback) {
  67523. this._additionalRenderLoopLogicCallback();
  67524. }
  67525. if (this._currentScene) {
  67526. if (this._textureLoadingCallback) {
  67527. var remaining = this._currentScene.getWaitingItemsCount();
  67528. if (remaining > 0) {
  67529. this._textureLoadingCallback(remaining);
  67530. }
  67531. }
  67532. this._currentScene.render();
  67533. }
  67534. };
  67535. FilesInput.prototype.drag = function (e) {
  67536. e.stopPropagation();
  67537. e.preventDefault();
  67538. };
  67539. FilesInput.prototype.drop = function (eventDrop) {
  67540. eventDrop.stopPropagation();
  67541. eventDrop.preventDefault();
  67542. this.loadFiles(eventDrop);
  67543. };
  67544. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67545. var _this = this;
  67546. var reader = folder.createReader();
  67547. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67548. reader.readEntries(function (entries) {
  67549. remaining.count += entries.length;
  67550. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67551. var entry = entries_1[_i];
  67552. if (entry.isFile) {
  67553. entry.file(function (file) {
  67554. file.correctName = relativePath + file.name;
  67555. files.push(file);
  67556. if (--remaining.count === 0) {
  67557. callback();
  67558. }
  67559. });
  67560. }
  67561. else if (entry.isDirectory) {
  67562. _this._traverseFolder(entry, files, remaining, callback);
  67563. }
  67564. }
  67565. if (--remaining.count) {
  67566. callback();
  67567. }
  67568. });
  67569. };
  67570. FilesInput.prototype._processFiles = function (files) {
  67571. for (var i = 0; i < files.length; i++) {
  67572. var name = files[i].correctName.toLowerCase();
  67573. var extension = name.split('.').pop();
  67574. if (!this.onProcessFileCallback(files[i], name, extension)) {
  67575. continue;
  67576. }
  67577. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  67578. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  67579. this._sceneFileToLoad = files[i];
  67580. }
  67581. else {
  67582. FilesInput.FilesToLoad[name] = files[i];
  67583. }
  67584. }
  67585. };
  67586. FilesInput.prototype.loadFiles = function (event) {
  67587. var _this = this;
  67588. if (this._startingProcessingFilesCallback)
  67589. this._startingProcessingFilesCallback();
  67590. // Handling data transfer via drag'n'drop
  67591. if (event && event.dataTransfer && event.dataTransfer.files) {
  67592. this._filesToLoad = event.dataTransfer.files;
  67593. }
  67594. // Handling files from input files
  67595. if (event && event.target && event.target.files) {
  67596. this._filesToLoad = event.target.files;
  67597. }
  67598. if (this._filesToLoad && this._filesToLoad.length > 0) {
  67599. var files_1 = new Array();
  67600. var folders = [];
  67601. var items = event.dataTransfer ? event.dataTransfer.items : null;
  67602. for (var i = 0; i < this._filesToLoad.length; i++) {
  67603. var fileToLoad = this._filesToLoad[i];
  67604. var name_1 = fileToLoad.name.toLowerCase();
  67605. var entry = void 0;
  67606. fileToLoad.correctName = name_1;
  67607. if (items) {
  67608. var item = items[i];
  67609. if (item.getAsEntry) {
  67610. entry = item.getAsEntry();
  67611. }
  67612. else if (item.webkitGetAsEntry) {
  67613. entry = item.webkitGetAsEntry();
  67614. }
  67615. }
  67616. if (!entry) {
  67617. files_1.push(fileToLoad);
  67618. }
  67619. else {
  67620. if (entry.isDirectory) {
  67621. folders.push(entry);
  67622. }
  67623. else {
  67624. files_1.push(fileToLoad);
  67625. }
  67626. }
  67627. }
  67628. if (folders.length === 0) {
  67629. this._processFiles(files_1);
  67630. this._processReload();
  67631. }
  67632. else {
  67633. var remaining = { count: folders.length };
  67634. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  67635. var folder = folders_1[_i];
  67636. this._traverseFolder(folder, files_1, remaining, function () {
  67637. _this._processFiles(files_1);
  67638. if (remaining.count === 0) {
  67639. _this._processReload();
  67640. }
  67641. });
  67642. }
  67643. }
  67644. }
  67645. };
  67646. FilesInput.prototype._processReload = function () {
  67647. if (this._onReloadCallback) {
  67648. this._onReloadCallback(this._sceneFileToLoad);
  67649. }
  67650. else {
  67651. this.reload();
  67652. }
  67653. };
  67654. FilesInput.prototype.reload = function () {
  67655. var _this = this;
  67656. // If a scene file has been provided
  67657. if (this._sceneFileToLoad) {
  67658. if (this._currentScene) {
  67659. if (BABYLON.Tools.errorsCount > 0) {
  67660. BABYLON.Tools.ClearLogCache();
  67661. }
  67662. this._engine.stopRenderLoop();
  67663. this._currentScene.dispose();
  67664. }
  67665. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  67666. if (_this._progressCallback) {
  67667. _this._progressCallback(progress);
  67668. }
  67669. }).then(function (scene) {
  67670. _this._currentScene = scene;
  67671. if (_this._sceneLoadedCallback) {
  67672. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  67673. }
  67674. // Wait for textures and shaders to be ready
  67675. _this._currentScene.executeWhenReady(function () {
  67676. _this._engine.runRenderLoop(function () {
  67677. _this.renderFunction();
  67678. });
  67679. });
  67680. }).catch(function (error) {
  67681. if (_this._errorCallback) {
  67682. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  67683. }
  67684. });
  67685. }
  67686. else {
  67687. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  67688. }
  67689. };
  67690. FilesInput.FilesToLoad = {};
  67691. return FilesInput;
  67692. }());
  67693. BABYLON.FilesInput = FilesInput;
  67694. })(BABYLON || (BABYLON = {}));
  67695. //# sourceMappingURL=babylon.filesInput.js.map
  67696. var BABYLON;
  67697. (function (BABYLON) {
  67698. /**
  67699. * This class implement a typical dictionary using a string as key and the generic type T as value.
  67700. * The underlying implementation relies on an associative array to ensure the best performances.
  67701. * The value can be anything including 'null' but except 'undefined'
  67702. */
  67703. var StringDictionary = /** @class */ (function () {
  67704. function StringDictionary() {
  67705. this._count = 0;
  67706. this._data = {};
  67707. }
  67708. /**
  67709. * This will clear this dictionary and copy the content from the 'source' one.
  67710. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  67711. * @param source the dictionary to take the content from and copy to this dictionary
  67712. */
  67713. StringDictionary.prototype.copyFrom = function (source) {
  67714. var _this = this;
  67715. this.clear();
  67716. source.forEach(function (t, v) { return _this.add(t, v); });
  67717. };
  67718. /**
  67719. * Get a value based from its key
  67720. * @param key the given key to get the matching value from
  67721. * @return the value if found, otherwise undefined is returned
  67722. */
  67723. StringDictionary.prototype.get = function (key) {
  67724. var val = this._data[key];
  67725. if (val !== undefined) {
  67726. return val;
  67727. }
  67728. return undefined;
  67729. };
  67730. /**
  67731. * Get a value from its key or add it if it doesn't exist.
  67732. * This method will ensure you that a given key/data will be present in the dictionary.
  67733. * @param key the given key to get the matching value from
  67734. * @param factory the factory that will create the value if the key is not present in the dictionary.
  67735. * The factory will only be invoked if there's no data for the given key.
  67736. * @return the value corresponding to the key.
  67737. */
  67738. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  67739. var val = this.get(key);
  67740. if (val !== undefined) {
  67741. return val;
  67742. }
  67743. val = factory(key);
  67744. if (val) {
  67745. this.add(key, val);
  67746. }
  67747. return val;
  67748. };
  67749. /**
  67750. * Get a value from its key if present in the dictionary otherwise add it
  67751. * @param key the key to get the value from
  67752. * @param val if there's no such key/value pair in the dictionary add it with this value
  67753. * @return the value corresponding to the key
  67754. */
  67755. StringDictionary.prototype.getOrAdd = function (key, val) {
  67756. var curVal = this.get(key);
  67757. if (curVal !== undefined) {
  67758. return curVal;
  67759. }
  67760. this.add(key, val);
  67761. return val;
  67762. };
  67763. /**
  67764. * Check if there's a given key in the dictionary
  67765. * @param key the key to check for
  67766. * @return true if the key is present, false otherwise
  67767. */
  67768. StringDictionary.prototype.contains = function (key) {
  67769. return this._data[key] !== undefined;
  67770. };
  67771. /**
  67772. * Add a new key and its corresponding value
  67773. * @param key the key to add
  67774. * @param value the value corresponding to the key
  67775. * @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
  67776. */
  67777. StringDictionary.prototype.add = function (key, value) {
  67778. if (this._data[key] !== undefined) {
  67779. return false;
  67780. }
  67781. this._data[key] = value;
  67782. ++this._count;
  67783. return true;
  67784. };
  67785. StringDictionary.prototype.set = function (key, value) {
  67786. if (this._data[key] === undefined) {
  67787. return false;
  67788. }
  67789. this._data[key] = value;
  67790. return true;
  67791. };
  67792. /**
  67793. * Get the element of the given key and remove it from the dictionary
  67794. * @param key
  67795. */
  67796. StringDictionary.prototype.getAndRemove = function (key) {
  67797. var val = this.get(key);
  67798. if (val !== undefined) {
  67799. delete this._data[key];
  67800. --this._count;
  67801. return val;
  67802. }
  67803. return null;
  67804. };
  67805. /**
  67806. * Remove a key/value from the dictionary.
  67807. * @param key the key to remove
  67808. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  67809. */
  67810. StringDictionary.prototype.remove = function (key) {
  67811. if (this.contains(key)) {
  67812. delete this._data[key];
  67813. --this._count;
  67814. return true;
  67815. }
  67816. return false;
  67817. };
  67818. /**
  67819. * Clear the whole content of the dictionary
  67820. */
  67821. StringDictionary.prototype.clear = function () {
  67822. this._data = {};
  67823. this._count = 0;
  67824. };
  67825. Object.defineProperty(StringDictionary.prototype, "count", {
  67826. get: function () {
  67827. return this._count;
  67828. },
  67829. enumerable: true,
  67830. configurable: true
  67831. });
  67832. /**
  67833. * Execute a callback on each key/val of the dictionary.
  67834. * Note that you can remove any element in this dictionary in the callback implementation
  67835. * @param callback the callback to execute on a given key/value pair
  67836. */
  67837. StringDictionary.prototype.forEach = function (callback) {
  67838. for (var cur in this._data) {
  67839. var val = this._data[cur];
  67840. callback(cur, val);
  67841. }
  67842. };
  67843. /**
  67844. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  67845. * If the callback returns null or undefined the method will iterate to the next key/value pair
  67846. * Note that you can remove any element in this dictionary in the callback implementation
  67847. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  67848. */
  67849. StringDictionary.prototype.first = function (callback) {
  67850. for (var cur in this._data) {
  67851. var val = this._data[cur];
  67852. var res = callback(cur, val);
  67853. if (res) {
  67854. return res;
  67855. }
  67856. }
  67857. return null;
  67858. };
  67859. return StringDictionary;
  67860. }());
  67861. BABYLON.StringDictionary = StringDictionary;
  67862. })(BABYLON || (BABYLON = {}));
  67863. //# sourceMappingURL=babylon.stringDictionary.js.map
  67864. var BABYLON;
  67865. (function (BABYLON) {
  67866. var Tags = /** @class */ (function () {
  67867. function Tags() {
  67868. }
  67869. Tags.EnableFor = function (obj) {
  67870. obj._tags = obj._tags || {};
  67871. obj.hasTags = function () {
  67872. return Tags.HasTags(obj);
  67873. };
  67874. obj.addTags = function (tagsString) {
  67875. return Tags.AddTagsTo(obj, tagsString);
  67876. };
  67877. obj.removeTags = function (tagsString) {
  67878. return Tags.RemoveTagsFrom(obj, tagsString);
  67879. };
  67880. obj.matchesTagsQuery = function (tagsQuery) {
  67881. return Tags.MatchesQuery(obj, tagsQuery);
  67882. };
  67883. };
  67884. Tags.DisableFor = function (obj) {
  67885. delete obj._tags;
  67886. delete obj.hasTags;
  67887. delete obj.addTags;
  67888. delete obj.removeTags;
  67889. delete obj.matchesTagsQuery;
  67890. };
  67891. Tags.HasTags = function (obj) {
  67892. if (!obj._tags) {
  67893. return false;
  67894. }
  67895. return !BABYLON.Tools.IsEmpty(obj._tags);
  67896. };
  67897. Tags.GetTags = function (obj, asString) {
  67898. if (asString === void 0) { asString = true; }
  67899. if (!obj._tags) {
  67900. return null;
  67901. }
  67902. if (asString) {
  67903. var tagsArray = [];
  67904. for (var tag in obj._tags) {
  67905. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  67906. tagsArray.push(tag);
  67907. }
  67908. }
  67909. return tagsArray.join(" ");
  67910. }
  67911. else {
  67912. return obj._tags;
  67913. }
  67914. };
  67915. // the tags 'true' and 'false' are reserved and cannot be used as tags
  67916. // a tag cannot start with '||', '&&', and '!'
  67917. // it cannot contain whitespaces
  67918. Tags.AddTagsTo = function (obj, tagsString) {
  67919. if (!tagsString) {
  67920. return;
  67921. }
  67922. if (typeof tagsString !== "string") {
  67923. return;
  67924. }
  67925. var tags = tagsString.split(" ");
  67926. tags.forEach(function (tag, index, array) {
  67927. Tags._AddTagTo(obj, tag);
  67928. });
  67929. };
  67930. Tags._AddTagTo = function (obj, tag) {
  67931. tag = tag.trim();
  67932. if (tag === "" || tag === "true" || tag === "false") {
  67933. return;
  67934. }
  67935. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  67936. return;
  67937. }
  67938. Tags.EnableFor(obj);
  67939. obj._tags[tag] = true;
  67940. };
  67941. Tags.RemoveTagsFrom = function (obj, tagsString) {
  67942. if (!Tags.HasTags(obj)) {
  67943. return;
  67944. }
  67945. var tags = tagsString.split(" ");
  67946. for (var t in tags) {
  67947. Tags._RemoveTagFrom(obj, tags[t]);
  67948. }
  67949. };
  67950. Tags._RemoveTagFrom = function (obj, tag) {
  67951. delete obj._tags[tag];
  67952. };
  67953. Tags.MatchesQuery = function (obj, tagsQuery) {
  67954. if (tagsQuery === undefined) {
  67955. return true;
  67956. }
  67957. if (tagsQuery === "") {
  67958. return Tags.HasTags(obj);
  67959. }
  67960. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  67961. };
  67962. return Tags;
  67963. }());
  67964. BABYLON.Tags = Tags;
  67965. })(BABYLON || (BABYLON = {}));
  67966. //# sourceMappingURL=babylon.tags.js.map
  67967. var BABYLON;
  67968. (function (BABYLON) {
  67969. var AndOrNotEvaluator = /** @class */ (function () {
  67970. function AndOrNotEvaluator() {
  67971. }
  67972. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  67973. if (!query.match(/\([^\(\)]*\)/g)) {
  67974. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  67975. }
  67976. else {
  67977. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  67978. // remove parenthesis
  67979. r = r.slice(1, r.length - 1);
  67980. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  67981. });
  67982. }
  67983. if (query === "true") {
  67984. return true;
  67985. }
  67986. if (query === "false") {
  67987. return false;
  67988. }
  67989. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  67990. };
  67991. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  67992. evaluateCallback = evaluateCallback || (function (r) {
  67993. return r === "true" ? true : false;
  67994. });
  67995. var result;
  67996. var or = parenthesisContent.split("||");
  67997. for (var i in or) {
  67998. if (or.hasOwnProperty(i)) {
  67999. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68000. var and = ori.split("&&");
  68001. if (and.length > 1) {
  68002. for (var j = 0; j < and.length; ++j) {
  68003. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68004. if (andj !== "true" && andj !== "false") {
  68005. if (andj[0] === "!") {
  68006. result = !evaluateCallback(andj.substring(1));
  68007. }
  68008. else {
  68009. result = evaluateCallback(andj);
  68010. }
  68011. }
  68012. else {
  68013. result = andj === "true" ? true : false;
  68014. }
  68015. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68016. ori = "false";
  68017. break;
  68018. }
  68019. }
  68020. }
  68021. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68022. result = true;
  68023. break;
  68024. }
  68025. // result equals false (or undefined)
  68026. if (ori !== "true" && ori !== "false") {
  68027. if (ori[0] === "!") {
  68028. result = !evaluateCallback(ori.substring(1));
  68029. }
  68030. else {
  68031. result = evaluateCallback(ori);
  68032. }
  68033. }
  68034. else {
  68035. result = ori === "true" ? true : false;
  68036. }
  68037. }
  68038. }
  68039. // the whole parenthesis scope is replaced by 'true' or 'false'
  68040. return result ? "true" : "false";
  68041. };
  68042. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68043. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68044. // remove whitespaces
  68045. r = r.replace(/[\s]/g, function () { return ""; });
  68046. return r.length % 2 ? "!" : "";
  68047. });
  68048. booleanString = booleanString.trim();
  68049. if (booleanString === "!true") {
  68050. booleanString = "false";
  68051. }
  68052. else if (booleanString === "!false") {
  68053. booleanString = "true";
  68054. }
  68055. return booleanString;
  68056. };
  68057. return AndOrNotEvaluator;
  68058. }());
  68059. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68060. })(BABYLON || (BABYLON = {}));
  68061. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68062. var BABYLON;
  68063. (function (BABYLON) {
  68064. var Database = /** @class */ (function () {
  68065. function Database(urlToScene, callbackManifestChecked) {
  68066. // Handling various flavors of prefixed version of IndexedDB
  68067. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68068. this.callbackManifestChecked = callbackManifestChecked;
  68069. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  68070. this.db = null;
  68071. this._enableSceneOffline = false;
  68072. this._enableTexturesOffline = false;
  68073. this.manifestVersionFound = 0;
  68074. this.mustUpdateRessources = false;
  68075. this.hasReachedQuota = false;
  68076. if (!Database.IDBStorageEnabled) {
  68077. this.callbackManifestChecked(true);
  68078. }
  68079. else {
  68080. this.checkManifestFile();
  68081. }
  68082. }
  68083. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68084. get: function () {
  68085. return this._enableSceneOffline;
  68086. },
  68087. enumerable: true,
  68088. configurable: true
  68089. });
  68090. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68091. get: function () {
  68092. return this._enableTexturesOffline;
  68093. },
  68094. enumerable: true,
  68095. configurable: true
  68096. });
  68097. Database.prototype.checkManifestFile = function () {
  68098. var _this = this;
  68099. var noManifestFile = function () {
  68100. _this._enableSceneOffline = false;
  68101. _this._enableTexturesOffline = false;
  68102. _this.callbackManifestChecked(false);
  68103. };
  68104. var timeStampUsed = false;
  68105. var manifestURL = this.currentSceneUrl + ".manifest";
  68106. var xhr = new XMLHttpRequest();
  68107. if (navigator.onLine) {
  68108. // Adding a timestamp to by-pass browsers' cache
  68109. timeStampUsed = true;
  68110. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  68111. }
  68112. xhr.open("GET", manifestURL, true);
  68113. xhr.addEventListener("load", function () {
  68114. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68115. try {
  68116. var manifestFile = JSON.parse(xhr.response);
  68117. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68118. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68119. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68120. _this.manifestVersionFound = manifestFile.version;
  68121. }
  68122. if (_this.callbackManifestChecked) {
  68123. _this.callbackManifestChecked(true);
  68124. }
  68125. }
  68126. catch (ex) {
  68127. noManifestFile();
  68128. }
  68129. }
  68130. else {
  68131. noManifestFile();
  68132. }
  68133. }, false);
  68134. xhr.addEventListener("error", function (event) {
  68135. if (timeStampUsed) {
  68136. timeStampUsed = false;
  68137. // Let's retry without the timeStamp
  68138. // It could fail when coupled with HTML5 Offline API
  68139. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68140. xhr.open("GET", retryManifestURL, true);
  68141. xhr.send();
  68142. }
  68143. else {
  68144. noManifestFile();
  68145. }
  68146. }, false);
  68147. try {
  68148. xhr.send();
  68149. }
  68150. catch (ex) {
  68151. BABYLON.Tools.Error("Error on XHR send request.");
  68152. this.callbackManifestChecked(false);
  68153. }
  68154. };
  68155. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68156. var _this = this;
  68157. var handleError = function () {
  68158. _this.isSupported = false;
  68159. if (errorCallback)
  68160. errorCallback();
  68161. };
  68162. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68163. // Your browser doesn't support IndexedDB
  68164. this.isSupported = false;
  68165. if (errorCallback)
  68166. errorCallback();
  68167. }
  68168. else {
  68169. // If the DB hasn't been opened or created yet
  68170. if (!this.db) {
  68171. this.hasReachedQuota = false;
  68172. this.isSupported = true;
  68173. var request = this.idbFactory.open("babylonjs", 1);
  68174. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68175. request.onerror = function (event) {
  68176. handleError();
  68177. };
  68178. // executes when a version change transaction cannot complete due to other active transactions
  68179. request.onblocked = function (event) {
  68180. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68181. handleError();
  68182. };
  68183. // DB has been opened successfully
  68184. request.onsuccess = function (event) {
  68185. _this.db = request.result;
  68186. successCallback();
  68187. };
  68188. // Initialization of the DB. Creating Scenes & Textures stores
  68189. request.onupgradeneeded = function (event) {
  68190. _this.db = (event.target).result;
  68191. if (_this.db) {
  68192. try {
  68193. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68194. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68195. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68196. }
  68197. catch (ex) {
  68198. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68199. handleError();
  68200. }
  68201. }
  68202. };
  68203. }
  68204. // DB has already been created and opened
  68205. else {
  68206. if (successCallback)
  68207. successCallback();
  68208. }
  68209. }
  68210. };
  68211. Database.prototype.loadImageFromDB = function (url, image) {
  68212. var _this = this;
  68213. var completeURL = Database.ReturnFullUrlLocation(url);
  68214. var saveAndLoadImage = function () {
  68215. if (!_this.hasReachedQuota && _this.db !== null) {
  68216. // the texture is not yet in the DB, let's try to save it
  68217. _this._saveImageIntoDBAsync(completeURL, image);
  68218. }
  68219. // If the texture is not in the DB and we've reached the DB quota limit
  68220. // let's load it directly from the web
  68221. else {
  68222. image.src = url;
  68223. }
  68224. };
  68225. if (!this.mustUpdateRessources) {
  68226. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68227. }
  68228. // First time we're download the images or update requested in the manifest file by a version change
  68229. else {
  68230. saveAndLoadImage();
  68231. }
  68232. };
  68233. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68234. if (this.isSupported && this.db !== null) {
  68235. var texture;
  68236. var transaction = this.db.transaction(["textures"]);
  68237. transaction.onabort = function (event) {
  68238. image.src = url;
  68239. };
  68240. transaction.oncomplete = function (event) {
  68241. var blobTextureURL;
  68242. if (texture) {
  68243. var URL = window.URL || window.webkitURL;
  68244. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68245. image.onerror = function () {
  68246. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68247. image.src = url;
  68248. };
  68249. image.src = blobTextureURL;
  68250. }
  68251. else {
  68252. notInDBCallback();
  68253. }
  68254. };
  68255. var getRequest = transaction.objectStore("textures").get(url);
  68256. getRequest.onsuccess = function (event) {
  68257. texture = (event.target).result;
  68258. };
  68259. getRequest.onerror = function (event) {
  68260. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68261. image.src = url;
  68262. };
  68263. }
  68264. else {
  68265. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68266. image.src = url;
  68267. }
  68268. };
  68269. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68270. var _this = this;
  68271. if (this.isSupported) {
  68272. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68273. var generateBlobUrl = function () {
  68274. var blobTextureURL;
  68275. if (blob) {
  68276. var URL = window.URL || window.webkitURL;
  68277. try {
  68278. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68279. }
  68280. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68281. catch (ex) {
  68282. blobTextureURL = URL.createObjectURL(blob);
  68283. }
  68284. }
  68285. if (blobTextureURL) {
  68286. image.src = blobTextureURL;
  68287. }
  68288. };
  68289. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68290. var xhr = new XMLHttpRequest(), blob;
  68291. xhr.open("GET", url, true);
  68292. xhr.responseType = "blob";
  68293. xhr.addEventListener("load", function () {
  68294. if (xhr.status === 200 && _this.db) {
  68295. // Blob as response (XHR2)
  68296. blob = xhr.response;
  68297. var transaction = _this.db.transaction(["textures"], "readwrite");
  68298. // the transaction could abort because of a QuotaExceededError error
  68299. transaction.onabort = function (event) {
  68300. try {
  68301. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68302. var srcElement = (event.srcElement || event.target);
  68303. var error = srcElement.error;
  68304. if (error && error.name === "QuotaExceededError") {
  68305. _this.hasReachedQuota = true;
  68306. }
  68307. }
  68308. catch (ex) { }
  68309. generateBlobUrl();
  68310. };
  68311. transaction.oncomplete = function (event) {
  68312. generateBlobUrl();
  68313. };
  68314. var newTexture = { textureUrl: url, data: blob };
  68315. try {
  68316. // Put the blob into the dabase
  68317. var addRequest = transaction.objectStore("textures").put(newTexture);
  68318. addRequest.onsuccess = function (event) {
  68319. };
  68320. addRequest.onerror = function (event) {
  68321. generateBlobUrl();
  68322. };
  68323. }
  68324. catch (ex) {
  68325. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68326. if (ex.code === 25) {
  68327. Database.IsUASupportingBlobStorage = false;
  68328. }
  68329. image.src = url;
  68330. }
  68331. }
  68332. else {
  68333. image.src = url;
  68334. }
  68335. }, false);
  68336. xhr.addEventListener("error", function (event) {
  68337. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68338. image.src = url;
  68339. }, false);
  68340. xhr.send();
  68341. }
  68342. else {
  68343. image.src = url;
  68344. }
  68345. }
  68346. else {
  68347. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68348. image.src = url;
  68349. }
  68350. };
  68351. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68352. var _this = this;
  68353. var updateVersion = function () {
  68354. // the version is not yet in the DB or we need to update it
  68355. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68356. };
  68357. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68358. };
  68359. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68360. var _this = this;
  68361. if (this.isSupported && this.db) {
  68362. var version;
  68363. try {
  68364. var transaction = this.db.transaction(["versions"]);
  68365. transaction.oncomplete = function (event) {
  68366. if (version) {
  68367. // If the version in the JSON file is > than the version in DB
  68368. if (_this.manifestVersionFound > version.data) {
  68369. _this.mustUpdateRessources = true;
  68370. updateInDBCallback();
  68371. }
  68372. else {
  68373. callback(version.data);
  68374. }
  68375. }
  68376. // version was not found in DB
  68377. else {
  68378. _this.mustUpdateRessources = true;
  68379. updateInDBCallback();
  68380. }
  68381. };
  68382. transaction.onabort = function (event) {
  68383. callback(-1);
  68384. };
  68385. var getRequest = transaction.objectStore("versions").get(url);
  68386. getRequest.onsuccess = function (event) {
  68387. version = (event.target).result;
  68388. };
  68389. getRequest.onerror = function (event) {
  68390. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68391. callback(-1);
  68392. };
  68393. }
  68394. catch (ex) {
  68395. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68396. callback(-1);
  68397. }
  68398. }
  68399. else {
  68400. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68401. callback(-1);
  68402. }
  68403. };
  68404. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68405. var _this = this;
  68406. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68407. try {
  68408. // Open a transaction to the database
  68409. var transaction = this.db.transaction(["versions"], "readwrite");
  68410. // the transaction could abort because of a QuotaExceededError error
  68411. transaction.onabort = function (event) {
  68412. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68413. var error = event.srcElement['error'];
  68414. if (error && error.name === "QuotaExceededError") {
  68415. _this.hasReachedQuota = true;
  68416. }
  68417. }
  68418. catch (ex) { }
  68419. callback(-1);
  68420. };
  68421. transaction.oncomplete = function (event) {
  68422. callback(_this.manifestVersionFound);
  68423. };
  68424. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68425. // Put the scene into the database
  68426. var addRequest = transaction.objectStore("versions").put(newVersion);
  68427. addRequest.onsuccess = function (event) {
  68428. };
  68429. addRequest.onerror = function (event) {
  68430. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68431. };
  68432. }
  68433. catch (ex) {
  68434. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68435. callback(-1);
  68436. }
  68437. }
  68438. else {
  68439. callback(-1);
  68440. }
  68441. };
  68442. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68443. var _this = this;
  68444. var completeUrl = Database.ReturnFullUrlLocation(url);
  68445. var saveAndLoadFile = function () {
  68446. // the scene is not yet in the DB, let's try to save it
  68447. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68448. };
  68449. this._checkVersionFromDB(completeUrl, function (version) {
  68450. if (version !== -1) {
  68451. if (!_this.mustUpdateRessources) {
  68452. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68453. }
  68454. else {
  68455. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68456. }
  68457. }
  68458. else {
  68459. if (errorCallback) {
  68460. errorCallback();
  68461. }
  68462. }
  68463. });
  68464. };
  68465. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68466. if (this.isSupported && this.db) {
  68467. var targetStore;
  68468. if (url.indexOf(".babylon") !== -1) {
  68469. targetStore = "scenes";
  68470. }
  68471. else {
  68472. targetStore = "textures";
  68473. }
  68474. var file;
  68475. var transaction = this.db.transaction([targetStore]);
  68476. transaction.oncomplete = function (event) {
  68477. if (file) {
  68478. callback(file.data);
  68479. }
  68480. // file was not found in DB
  68481. else {
  68482. notInDBCallback();
  68483. }
  68484. };
  68485. transaction.onabort = function (event) {
  68486. notInDBCallback();
  68487. };
  68488. var getRequest = transaction.objectStore(targetStore).get(url);
  68489. getRequest.onsuccess = function (event) {
  68490. file = (event.target).result;
  68491. };
  68492. getRequest.onerror = function (event) {
  68493. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68494. notInDBCallback();
  68495. };
  68496. }
  68497. else {
  68498. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68499. callback();
  68500. }
  68501. };
  68502. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68503. var _this = this;
  68504. if (this.isSupported) {
  68505. var targetStore;
  68506. if (url.indexOf(".babylon") !== -1) {
  68507. targetStore = "scenes";
  68508. }
  68509. else {
  68510. targetStore = "textures";
  68511. }
  68512. // Create XHR
  68513. var xhr = new XMLHttpRequest();
  68514. var fileData;
  68515. xhr.open("GET", url, true);
  68516. if (useArrayBuffer) {
  68517. xhr.responseType = "arraybuffer";
  68518. }
  68519. if (progressCallback) {
  68520. xhr.onprogress = progressCallback;
  68521. }
  68522. xhr.addEventListener("load", function () {
  68523. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  68524. // Blob as response (XHR2)
  68525. //fileData = xhr.responseText;
  68526. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  68527. if (!_this.hasReachedQuota && _this.db) {
  68528. // Open a transaction to the database
  68529. var transaction = _this.db.transaction([targetStore], "readwrite");
  68530. // the transaction could abort because of a QuotaExceededError error
  68531. transaction.onabort = function (event) {
  68532. try {
  68533. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68534. var error = event.srcElement['error'];
  68535. if (error && error.name === "QuotaExceededError") {
  68536. _this.hasReachedQuota = true;
  68537. }
  68538. }
  68539. catch (ex) { }
  68540. callback(fileData);
  68541. };
  68542. transaction.oncomplete = function (event) {
  68543. callback(fileData);
  68544. };
  68545. var newFile;
  68546. if (targetStore === "scenes") {
  68547. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  68548. }
  68549. else {
  68550. newFile = { textureUrl: url, data: fileData };
  68551. }
  68552. try {
  68553. // Put the scene into the database
  68554. var addRequest = transaction.objectStore(targetStore).put(newFile);
  68555. addRequest.onsuccess = function (event) {
  68556. };
  68557. addRequest.onerror = function (event) {
  68558. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  68559. };
  68560. }
  68561. catch (ex) {
  68562. callback(fileData);
  68563. }
  68564. }
  68565. else {
  68566. callback(fileData);
  68567. }
  68568. }
  68569. else {
  68570. callback();
  68571. }
  68572. }, false);
  68573. xhr.addEventListener("error", function (event) {
  68574. BABYLON.Tools.Error("error on XHR request.");
  68575. callback();
  68576. }, false);
  68577. xhr.send();
  68578. }
  68579. else {
  68580. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68581. callback();
  68582. }
  68583. };
  68584. Database.IsUASupportingBlobStorage = true;
  68585. Database.IDBStorageEnabled = true;
  68586. Database.parseURL = function (url) {
  68587. var a = document.createElement('a');
  68588. a.href = url;
  68589. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  68590. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  68591. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  68592. return absLocation;
  68593. };
  68594. Database.ReturnFullUrlLocation = function (url) {
  68595. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  68596. return (Database.parseURL(window.location.href) + url);
  68597. }
  68598. else {
  68599. return url;
  68600. }
  68601. };
  68602. return Database;
  68603. }());
  68604. BABYLON.Database = Database;
  68605. })(BABYLON || (BABYLON = {}));
  68606. //# sourceMappingURL=babylon.database.js.map
  68607. var BABYLON;
  68608. (function (BABYLON) {
  68609. var FresnelParameters = /** @class */ (function () {
  68610. function FresnelParameters() {
  68611. this._isEnabled = true;
  68612. this.leftColor = BABYLON.Color3.White();
  68613. this.rightColor = BABYLON.Color3.Black();
  68614. this.bias = 0;
  68615. this.power = 1;
  68616. }
  68617. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  68618. get: function () {
  68619. return this._isEnabled;
  68620. },
  68621. set: function (value) {
  68622. if (this._isEnabled === value) {
  68623. return;
  68624. }
  68625. this._isEnabled = value;
  68626. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  68627. },
  68628. enumerable: true,
  68629. configurable: true
  68630. });
  68631. FresnelParameters.prototype.clone = function () {
  68632. var newFresnelParameters = new FresnelParameters();
  68633. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  68634. return newFresnelParameters;
  68635. };
  68636. FresnelParameters.prototype.serialize = function () {
  68637. var serializationObject = {};
  68638. serializationObject.isEnabled = this.isEnabled;
  68639. serializationObject.leftColor = this.leftColor.asArray();
  68640. serializationObject.rightColor = this.rightColor.asArray();
  68641. serializationObject.bias = this.bias;
  68642. serializationObject.power = this.power;
  68643. return serializationObject;
  68644. };
  68645. FresnelParameters.Parse = function (parsedFresnelParameters) {
  68646. var fresnelParameters = new FresnelParameters();
  68647. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  68648. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  68649. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  68650. fresnelParameters.bias = parsedFresnelParameters.bias;
  68651. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  68652. return fresnelParameters;
  68653. };
  68654. return FresnelParameters;
  68655. }());
  68656. BABYLON.FresnelParameters = FresnelParameters;
  68657. })(BABYLON || (BABYLON = {}));
  68658. //# sourceMappingURL=babylon.fresnelParameters.js.map
  68659. var BABYLON;
  68660. (function (BABYLON) {
  68661. var MultiMaterial = /** @class */ (function (_super) {
  68662. __extends(MultiMaterial, _super);
  68663. function MultiMaterial(name, scene) {
  68664. var _this = _super.call(this, name, scene, true) || this;
  68665. scene.multiMaterials.push(_this);
  68666. _this.subMaterials = new Array();
  68667. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  68668. return _this;
  68669. }
  68670. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  68671. get: function () {
  68672. return this._subMaterials;
  68673. },
  68674. set: function (value) {
  68675. this._subMaterials = value;
  68676. this._hookArray(value);
  68677. },
  68678. enumerable: true,
  68679. configurable: true
  68680. });
  68681. MultiMaterial.prototype._hookArray = function (array) {
  68682. var _this = this;
  68683. var oldPush = array.push;
  68684. array.push = function () {
  68685. var items = [];
  68686. for (var _i = 0; _i < arguments.length; _i++) {
  68687. items[_i] = arguments[_i];
  68688. }
  68689. var result = oldPush.apply(array, items);
  68690. _this._markAllSubMeshesAsTexturesDirty();
  68691. return result;
  68692. };
  68693. var oldSplice = array.splice;
  68694. array.splice = function (index, deleteCount) {
  68695. var deleted = oldSplice.apply(array, [index, deleteCount]);
  68696. _this._markAllSubMeshesAsTexturesDirty();
  68697. return deleted;
  68698. };
  68699. };
  68700. // Properties
  68701. MultiMaterial.prototype.getSubMaterial = function (index) {
  68702. if (index < 0 || index >= this.subMaterials.length) {
  68703. return this.getScene().defaultMaterial;
  68704. }
  68705. return this.subMaterials[index];
  68706. };
  68707. MultiMaterial.prototype.getActiveTextures = function () {
  68708. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  68709. if (subMaterial) {
  68710. return subMaterial.getActiveTextures();
  68711. }
  68712. else {
  68713. return [];
  68714. }
  68715. }));
  68716. var _a;
  68717. };
  68718. // Methods
  68719. MultiMaterial.prototype.getClassName = function () {
  68720. return "MultiMaterial";
  68721. };
  68722. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  68723. for (var index = 0; index < this.subMaterials.length; index++) {
  68724. var subMaterial = this.subMaterials[index];
  68725. if (subMaterial) {
  68726. if (subMaterial.storeEffectOnSubMeshes) {
  68727. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  68728. return false;
  68729. }
  68730. continue;
  68731. }
  68732. if (!subMaterial.isReady(mesh)) {
  68733. return false;
  68734. }
  68735. }
  68736. }
  68737. return true;
  68738. };
  68739. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  68740. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  68741. for (var index = 0; index < this.subMaterials.length; index++) {
  68742. var subMaterial = null;
  68743. var current = this.subMaterials[index];
  68744. if (cloneChildren && current) {
  68745. subMaterial = current.clone(name + "-" + current.name);
  68746. }
  68747. else {
  68748. subMaterial = this.subMaterials[index];
  68749. }
  68750. newMultiMaterial.subMaterials.push(subMaterial);
  68751. }
  68752. return newMultiMaterial;
  68753. };
  68754. MultiMaterial.prototype.serialize = function () {
  68755. var serializationObject = {};
  68756. serializationObject.name = this.name;
  68757. serializationObject.id = this.id;
  68758. if (BABYLON.Tags) {
  68759. serializationObject.tags = BABYLON.Tags.GetTags(this);
  68760. }
  68761. serializationObject.materials = [];
  68762. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  68763. var subMat = this.subMaterials[matIndex];
  68764. if (subMat) {
  68765. serializationObject.materials.push(subMat.id);
  68766. }
  68767. else {
  68768. serializationObject.materials.push(null);
  68769. }
  68770. }
  68771. return serializationObject;
  68772. };
  68773. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  68774. var scene = this.getScene();
  68775. if (!scene) {
  68776. return;
  68777. }
  68778. var index = scene.multiMaterials.indexOf(this);
  68779. if (index >= 0) {
  68780. scene.multiMaterials.splice(index, 1);
  68781. }
  68782. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  68783. };
  68784. return MultiMaterial;
  68785. }(BABYLON.Material));
  68786. BABYLON.MultiMaterial = MultiMaterial;
  68787. })(BABYLON || (BABYLON = {}));
  68788. //# sourceMappingURL=babylon.multiMaterial.js.map
  68789. var BABYLON;
  68790. (function (BABYLON) {
  68791. var FreeCameraTouchInput = /** @class */ (function () {
  68792. function FreeCameraTouchInput() {
  68793. this._offsetX = null;
  68794. this._offsetY = null;
  68795. this._pointerPressed = new Array();
  68796. this.touchAngularSensibility = 200000.0;
  68797. this.touchMoveSensibility = 250.0;
  68798. }
  68799. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  68800. var _this = this;
  68801. var previousPosition = null;
  68802. if (this._pointerInput === undefined) {
  68803. this._onLostFocus = function (evt) {
  68804. _this._offsetX = null;
  68805. _this._offsetY = null;
  68806. };
  68807. this._pointerInput = function (p, s) {
  68808. var evt = p.event;
  68809. if (evt.pointerType === "mouse") {
  68810. return;
  68811. }
  68812. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  68813. if (!noPreventDefault) {
  68814. evt.preventDefault();
  68815. }
  68816. _this._pointerPressed.push(evt.pointerId);
  68817. if (_this._pointerPressed.length !== 1) {
  68818. return;
  68819. }
  68820. previousPosition = {
  68821. x: evt.clientX,
  68822. y: evt.clientY
  68823. };
  68824. }
  68825. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  68826. if (!noPreventDefault) {
  68827. evt.preventDefault();
  68828. }
  68829. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68830. if (index === -1) {
  68831. return;
  68832. }
  68833. _this._pointerPressed.splice(index, 1);
  68834. if (index != 0) {
  68835. return;
  68836. }
  68837. previousPosition = null;
  68838. _this._offsetX = null;
  68839. _this._offsetY = null;
  68840. }
  68841. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  68842. if (!noPreventDefault) {
  68843. evt.preventDefault();
  68844. }
  68845. if (!previousPosition) {
  68846. return;
  68847. }
  68848. var index = _this._pointerPressed.indexOf(evt.pointerId);
  68849. if (index != 0) {
  68850. return;
  68851. }
  68852. _this._offsetX = evt.clientX - previousPosition.x;
  68853. _this._offsetY = -(evt.clientY - previousPosition.y);
  68854. }
  68855. };
  68856. }
  68857. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  68858. if (this._onLostFocus) {
  68859. element.addEventListener("blur", this._onLostFocus);
  68860. }
  68861. };
  68862. FreeCameraTouchInput.prototype.detachControl = function (element) {
  68863. if (this._pointerInput && element) {
  68864. if (this._observer) {
  68865. this.camera.getScene().onPointerObservable.remove(this._observer);
  68866. this._observer = null;
  68867. }
  68868. if (this._onLostFocus) {
  68869. element.removeEventListener("blur", this._onLostFocus);
  68870. this._onLostFocus = null;
  68871. }
  68872. this._pointerPressed = [];
  68873. this._offsetX = null;
  68874. this._offsetY = null;
  68875. }
  68876. };
  68877. FreeCameraTouchInput.prototype.checkInputs = function () {
  68878. if (this._offsetX && this._offsetY) {
  68879. var camera = this.camera;
  68880. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  68881. if (this._pointerPressed.length > 1) {
  68882. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  68883. }
  68884. else {
  68885. var speed = camera._computeLocalCameraSpeed();
  68886. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  68887. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  68888. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  68889. }
  68890. }
  68891. };
  68892. FreeCameraTouchInput.prototype.getClassName = function () {
  68893. return "FreeCameraTouchInput";
  68894. };
  68895. FreeCameraTouchInput.prototype.getSimpleName = function () {
  68896. return "touch";
  68897. };
  68898. __decorate([
  68899. BABYLON.serialize()
  68900. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  68901. __decorate([
  68902. BABYLON.serialize()
  68903. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  68904. return FreeCameraTouchInput;
  68905. }());
  68906. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  68907. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  68908. })(BABYLON || (BABYLON = {}));
  68909. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  68910. var BABYLON;
  68911. (function (BABYLON) {
  68912. // We're mainly based on the logic defined into the FreeCamera code
  68913. var TouchCamera = /** @class */ (function (_super) {
  68914. __extends(TouchCamera, _super);
  68915. //-- end properties for backward compatibility for inputs
  68916. function TouchCamera(name, position, scene) {
  68917. var _this = _super.call(this, name, position, scene) || this;
  68918. _this.inputs.addTouch();
  68919. _this._setupInputs();
  68920. return _this;
  68921. }
  68922. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  68923. //-- Begin properties for backward compatibility for inputs
  68924. get: function () {
  68925. var touch = this.inputs.attached["touch"];
  68926. if (touch)
  68927. return touch.touchAngularSensibility;
  68928. return 0;
  68929. },
  68930. set: function (value) {
  68931. var touch = this.inputs.attached["touch"];
  68932. if (touch)
  68933. touch.touchAngularSensibility = value;
  68934. },
  68935. enumerable: true,
  68936. configurable: true
  68937. });
  68938. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  68939. get: function () {
  68940. var touch = this.inputs.attached["touch"];
  68941. if (touch)
  68942. return touch.touchMoveSensibility;
  68943. return 0;
  68944. },
  68945. set: function (value) {
  68946. var touch = this.inputs.attached["touch"];
  68947. if (touch)
  68948. touch.touchMoveSensibility = value;
  68949. },
  68950. enumerable: true,
  68951. configurable: true
  68952. });
  68953. TouchCamera.prototype.getClassName = function () {
  68954. return "TouchCamera";
  68955. };
  68956. TouchCamera.prototype._setupInputs = function () {
  68957. var mouse = this.inputs.attached["mouse"];
  68958. if (mouse) {
  68959. mouse.touchEnabled = false;
  68960. }
  68961. };
  68962. return TouchCamera;
  68963. }(BABYLON.FreeCamera));
  68964. BABYLON.TouchCamera = TouchCamera;
  68965. })(BABYLON || (BABYLON = {}));
  68966. //# sourceMappingURL=babylon.touchCamera.js.map
  68967. var BABYLON;
  68968. (function (BABYLON) {
  68969. var ProceduralTexture = /** @class */ (function (_super) {
  68970. __extends(ProceduralTexture, _super);
  68971. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  68972. if (fallbackTexture === void 0) { fallbackTexture = null; }
  68973. if (generateMipMaps === void 0) { generateMipMaps = true; }
  68974. if (isCube === void 0) { isCube = false; }
  68975. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  68976. _this.isCube = isCube;
  68977. _this.isEnabled = true;
  68978. _this._currentRefreshId = -1;
  68979. _this._refreshRate = 1;
  68980. _this._vertexBuffers = {};
  68981. _this._uniforms = new Array();
  68982. _this._samplers = new Array();
  68983. _this._textures = {};
  68984. _this._floats = {};
  68985. _this._floatsArrays = {};
  68986. _this._colors3 = {};
  68987. _this._colors4 = {};
  68988. _this._vectors2 = {};
  68989. _this._vectors3 = {};
  68990. _this._matrices = {};
  68991. _this._fallbackTextureUsed = false;
  68992. scene.proceduralTextures.push(_this);
  68993. _this._engine = scene.getEngine();
  68994. _this.name = name;
  68995. _this.isRenderTarget = true;
  68996. _this._size = size;
  68997. _this._generateMipMaps = generateMipMaps;
  68998. _this.setFragment(fragment);
  68999. _this._fallbackTexture = fallbackTexture;
  69000. if (isCube) {
  69001. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69002. _this.setFloat("face", 0);
  69003. }
  69004. else {
  69005. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69006. }
  69007. // VBO
  69008. var vertices = [];
  69009. vertices.push(1, 1);
  69010. vertices.push(-1, 1);
  69011. vertices.push(-1, -1);
  69012. vertices.push(1, -1);
  69013. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69014. _this._createIndexBuffer();
  69015. return _this;
  69016. }
  69017. ProceduralTexture.prototype._createIndexBuffer = function () {
  69018. var engine = this._engine;
  69019. // Indices
  69020. var indices = [];
  69021. indices.push(0);
  69022. indices.push(1);
  69023. indices.push(2);
  69024. indices.push(0);
  69025. indices.push(2);
  69026. indices.push(3);
  69027. this._indexBuffer = engine.createIndexBuffer(indices);
  69028. };
  69029. ProceduralTexture.prototype._rebuild = function () {
  69030. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69031. if (vb) {
  69032. vb._rebuild();
  69033. }
  69034. this._createIndexBuffer();
  69035. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69036. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69037. }
  69038. };
  69039. ProceduralTexture.prototype.reset = function () {
  69040. if (this._effect === undefined) {
  69041. return;
  69042. }
  69043. var engine = this._engine;
  69044. engine._releaseEffect(this._effect);
  69045. };
  69046. ProceduralTexture.prototype.isReady = function () {
  69047. var _this = this;
  69048. var engine = this._engine;
  69049. var shaders;
  69050. if (!this._fragment) {
  69051. return false;
  69052. }
  69053. if (this._fallbackTextureUsed) {
  69054. return true;
  69055. }
  69056. if (this._fragment.fragmentElement !== undefined) {
  69057. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69058. }
  69059. else {
  69060. shaders = { vertex: "procedural", fragment: this._fragment };
  69061. }
  69062. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69063. _this.releaseInternalTexture();
  69064. if (_this._fallbackTexture) {
  69065. _this._texture = _this._fallbackTexture._texture;
  69066. if (_this._texture) {
  69067. _this._texture.incrementReferences();
  69068. }
  69069. }
  69070. _this._fallbackTextureUsed = true;
  69071. });
  69072. return this._effect.isReady();
  69073. };
  69074. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69075. this._currentRefreshId = -1;
  69076. };
  69077. ProceduralTexture.prototype.setFragment = function (fragment) {
  69078. this._fragment = fragment;
  69079. };
  69080. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69081. get: function () {
  69082. return this._refreshRate;
  69083. },
  69084. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69085. set: function (value) {
  69086. this._refreshRate = value;
  69087. this.resetRefreshCounter();
  69088. },
  69089. enumerable: true,
  69090. configurable: true
  69091. });
  69092. ProceduralTexture.prototype._shouldRender = function () {
  69093. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69094. return false;
  69095. }
  69096. if (this._fallbackTextureUsed) {
  69097. return false;
  69098. }
  69099. if (this._currentRefreshId === -1) { // At least render once
  69100. this._currentRefreshId = 1;
  69101. return true;
  69102. }
  69103. if (this.refreshRate === this._currentRefreshId) {
  69104. this._currentRefreshId = 1;
  69105. return true;
  69106. }
  69107. this._currentRefreshId++;
  69108. return false;
  69109. };
  69110. ProceduralTexture.prototype.getRenderSize = function () {
  69111. return this._size;
  69112. };
  69113. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69114. if (this._fallbackTextureUsed) {
  69115. return;
  69116. }
  69117. this.releaseInternalTexture();
  69118. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69119. };
  69120. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69121. if (this._uniforms.indexOf(uniformName) === -1) {
  69122. this._uniforms.push(uniformName);
  69123. }
  69124. };
  69125. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69126. if (this._samplers.indexOf(name) === -1) {
  69127. this._samplers.push(name);
  69128. }
  69129. this._textures[name] = texture;
  69130. return this;
  69131. };
  69132. ProceduralTexture.prototype.setFloat = function (name, value) {
  69133. this._checkUniform(name);
  69134. this._floats[name] = value;
  69135. return this;
  69136. };
  69137. ProceduralTexture.prototype.setFloats = function (name, value) {
  69138. this._checkUniform(name);
  69139. this._floatsArrays[name] = value;
  69140. return this;
  69141. };
  69142. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69143. this._checkUniform(name);
  69144. this._colors3[name] = value;
  69145. return this;
  69146. };
  69147. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69148. this._checkUniform(name);
  69149. this._colors4[name] = value;
  69150. return this;
  69151. };
  69152. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69153. this._checkUniform(name);
  69154. this._vectors2[name] = value;
  69155. return this;
  69156. };
  69157. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69158. this._checkUniform(name);
  69159. this._vectors3[name] = value;
  69160. return this;
  69161. };
  69162. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69163. this._checkUniform(name);
  69164. this._matrices[name] = value;
  69165. return this;
  69166. };
  69167. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69168. var scene = this.getScene();
  69169. if (!scene) {
  69170. return;
  69171. }
  69172. var engine = this._engine;
  69173. // Render
  69174. engine.enableEffect(this._effect);
  69175. engine.setState(false);
  69176. // Texture
  69177. for (var name in this._textures) {
  69178. this._effect.setTexture(name, this._textures[name]);
  69179. }
  69180. // Float
  69181. for (name in this._floats) {
  69182. this._effect.setFloat(name, this._floats[name]);
  69183. }
  69184. // Floats
  69185. for (name in this._floatsArrays) {
  69186. this._effect.setArray(name, this._floatsArrays[name]);
  69187. }
  69188. // Color3
  69189. for (name in this._colors3) {
  69190. this._effect.setColor3(name, this._colors3[name]);
  69191. }
  69192. // Color4
  69193. for (name in this._colors4) {
  69194. var color = this._colors4[name];
  69195. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69196. }
  69197. // Vector2
  69198. for (name in this._vectors2) {
  69199. this._effect.setVector2(name, this._vectors2[name]);
  69200. }
  69201. // Vector3
  69202. for (name in this._vectors3) {
  69203. this._effect.setVector3(name, this._vectors3[name]);
  69204. }
  69205. // Matrix
  69206. for (name in this._matrices) {
  69207. this._effect.setMatrix(name, this._matrices[name]);
  69208. }
  69209. if (!this._texture) {
  69210. return;
  69211. }
  69212. if (this.isCube) {
  69213. for (var face = 0; face < 6; face++) {
  69214. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69215. // VBOs
  69216. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69217. this._effect.setFloat("face", face);
  69218. // Clear
  69219. engine.clear(scene.clearColor, true, true, true);
  69220. // Draw order
  69221. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69222. // Mipmaps
  69223. if (face === 5) {
  69224. engine.generateMipMapsForCubemap(this._texture);
  69225. }
  69226. }
  69227. }
  69228. else {
  69229. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69230. // VBOs
  69231. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69232. // Clear
  69233. engine.clear(scene.clearColor, true, true, true);
  69234. // Draw order
  69235. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69236. }
  69237. // Unbind
  69238. engine.unBindFramebuffer(this._texture, this.isCube);
  69239. if (this.onGenerated) {
  69240. this.onGenerated();
  69241. }
  69242. };
  69243. ProceduralTexture.prototype.clone = function () {
  69244. var textureSize = this.getSize();
  69245. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69246. // Base texture
  69247. newTexture.hasAlpha = this.hasAlpha;
  69248. newTexture.level = this.level;
  69249. // RenderTarget Texture
  69250. newTexture.coordinatesMode = this.coordinatesMode;
  69251. return newTexture;
  69252. };
  69253. ProceduralTexture.prototype.dispose = function () {
  69254. var scene = this.getScene();
  69255. if (!scene) {
  69256. return;
  69257. }
  69258. var index = scene.proceduralTextures.indexOf(this);
  69259. if (index >= 0) {
  69260. scene.proceduralTextures.splice(index, 1);
  69261. }
  69262. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69263. if (vertexBuffer) {
  69264. vertexBuffer.dispose();
  69265. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69266. }
  69267. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69268. this._indexBuffer = null;
  69269. }
  69270. _super.prototype.dispose.call(this);
  69271. };
  69272. return ProceduralTexture;
  69273. }(BABYLON.Texture));
  69274. BABYLON.ProceduralTexture = ProceduralTexture;
  69275. })(BABYLON || (BABYLON = {}));
  69276. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69277. var BABYLON;
  69278. (function (BABYLON) {
  69279. var CustomProceduralTexture = /** @class */ (function (_super) {
  69280. __extends(CustomProceduralTexture, _super);
  69281. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69282. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69283. _this._animate = true;
  69284. _this._time = 0;
  69285. _this._texturePath = texturePath;
  69286. //Try to load json
  69287. _this.loadJson(texturePath);
  69288. _this.refreshRate = 1;
  69289. return _this;
  69290. }
  69291. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69292. var _this = this;
  69293. var noConfigFile = function () {
  69294. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69295. try {
  69296. _this.setFragment(_this._texturePath);
  69297. }
  69298. catch (ex) {
  69299. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69300. }
  69301. };
  69302. var configFileUrl = jsonUrl + "/config.json";
  69303. var xhr = new XMLHttpRequest();
  69304. xhr.open("GET", configFileUrl, true);
  69305. xhr.addEventListener("load", function () {
  69306. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69307. try {
  69308. _this._config = JSON.parse(xhr.response);
  69309. _this.updateShaderUniforms();
  69310. _this.updateTextures();
  69311. _this.setFragment(_this._texturePath + "/custom");
  69312. _this._animate = _this._config.animate;
  69313. _this.refreshRate = _this._config.refreshrate;
  69314. }
  69315. catch (ex) {
  69316. noConfigFile();
  69317. }
  69318. }
  69319. else {
  69320. noConfigFile();
  69321. }
  69322. }, false);
  69323. xhr.addEventListener("error", function () {
  69324. noConfigFile();
  69325. }, false);
  69326. try {
  69327. xhr.send();
  69328. }
  69329. catch (ex) {
  69330. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69331. }
  69332. };
  69333. CustomProceduralTexture.prototype.isReady = function () {
  69334. if (!_super.prototype.isReady.call(this)) {
  69335. return false;
  69336. }
  69337. for (var name in this._textures) {
  69338. var texture = this._textures[name];
  69339. if (!texture.isReady()) {
  69340. return false;
  69341. }
  69342. }
  69343. return true;
  69344. };
  69345. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69346. var scene = this.getScene();
  69347. if (this._animate && scene) {
  69348. this._time += scene.getAnimationRatio() * 0.03;
  69349. this.updateShaderUniforms();
  69350. }
  69351. _super.prototype.render.call(this, useCameraPostProcess);
  69352. };
  69353. CustomProceduralTexture.prototype.updateTextures = function () {
  69354. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69355. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69356. }
  69357. };
  69358. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69359. if (this._config) {
  69360. for (var j = 0; j < this._config.uniforms.length; j++) {
  69361. var uniform = this._config.uniforms[j];
  69362. switch (uniform.type) {
  69363. case "float":
  69364. this.setFloat(uniform.name, uniform.value);
  69365. break;
  69366. case "color3":
  69367. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69368. break;
  69369. case "color4":
  69370. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69371. break;
  69372. case "vector2":
  69373. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69374. break;
  69375. case "vector3":
  69376. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69377. break;
  69378. }
  69379. }
  69380. }
  69381. this.setFloat("time", this._time);
  69382. };
  69383. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69384. get: function () {
  69385. return this._animate;
  69386. },
  69387. set: function (value) {
  69388. this._animate = value;
  69389. },
  69390. enumerable: true,
  69391. configurable: true
  69392. });
  69393. return CustomProceduralTexture;
  69394. }(BABYLON.ProceduralTexture));
  69395. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69396. })(BABYLON || (BABYLON = {}));
  69397. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69398. var BABYLON;
  69399. (function (BABYLON) {
  69400. var FreeCameraGamepadInput = /** @class */ (function () {
  69401. function FreeCameraGamepadInput() {
  69402. this.gamepadAngularSensibility = 200;
  69403. this.gamepadMoveSensibility = 40;
  69404. // private members
  69405. this._cameraTransform = BABYLON.Matrix.Identity();
  69406. this._deltaTransform = BABYLON.Vector3.Zero();
  69407. this._vector3 = BABYLON.Vector3.Zero();
  69408. this._vector2 = BABYLON.Vector2.Zero();
  69409. }
  69410. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69411. var _this = this;
  69412. var manager = this.camera.getScene().gamepadManager;
  69413. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69414. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69415. // prioritize XBOX gamepads.
  69416. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69417. _this.gamepad = gamepad;
  69418. }
  69419. }
  69420. });
  69421. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69422. if (_this.gamepad === gamepad) {
  69423. _this.gamepad = null;
  69424. }
  69425. });
  69426. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69427. };
  69428. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69429. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69430. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69431. this.gamepad = null;
  69432. };
  69433. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69434. if (this.gamepad && this.gamepad.leftStick) {
  69435. var camera = this.camera;
  69436. var LSValues = this.gamepad.leftStick;
  69437. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69438. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69439. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69440. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69441. var RSValues = this.gamepad.rightStick;
  69442. if (RSValues) {
  69443. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69444. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69445. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69446. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69447. }
  69448. else {
  69449. RSValues = { x: 0, y: 0 };
  69450. }
  69451. if (!camera.rotationQuaternion) {
  69452. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69453. }
  69454. else {
  69455. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69456. }
  69457. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69458. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69459. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69460. camera.cameraDirection.addInPlace(this._deltaTransform);
  69461. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69462. camera.cameraRotation.addInPlace(this._vector2);
  69463. }
  69464. };
  69465. FreeCameraGamepadInput.prototype.getClassName = function () {
  69466. return "FreeCameraGamepadInput";
  69467. };
  69468. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69469. return "gamepad";
  69470. };
  69471. __decorate([
  69472. BABYLON.serialize()
  69473. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69474. __decorate([
  69475. BABYLON.serialize()
  69476. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69477. return FreeCameraGamepadInput;
  69478. }());
  69479. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69480. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69481. })(BABYLON || (BABYLON = {}));
  69482. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69483. var BABYLON;
  69484. (function (BABYLON) {
  69485. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69486. function ArcRotateCameraGamepadInput() {
  69487. this.gamepadRotationSensibility = 80;
  69488. this.gamepadMoveSensibility = 40;
  69489. }
  69490. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69491. var _this = this;
  69492. var manager = this.camera.getScene().gamepadManager;
  69493. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69494. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69495. // prioritize XBOX gamepads.
  69496. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69497. _this.gamepad = gamepad;
  69498. }
  69499. }
  69500. });
  69501. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69502. if (_this.gamepad === gamepad) {
  69503. _this.gamepad = null;
  69504. }
  69505. });
  69506. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69507. };
  69508. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  69509. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69510. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69511. this.gamepad = null;
  69512. };
  69513. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  69514. if (this.gamepad) {
  69515. var camera = this.camera;
  69516. var RSValues = this.gamepad.rightStick;
  69517. if (RSValues) {
  69518. if (RSValues.x != 0) {
  69519. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  69520. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  69521. camera.inertialAlphaOffset += normalizedRX;
  69522. }
  69523. }
  69524. if (RSValues.y != 0) {
  69525. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  69526. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  69527. camera.inertialBetaOffset += normalizedRY;
  69528. }
  69529. }
  69530. }
  69531. var LSValues = this.gamepad.leftStick;
  69532. if (LSValues && LSValues.y != 0) {
  69533. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69534. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  69535. this.camera.inertialRadiusOffset -= normalizedLY;
  69536. }
  69537. }
  69538. }
  69539. };
  69540. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  69541. return "ArcRotateCameraGamepadInput";
  69542. };
  69543. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  69544. return "gamepad";
  69545. };
  69546. __decorate([
  69547. BABYLON.serialize()
  69548. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  69549. __decorate([
  69550. BABYLON.serialize()
  69551. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69552. return ArcRotateCameraGamepadInput;
  69553. }());
  69554. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  69555. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  69556. })(BABYLON || (BABYLON = {}));
  69557. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  69558. var BABYLON;
  69559. (function (BABYLON) {
  69560. var GamepadManager = /** @class */ (function () {
  69561. function GamepadManager(_scene) {
  69562. var _this = this;
  69563. this._scene = _scene;
  69564. this._babylonGamepads = [];
  69565. this._oneGamepadConnected = false;
  69566. this._isMonitoring = false;
  69567. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  69568. if (!BABYLON.Tools.IsWindowObjectExist()) {
  69569. this._gamepadEventSupported = false;
  69570. }
  69571. else {
  69572. this._gamepadEventSupported = 'GamepadEvent' in window;
  69573. this._gamepadSupport = (navigator.getGamepads ||
  69574. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  69575. }
  69576. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  69577. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  69578. for (var i in _this._babylonGamepads) {
  69579. var gamepad = _this._babylonGamepads[i];
  69580. if (gamepad && gamepad._isConnected) {
  69581. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  69582. }
  69583. }
  69584. });
  69585. this._onGamepadConnectedEvent = function (evt) {
  69586. var gamepad = evt.gamepad;
  69587. if (gamepad.index in _this._babylonGamepads) {
  69588. if (_this._babylonGamepads[gamepad.index].isConnected) {
  69589. return;
  69590. }
  69591. }
  69592. var newGamepad;
  69593. if (_this._babylonGamepads[gamepad.index]) {
  69594. newGamepad = _this._babylonGamepads[gamepad.index];
  69595. newGamepad.browserGamepad = gamepad;
  69596. newGamepad._isConnected = true;
  69597. }
  69598. else {
  69599. newGamepad = _this._addNewGamepad(gamepad);
  69600. }
  69601. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69602. _this._startMonitoringGamepads();
  69603. };
  69604. this._onGamepadDisconnectedEvent = function (evt) {
  69605. var gamepad = evt.gamepad;
  69606. // Remove the gamepad from the list of gamepads to monitor.
  69607. for (var i in _this._babylonGamepads) {
  69608. if (_this._babylonGamepads[i].index === gamepad.index) {
  69609. var disconnectedGamepad = _this._babylonGamepads[i];
  69610. disconnectedGamepad._isConnected = false;
  69611. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  69612. break;
  69613. }
  69614. }
  69615. };
  69616. if (this._gamepadSupport) {
  69617. //first add already-connected gamepads
  69618. this._updateGamepadObjects();
  69619. if (this._babylonGamepads.length) {
  69620. this._startMonitoringGamepads();
  69621. }
  69622. // Checking if the gamepad connected event is supported (like in Firefox)
  69623. if (this._gamepadEventSupported) {
  69624. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  69625. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  69626. }
  69627. else {
  69628. this._startMonitoringGamepads();
  69629. }
  69630. }
  69631. }
  69632. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  69633. get: function () {
  69634. return this._babylonGamepads;
  69635. },
  69636. enumerable: true,
  69637. configurable: true
  69638. });
  69639. GamepadManager.prototype.getGamepadByType = function (type) {
  69640. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  69641. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  69642. var gamepad = _a[_i];
  69643. if (gamepad && gamepad.type === type) {
  69644. return gamepad;
  69645. }
  69646. }
  69647. return null;
  69648. };
  69649. GamepadManager.prototype.dispose = function () {
  69650. if (this._gamepadEventSupported) {
  69651. if (this._onGamepadConnectedEvent) {
  69652. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  69653. }
  69654. if (this._onGamepadDisconnectedEvent) {
  69655. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  69656. }
  69657. this._onGamepadConnectedEvent = null;
  69658. this._onGamepadDisconnectedEvent = null;
  69659. }
  69660. this._babylonGamepads.forEach(function (gamepad) {
  69661. gamepad.dispose();
  69662. });
  69663. this.onGamepadConnectedObservable.clear();
  69664. this.onGamepadDisconnectedObservable.clear();
  69665. this._oneGamepadConnected = false;
  69666. this._stopMonitoringGamepads();
  69667. this._babylonGamepads = [];
  69668. };
  69669. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  69670. if (!this._oneGamepadConnected) {
  69671. this._oneGamepadConnected = true;
  69672. }
  69673. var newGamepad;
  69674. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  69675. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  69676. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  69677. }
  69678. // if pose is supported, use the (WebVR) pose enabled controller
  69679. else if (gamepad.pose) {
  69680. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  69681. }
  69682. else {
  69683. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  69684. }
  69685. this._babylonGamepads[newGamepad.index] = newGamepad;
  69686. return newGamepad;
  69687. };
  69688. GamepadManager.prototype._startMonitoringGamepads = function () {
  69689. if (!this._isMonitoring) {
  69690. this._isMonitoring = true;
  69691. //back-comp
  69692. if (!this._scene) {
  69693. this._checkGamepadsStatus();
  69694. }
  69695. }
  69696. };
  69697. GamepadManager.prototype._stopMonitoringGamepads = function () {
  69698. this._isMonitoring = false;
  69699. };
  69700. GamepadManager.prototype._checkGamepadsStatus = function () {
  69701. var _this = this;
  69702. // Hack to be compatible Chrome
  69703. this._updateGamepadObjects();
  69704. for (var i in this._babylonGamepads) {
  69705. var gamepad = this._babylonGamepads[i];
  69706. if (!gamepad || !gamepad.isConnected) {
  69707. continue;
  69708. }
  69709. gamepad.update();
  69710. }
  69711. if (this._isMonitoring && !this._scene) {
  69712. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  69713. }
  69714. };
  69715. // This function is called only on Chrome, which does not properly support
  69716. // connection/disconnection events and forces you to recopy again the gamepad object
  69717. GamepadManager.prototype._updateGamepadObjects = function () {
  69718. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  69719. for (var i = 0; i < gamepads.length; i++) {
  69720. var gamepad = gamepads[i];
  69721. if (gamepad) {
  69722. if (!this._babylonGamepads[gamepad.index]) {
  69723. var newGamepad = this._addNewGamepad(gamepad);
  69724. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  69725. }
  69726. else {
  69727. // Forced to copy again this object for Chrome for unknown reason
  69728. this._babylonGamepads[i].browserGamepad = gamepad;
  69729. if (!this._babylonGamepads[i].isConnected) {
  69730. this._babylonGamepads[i]._isConnected = true;
  69731. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  69732. }
  69733. }
  69734. }
  69735. }
  69736. };
  69737. return GamepadManager;
  69738. }());
  69739. BABYLON.GamepadManager = GamepadManager;
  69740. })(BABYLON || (BABYLON = {}));
  69741. //# sourceMappingURL=babylon.gamepadManager.js.map
  69742. var BABYLON;
  69743. (function (BABYLON) {
  69744. var StickValues = /** @class */ (function () {
  69745. function StickValues(x, y) {
  69746. this.x = x;
  69747. this.y = y;
  69748. }
  69749. return StickValues;
  69750. }());
  69751. BABYLON.StickValues = StickValues;
  69752. var Gamepad = /** @class */ (function () {
  69753. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  69754. if (leftStickX === void 0) { leftStickX = 0; }
  69755. if (leftStickY === void 0) { leftStickY = 1; }
  69756. if (rightStickX === void 0) { rightStickX = 2; }
  69757. if (rightStickY === void 0) { rightStickY = 3; }
  69758. this.id = id;
  69759. this.index = index;
  69760. this.browserGamepad = browserGamepad;
  69761. this._isConnected = true;
  69762. this._invertLeftStickY = false;
  69763. this.type = Gamepad.GAMEPAD;
  69764. this._leftStickAxisX = leftStickX;
  69765. this._leftStickAxisY = leftStickY;
  69766. this._rightStickAxisX = rightStickX;
  69767. this._rightStickAxisY = rightStickY;
  69768. if (this.browserGamepad.axes.length >= 2) {
  69769. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69770. }
  69771. if (this.browserGamepad.axes.length >= 4) {
  69772. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69773. }
  69774. }
  69775. Object.defineProperty(Gamepad.prototype, "isConnected", {
  69776. get: function () {
  69777. return this._isConnected;
  69778. },
  69779. enumerable: true,
  69780. configurable: true
  69781. });
  69782. Gamepad.prototype.onleftstickchanged = function (callback) {
  69783. this._onleftstickchanged = callback;
  69784. };
  69785. Gamepad.prototype.onrightstickchanged = function (callback) {
  69786. this._onrightstickchanged = callback;
  69787. };
  69788. Object.defineProperty(Gamepad.prototype, "leftStick", {
  69789. get: function () {
  69790. return this._leftStick;
  69791. },
  69792. set: function (newValues) {
  69793. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  69794. this._onleftstickchanged(newValues);
  69795. }
  69796. this._leftStick = newValues;
  69797. },
  69798. enumerable: true,
  69799. configurable: true
  69800. });
  69801. Object.defineProperty(Gamepad.prototype, "rightStick", {
  69802. get: function () {
  69803. return this._rightStick;
  69804. },
  69805. set: function (newValues) {
  69806. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  69807. this._onrightstickchanged(newValues);
  69808. }
  69809. this._rightStick = newValues;
  69810. },
  69811. enumerable: true,
  69812. configurable: true
  69813. });
  69814. Gamepad.prototype.update = function () {
  69815. if (this._leftStick) {
  69816. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  69817. if (this._invertLeftStickY) {
  69818. this.leftStick.y *= -1;
  69819. }
  69820. }
  69821. if (this._rightStick) {
  69822. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  69823. }
  69824. };
  69825. Gamepad.prototype.dispose = function () {
  69826. };
  69827. Gamepad.GAMEPAD = 0;
  69828. Gamepad.GENERIC = 1;
  69829. Gamepad.XBOX = 2;
  69830. Gamepad.POSE_ENABLED = 3;
  69831. return Gamepad;
  69832. }());
  69833. BABYLON.Gamepad = Gamepad;
  69834. var GenericPad = /** @class */ (function (_super) {
  69835. __extends(GenericPad, _super);
  69836. function GenericPad(id, index, browserGamepad) {
  69837. var _this = _super.call(this, id, index, browserGamepad) || this;
  69838. _this.onButtonDownObservable = new BABYLON.Observable();
  69839. _this.onButtonUpObservable = new BABYLON.Observable();
  69840. _this.type = Gamepad.GENERIC;
  69841. _this._buttons = new Array(browserGamepad.buttons.length);
  69842. return _this;
  69843. }
  69844. GenericPad.prototype.onbuttondown = function (callback) {
  69845. this._onbuttondown = callback;
  69846. };
  69847. GenericPad.prototype.onbuttonup = function (callback) {
  69848. this._onbuttonup = callback;
  69849. };
  69850. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  69851. if (newValue !== currentValue) {
  69852. if (newValue === 1) {
  69853. if (this._onbuttondown) {
  69854. this._onbuttondown(buttonIndex);
  69855. }
  69856. this.onButtonDownObservable.notifyObservers(buttonIndex);
  69857. }
  69858. if (newValue === 0) {
  69859. if (this._onbuttonup) {
  69860. this._onbuttonup(buttonIndex);
  69861. }
  69862. this.onButtonUpObservable.notifyObservers(buttonIndex);
  69863. }
  69864. }
  69865. return newValue;
  69866. };
  69867. GenericPad.prototype.update = function () {
  69868. _super.prototype.update.call(this);
  69869. for (var index = 0; index < this._buttons.length; index++) {
  69870. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  69871. }
  69872. };
  69873. GenericPad.prototype.dispose = function () {
  69874. _super.prototype.dispose.call(this);
  69875. this.onButtonDownObservable.clear();
  69876. this.onButtonUpObservable.clear();
  69877. };
  69878. return GenericPad;
  69879. }(Gamepad));
  69880. BABYLON.GenericPad = GenericPad;
  69881. })(BABYLON || (BABYLON = {}));
  69882. //# sourceMappingURL=babylon.gamepad.js.map
  69883. var BABYLON;
  69884. (function (BABYLON) {
  69885. /**
  69886. * Defines supported buttons for XBox360 compatible gamepads
  69887. */
  69888. var Xbox360Button;
  69889. (function (Xbox360Button) {
  69890. /** A */
  69891. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  69892. /** B */
  69893. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  69894. /** X */
  69895. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  69896. /** Y */
  69897. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  69898. /** Start */
  69899. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  69900. /** Back */
  69901. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  69902. /** Left button */
  69903. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  69904. /** Right button */
  69905. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  69906. /** Left stick */
  69907. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  69908. /** Right stick */
  69909. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  69910. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  69911. /** Defines values for XBox360 DPad */
  69912. var Xbox360Dpad;
  69913. (function (Xbox360Dpad) {
  69914. /** Up */
  69915. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  69916. /** Down */
  69917. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  69918. /** Left */
  69919. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  69920. /** Right */
  69921. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  69922. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  69923. /**
  69924. * Defines a XBox360 gamepad
  69925. */
  69926. var Xbox360Pad = /** @class */ (function (_super) {
  69927. __extends(Xbox360Pad, _super);
  69928. /**
  69929. * Creates a new XBox360 gamepad object
  69930. * @param id defines the id of this gamepad
  69931. * @param index defines its index
  69932. * @param gamepad defines the internal HTML gamepad object
  69933. * @param xboxOne defines if it is a XBox One gamepad
  69934. */
  69935. function Xbox360Pad(id, index, gamepad, xboxOne) {
  69936. if (xboxOne === void 0) { xboxOne = false; }
  69937. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  69938. _this._leftTrigger = 0;
  69939. _this._rightTrigger = 0;
  69940. /** Observable raised when a button is pressed */
  69941. _this.onButtonDownObservable = new BABYLON.Observable();
  69942. /** Observable raised when a button is released */
  69943. _this.onButtonUpObservable = new BABYLON.Observable();
  69944. /** Observable raised when a pad is pressed */
  69945. _this.onPadDownObservable = new BABYLON.Observable();
  69946. /** Observable raised when a pad is released */
  69947. _this.onPadUpObservable = new BABYLON.Observable();
  69948. _this._buttonA = 0;
  69949. _this._buttonB = 0;
  69950. _this._buttonX = 0;
  69951. _this._buttonY = 0;
  69952. _this._buttonBack = 0;
  69953. _this._buttonStart = 0;
  69954. _this._buttonLB = 0;
  69955. _this._buttonRB = 0;
  69956. _this._buttonLeftStick = 0;
  69957. _this._buttonRightStick = 0;
  69958. _this._dPadUp = 0;
  69959. _this._dPadDown = 0;
  69960. _this._dPadLeft = 0;
  69961. _this._dPadRight = 0;
  69962. _this._isXboxOnePad = false;
  69963. _this.type = BABYLON.Gamepad.XBOX;
  69964. _this._isXboxOnePad = xboxOne;
  69965. return _this;
  69966. }
  69967. /**
  69968. * Defines the callback to call when left trigger is pressed
  69969. * @param callback defines the callback to use
  69970. */
  69971. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  69972. this._onlefttriggerchanged = callback;
  69973. };
  69974. /**
  69975. * Defines the callback to call when right trigger is pressed
  69976. * @param callback defines the callback to use
  69977. */
  69978. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  69979. this._onrighttriggerchanged = callback;
  69980. };
  69981. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  69982. /**
  69983. * Gets or sets left trigger value
  69984. */
  69985. get: function () {
  69986. return this._leftTrigger;
  69987. },
  69988. set: function (newValue) {
  69989. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  69990. this._onlefttriggerchanged(newValue);
  69991. }
  69992. this._leftTrigger = newValue;
  69993. },
  69994. enumerable: true,
  69995. configurable: true
  69996. });
  69997. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  69998. /**
  69999. * Gets or sets right trigger value
  70000. */
  70001. get: function () {
  70002. return this._rightTrigger;
  70003. },
  70004. set: function (newValue) {
  70005. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70006. this._onrighttriggerchanged(newValue);
  70007. }
  70008. this._rightTrigger = newValue;
  70009. },
  70010. enumerable: true,
  70011. configurable: true
  70012. });
  70013. /**
  70014. * Defines the callback to call when a button is pressed
  70015. * @param callback defines the callback to use
  70016. */
  70017. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70018. this._onbuttondown = callback;
  70019. };
  70020. /**
  70021. * Defines the callback to call when a button is released
  70022. * @param callback defines the callback to use
  70023. */
  70024. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70025. this._onbuttonup = callback;
  70026. };
  70027. /**
  70028. * Defines the callback to call when a pad is pressed
  70029. * @param callback defines the callback to use
  70030. */
  70031. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70032. this._ondpaddown = callback;
  70033. };
  70034. /**
  70035. * Defines the callback to call when a pad is released
  70036. * @param callback defines the callback to use
  70037. */
  70038. Xbox360Pad.prototype.ondpadup = function (callback) {
  70039. this._ondpadup = callback;
  70040. };
  70041. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70042. if (newValue !== currentValue) {
  70043. if (newValue === 1) {
  70044. if (this._onbuttondown) {
  70045. this._onbuttondown(buttonType);
  70046. }
  70047. this.onButtonDownObservable.notifyObservers(buttonType);
  70048. }
  70049. if (newValue === 0) {
  70050. if (this._onbuttonup) {
  70051. this._onbuttonup(buttonType);
  70052. }
  70053. this.onButtonUpObservable.notifyObservers(buttonType);
  70054. }
  70055. }
  70056. return newValue;
  70057. };
  70058. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70059. if (newValue !== currentValue) {
  70060. if (newValue === 1) {
  70061. if (this._ondpaddown) {
  70062. this._ondpaddown(buttonType);
  70063. }
  70064. this.onPadDownObservable.notifyObservers(buttonType);
  70065. }
  70066. if (newValue === 0) {
  70067. if (this._ondpadup) {
  70068. this._ondpadup(buttonType);
  70069. }
  70070. this.onPadUpObservable.notifyObservers(buttonType);
  70071. }
  70072. }
  70073. return newValue;
  70074. };
  70075. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70076. /** Gets or sets value of A button */
  70077. get: function () {
  70078. return this._buttonA;
  70079. },
  70080. set: function (value) {
  70081. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70082. },
  70083. enumerable: true,
  70084. configurable: true
  70085. });
  70086. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70087. /** Gets or sets value of B button */
  70088. get: function () {
  70089. return this._buttonB;
  70090. },
  70091. set: function (value) {
  70092. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70093. },
  70094. enumerable: true,
  70095. configurable: true
  70096. });
  70097. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70098. /** Gets or sets value of X button */
  70099. get: function () {
  70100. return this._buttonX;
  70101. },
  70102. set: function (value) {
  70103. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70104. },
  70105. enumerable: true,
  70106. configurable: true
  70107. });
  70108. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70109. /** Gets or sets value of Y button */
  70110. get: function () {
  70111. return this._buttonY;
  70112. },
  70113. set: function (value) {
  70114. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70115. },
  70116. enumerable: true,
  70117. configurable: true
  70118. });
  70119. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70120. /** Gets or sets value of Start button */
  70121. get: function () {
  70122. return this._buttonStart;
  70123. },
  70124. set: function (value) {
  70125. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70126. },
  70127. enumerable: true,
  70128. configurable: true
  70129. });
  70130. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70131. /** Gets or sets value of Back button */
  70132. get: function () {
  70133. return this._buttonBack;
  70134. },
  70135. set: function (value) {
  70136. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70137. },
  70138. enumerable: true,
  70139. configurable: true
  70140. });
  70141. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70142. /** Gets or sets value of Left button */
  70143. get: function () {
  70144. return this._buttonLB;
  70145. },
  70146. set: function (value) {
  70147. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70148. },
  70149. enumerable: true,
  70150. configurable: true
  70151. });
  70152. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70153. /** Gets or sets value of Right button */
  70154. get: function () {
  70155. return this._buttonRB;
  70156. },
  70157. set: function (value) {
  70158. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70159. },
  70160. enumerable: true,
  70161. configurable: true
  70162. });
  70163. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70164. /** Gets or sets value of left stick */
  70165. get: function () {
  70166. return this._buttonLeftStick;
  70167. },
  70168. set: function (value) {
  70169. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70170. },
  70171. enumerable: true,
  70172. configurable: true
  70173. });
  70174. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70175. /** Gets or sets value of right stick */
  70176. get: function () {
  70177. return this._buttonRightStick;
  70178. },
  70179. set: function (value) {
  70180. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70181. },
  70182. enumerable: true,
  70183. configurable: true
  70184. });
  70185. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70186. /** Gets or sets value of DPad up */
  70187. get: function () {
  70188. return this._dPadUp;
  70189. },
  70190. set: function (value) {
  70191. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70192. },
  70193. enumerable: true,
  70194. configurable: true
  70195. });
  70196. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70197. /** Gets or sets value of DPad down */
  70198. get: function () {
  70199. return this._dPadDown;
  70200. },
  70201. set: function (value) {
  70202. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70203. },
  70204. enumerable: true,
  70205. configurable: true
  70206. });
  70207. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70208. /** Gets or sets value of DPad left */
  70209. get: function () {
  70210. return this._dPadLeft;
  70211. },
  70212. set: function (value) {
  70213. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70214. },
  70215. enumerable: true,
  70216. configurable: true
  70217. });
  70218. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70219. /** Gets or sets value of DPad right */
  70220. get: function () {
  70221. return this._dPadRight;
  70222. },
  70223. set: function (value) {
  70224. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70225. },
  70226. enumerable: true,
  70227. configurable: true
  70228. });
  70229. /**
  70230. * Force the gamepad to synchronize with device values
  70231. */
  70232. Xbox360Pad.prototype.update = function () {
  70233. _super.prototype.update.call(this);
  70234. if (this._isXboxOnePad) {
  70235. this.buttonA = this.browserGamepad.buttons[0].value;
  70236. this.buttonB = this.browserGamepad.buttons[1].value;
  70237. this.buttonX = this.browserGamepad.buttons[2].value;
  70238. this.buttonY = this.browserGamepad.buttons[3].value;
  70239. this.buttonLB = this.browserGamepad.buttons[4].value;
  70240. this.buttonRB = this.browserGamepad.buttons[5].value;
  70241. this.leftTrigger = this.browserGamepad.axes[2];
  70242. this.rightTrigger = this.browserGamepad.axes[5];
  70243. this.buttonBack = this.browserGamepad.buttons[9].value;
  70244. this.buttonStart = this.browserGamepad.buttons[8].value;
  70245. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70246. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70247. this.dPadUp = this.browserGamepad.buttons[11].value;
  70248. this.dPadDown = this.browserGamepad.buttons[12].value;
  70249. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70250. this.dPadRight = this.browserGamepad.buttons[14].value;
  70251. }
  70252. else {
  70253. this.buttonA = this.browserGamepad.buttons[0].value;
  70254. this.buttonB = this.browserGamepad.buttons[1].value;
  70255. this.buttonX = this.browserGamepad.buttons[2].value;
  70256. this.buttonY = this.browserGamepad.buttons[3].value;
  70257. this.buttonLB = this.browserGamepad.buttons[4].value;
  70258. this.buttonRB = this.browserGamepad.buttons[5].value;
  70259. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70260. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70261. this.buttonBack = this.browserGamepad.buttons[8].value;
  70262. this.buttonStart = this.browserGamepad.buttons[9].value;
  70263. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70264. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70265. this.dPadUp = this.browserGamepad.buttons[12].value;
  70266. this.dPadDown = this.browserGamepad.buttons[13].value;
  70267. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70268. this.dPadRight = this.browserGamepad.buttons[15].value;
  70269. }
  70270. };
  70271. Xbox360Pad.prototype.dispose = function () {
  70272. _super.prototype.dispose.call(this);
  70273. this.onButtonDownObservable.clear();
  70274. this.onButtonUpObservable.clear();
  70275. this.onPadDownObservable.clear();
  70276. this.onPadUpObservable.clear();
  70277. };
  70278. return Xbox360Pad;
  70279. }(BABYLON.Gamepad));
  70280. BABYLON.Xbox360Pad = Xbox360Pad;
  70281. })(BABYLON || (BABYLON = {}));
  70282. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70283. var BABYLON;
  70284. (function (BABYLON) {
  70285. /**
  70286. * Defines the types of pose enabled controllers that are supported
  70287. */
  70288. var PoseEnabledControllerType;
  70289. (function (PoseEnabledControllerType) {
  70290. /**
  70291. * HTC Vive
  70292. */
  70293. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70294. /**
  70295. * Oculus Rift
  70296. */
  70297. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70298. /**
  70299. * Windows mixed reality
  70300. */
  70301. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70302. /**
  70303. * Samsung gear VR
  70304. */
  70305. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70306. /**
  70307. * Google Daydream
  70308. */
  70309. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70310. /**
  70311. * Generic
  70312. */
  70313. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70314. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70315. /**
  70316. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70317. */
  70318. var PoseEnabledControllerHelper = /** @class */ (function () {
  70319. function PoseEnabledControllerHelper() {
  70320. }
  70321. /**
  70322. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70323. * @param vrGamepad the gamepad to initialized
  70324. * @returns a vr controller of the type the gamepad identified as
  70325. */
  70326. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70327. // Oculus Touch
  70328. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70329. return new BABYLON.OculusTouchController(vrGamepad);
  70330. }
  70331. // Windows Mixed Reality controllers
  70332. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70333. return new BABYLON.WindowsMotionController(vrGamepad);
  70334. }
  70335. // HTC Vive
  70336. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70337. return new BABYLON.ViveController(vrGamepad);
  70338. }
  70339. // Samsung/Oculus Gear VR
  70340. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70341. return new BABYLON.GearVRController(vrGamepad);
  70342. }
  70343. // Google Daydream
  70344. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70345. return new BABYLON.DaydreamController(vrGamepad);
  70346. }
  70347. // Generic
  70348. else {
  70349. return new BABYLON.GenericController(vrGamepad);
  70350. }
  70351. };
  70352. return PoseEnabledControllerHelper;
  70353. }());
  70354. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70355. /**
  70356. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70357. */
  70358. var PoseEnabledController = /** @class */ (function (_super) {
  70359. __extends(PoseEnabledController, _super);
  70360. /**
  70361. * Creates a new PoseEnabledController from a gamepad
  70362. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70363. */
  70364. function PoseEnabledController(browserGamepad) {
  70365. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70366. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70367. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70368. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70369. /**
  70370. * The device position in babylon space
  70371. */
  70372. _this.devicePosition = BABYLON.Vector3.Zero();
  70373. /**
  70374. * The device rotation in babylon space
  70375. */
  70376. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70377. /**
  70378. * The scale factor of the device in babylon space
  70379. */
  70380. _this.deviceScaleFactor = 1;
  70381. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70382. /**
  70383. * Internal, matrix used to convert room space to babylon space
  70384. */
  70385. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70386. /**
  70387. * Node to be used when casting a ray from the controller
  70388. */
  70389. _this._pointingPoseNode = null;
  70390. _this._workingMatrix = BABYLON.Matrix.Identity();
  70391. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70392. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70393. _this.position = BABYLON.Vector3.Zero();
  70394. _this.rotationQuaternion = new BABYLON.Quaternion();
  70395. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70396. _this._calculatedRotation = new BABYLON.Quaternion();
  70397. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70398. return _this;
  70399. }
  70400. /**
  70401. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70402. */
  70403. PoseEnabledController.prototype.update = function () {
  70404. _super.prototype.update.call(this);
  70405. var pose = this.browserGamepad.pose;
  70406. this.updateFromDevice(pose);
  70407. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70408. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70409. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70410. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70411. if (this._mesh) {
  70412. this._mesh.position.copyFrom(this.devicePosition);
  70413. if (this._mesh.rotationQuaternion) {
  70414. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70415. }
  70416. }
  70417. };
  70418. /**
  70419. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70420. * @param poseData raw pose fromthe device
  70421. */
  70422. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70423. if (poseData) {
  70424. this.rawPose = poseData;
  70425. if (poseData.position) {
  70426. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70427. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70428. this._deviceRoomPosition.z *= -1;
  70429. }
  70430. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70431. this._calculatedPosition.addInPlace(this.position);
  70432. }
  70433. var pose = this.rawPose;
  70434. if (poseData.orientation && pose.orientation) {
  70435. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70436. if (this._mesh) {
  70437. if (this._mesh.getScene().useRightHandedSystem) {
  70438. this._deviceRoomRotationQuaternion.z *= -1;
  70439. this._deviceRoomRotationQuaternion.w *= -1;
  70440. }
  70441. else {
  70442. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70443. }
  70444. }
  70445. // if the camera is set, rotate to the camera's rotation
  70446. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70447. }
  70448. }
  70449. };
  70450. /**
  70451. * Attaches a mesh to the controller
  70452. * @param mesh the mesh to be attached
  70453. */
  70454. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70455. if (this._mesh) {
  70456. this._mesh.parent = null;
  70457. }
  70458. this._mesh = mesh;
  70459. if (this._poseControlledCamera) {
  70460. this._mesh.parent = this._poseControlledCamera;
  70461. }
  70462. if (!this._mesh.rotationQuaternion) {
  70463. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70464. }
  70465. };
  70466. /**
  70467. * Attaches the controllers mesh to a camera
  70468. * @param camera the camera the mesh should be attached to
  70469. */
  70470. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70471. this._poseControlledCamera = camera;
  70472. if (this._mesh) {
  70473. this._mesh.parent = this._poseControlledCamera;
  70474. }
  70475. };
  70476. /**
  70477. * Disposes of the controller
  70478. */
  70479. PoseEnabledController.prototype.dispose = function () {
  70480. if (this._mesh) {
  70481. this._mesh.dispose();
  70482. }
  70483. this._mesh = null;
  70484. _super.prototype.dispose.call(this);
  70485. };
  70486. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70487. /**
  70488. * The mesh that is attached to the controller
  70489. */
  70490. get: function () {
  70491. return this._mesh;
  70492. },
  70493. enumerable: true,
  70494. configurable: true
  70495. });
  70496. /**
  70497. * Gets the ray of the controller in the direction the controller is pointing
  70498. * @param length the length the resulting ray should be
  70499. * @returns a ray in the direction the controller is pointing
  70500. */
  70501. PoseEnabledController.prototype.getForwardRay = function (length) {
  70502. if (length === void 0) { length = 100; }
  70503. if (!this.mesh) {
  70504. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  70505. }
  70506. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  70507. var origin = m.getTranslation();
  70508. var forward = new BABYLON.Vector3(0, 0, -1);
  70509. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  70510. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  70511. return new BABYLON.Ray(origin, direction, length);
  70512. };
  70513. /**
  70514. * Name of the child mesh that can be used to cast a ray from the controller
  70515. */
  70516. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  70517. return PoseEnabledController;
  70518. }(BABYLON.Gamepad));
  70519. BABYLON.PoseEnabledController = PoseEnabledController;
  70520. })(BABYLON || (BABYLON = {}));
  70521. //# sourceMappingURL=babylon.poseEnabledController.js.map
  70522. var BABYLON;
  70523. (function (BABYLON) {
  70524. /**
  70525. * Defines the WebVRController object that represents controllers tracked in 3D space
  70526. */
  70527. var WebVRController = /** @class */ (function (_super) {
  70528. __extends(WebVRController, _super);
  70529. /**
  70530. * Creates a new WebVRController from a gamepad
  70531. * @param vrGamepad the gamepad that the WebVRController should be created from
  70532. */
  70533. function WebVRController(vrGamepad) {
  70534. var _this = _super.call(this, vrGamepad) || this;
  70535. // Observables
  70536. /**
  70537. * Fired when the trigger state has changed
  70538. */
  70539. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  70540. /**
  70541. * Fired when the main button state has changed
  70542. */
  70543. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  70544. /**
  70545. * Fired when the secondary button state has changed
  70546. */
  70547. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  70548. /**
  70549. * Fired when the pad state has changed
  70550. */
  70551. _this.onPadStateChangedObservable = new BABYLON.Observable();
  70552. /**
  70553. * Fired when controllers stick values have changed
  70554. */
  70555. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  70556. /**
  70557. * X and Y axis corrisponding to the controllers joystick
  70558. */
  70559. _this.pad = { x: 0, y: 0 };
  70560. // avoid GC, store state in a tmp object
  70561. _this._changes = {
  70562. pressChanged: false,
  70563. touchChanged: false,
  70564. valueChanged: false,
  70565. changed: false
  70566. };
  70567. _this._buttons = new Array(vrGamepad.buttons.length);
  70568. _this.hand = vrGamepad.hand;
  70569. return _this;
  70570. }
  70571. /**
  70572. * Fired when a controller button's state has changed
  70573. * @param callback the callback containing the button that was modified
  70574. */
  70575. WebVRController.prototype.onButtonStateChange = function (callback) {
  70576. this._onButtonStateChange = callback;
  70577. };
  70578. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  70579. /**
  70580. * The default controller model for the controller
  70581. */
  70582. get: function () {
  70583. return this._defaultModel;
  70584. },
  70585. enumerable: true,
  70586. configurable: true
  70587. });
  70588. /**
  70589. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  70590. */
  70591. WebVRController.prototype.update = function () {
  70592. _super.prototype.update.call(this);
  70593. for (var index = 0; index < this._buttons.length; index++) {
  70594. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  70595. }
  70596. ;
  70597. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  70598. this.pad.x = this.leftStick.x;
  70599. this.pad.y = this.leftStick.y;
  70600. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  70601. }
  70602. };
  70603. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  70604. if (!newState) {
  70605. newState = {
  70606. pressed: false,
  70607. touched: false,
  70608. value: 0
  70609. };
  70610. }
  70611. if (!currentState) {
  70612. this._buttons[buttonIndex] = {
  70613. pressed: newState.pressed,
  70614. touched: newState.touched,
  70615. value: newState.value
  70616. };
  70617. return;
  70618. }
  70619. this._checkChanges(newState, currentState);
  70620. if (this._changes.changed) {
  70621. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  70622. this._handleButtonChange(buttonIndex, newState, this._changes);
  70623. }
  70624. this._buttons[buttonIndex].pressed = newState.pressed;
  70625. this._buttons[buttonIndex].touched = newState.touched;
  70626. // oculus triggers are never 0, thou not touched.
  70627. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  70628. };
  70629. WebVRController.prototype._checkChanges = function (newState, currentState) {
  70630. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  70631. this._changes.touchChanged = newState.touched !== currentState.touched;
  70632. this._changes.valueChanged = newState.value !== currentState.value;
  70633. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  70634. return this._changes;
  70635. };
  70636. /**
  70637. * Disposes of th webVRCOntroller
  70638. */
  70639. WebVRController.prototype.dispose = function () {
  70640. _super.prototype.dispose.call(this);
  70641. this.onTriggerStateChangedObservable.clear();
  70642. this.onMainButtonStateChangedObservable.clear();
  70643. this.onSecondaryButtonStateChangedObservable.clear();
  70644. this.onPadStateChangedObservable.clear();
  70645. this.onPadValuesChangedObservable.clear();
  70646. };
  70647. return WebVRController;
  70648. }(BABYLON.PoseEnabledController));
  70649. BABYLON.WebVRController = WebVRController;
  70650. })(BABYLON || (BABYLON = {}));
  70651. //# sourceMappingURL=babylon.webVRController.js.map
  70652. var BABYLON;
  70653. (function (BABYLON) {
  70654. /**
  70655. * Oculus Touch Controller
  70656. */
  70657. var OculusTouchController = /** @class */ (function (_super) {
  70658. __extends(OculusTouchController, _super);
  70659. /**
  70660. * Creates a new OculusTouchController from a gamepad
  70661. * @param vrGamepad the gamepad that the controller should be created from
  70662. */
  70663. function OculusTouchController(vrGamepad) {
  70664. var _this = _super.call(this, vrGamepad) || this;
  70665. /**
  70666. * Fired when the secondary trigger on this controller is modified
  70667. */
  70668. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  70669. /**
  70670. * Fired when the thumb rest on this controller is modified
  70671. */
  70672. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  70673. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  70674. return _this;
  70675. }
  70676. /**
  70677. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70678. * @param scene scene in which to add meshes
  70679. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70680. */
  70681. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70682. var _this = this;
  70683. var meshName;
  70684. // Hand
  70685. if (this.hand === 'left') {
  70686. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  70687. }
  70688. else { // Right is the default if no hand is specified
  70689. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  70690. }
  70691. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  70692. /*
  70693. Parent Mesh name: oculus_touch_left
  70694. - body
  70695. - trigger
  70696. - thumbstick
  70697. - grip
  70698. - button_y
  70699. - button_x
  70700. - button_enter
  70701. */
  70702. _this._defaultModel = newMeshes[1];
  70703. _this.attachToMesh(_this._defaultModel);
  70704. if (meshLoaded) {
  70705. meshLoaded(_this._defaultModel);
  70706. }
  70707. });
  70708. };
  70709. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  70710. /**
  70711. * Fired when the A button on this controller is modified
  70712. */
  70713. get: function () {
  70714. if (this.hand === 'right') {
  70715. return this.onMainButtonStateChangedObservable;
  70716. }
  70717. else {
  70718. throw new Error('No A button on left hand');
  70719. }
  70720. },
  70721. enumerable: true,
  70722. configurable: true
  70723. });
  70724. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  70725. /**
  70726. * Fired when the B button on this controller is modified
  70727. */
  70728. get: function () {
  70729. if (this.hand === 'right') {
  70730. return this.onSecondaryButtonStateChangedObservable;
  70731. }
  70732. else {
  70733. throw new Error('No B button on left hand');
  70734. }
  70735. },
  70736. enumerable: true,
  70737. configurable: true
  70738. });
  70739. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  70740. /**
  70741. * Fired when the X button on this controller is modified
  70742. */
  70743. get: function () {
  70744. if (this.hand === 'left') {
  70745. return this.onMainButtonStateChangedObservable;
  70746. }
  70747. else {
  70748. throw new Error('No X button on right hand');
  70749. }
  70750. },
  70751. enumerable: true,
  70752. configurable: true
  70753. });
  70754. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  70755. /**
  70756. * Fired when the Y button on this controller is modified
  70757. */
  70758. get: function () {
  70759. if (this.hand === 'left') {
  70760. return this.onSecondaryButtonStateChangedObservable;
  70761. }
  70762. else {
  70763. throw new Error('No Y button on right hand');
  70764. }
  70765. },
  70766. enumerable: true,
  70767. configurable: true
  70768. });
  70769. /**
  70770. * Called once for each button that changed state since the last frame
  70771. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  70772. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  70773. * 2) secondary trigger (same)
  70774. * 3) A (right) X (left), touch, pressed = value
  70775. * 4) B / Y
  70776. * 5) thumb rest
  70777. * @param buttonIdx Which button index changed
  70778. * @param state New state of the button
  70779. * @param changes Which properties on the state changed since last frame
  70780. */
  70781. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70782. var notifyObject = state; //{ state: state, changes: changes };
  70783. var triggerDirection = this.hand === 'right' ? -1 : 1;
  70784. switch (buttonIdx) {
  70785. case 0:
  70786. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70787. return;
  70788. case 1: // index trigger
  70789. if (this._defaultModel) {
  70790. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  70791. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  70792. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  70793. }
  70794. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70795. return;
  70796. case 2: // secondary trigger
  70797. if (this._defaultModel) {
  70798. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  70799. }
  70800. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  70801. return;
  70802. case 3:
  70803. if (this._defaultModel) {
  70804. if (notifyObject.pressed) {
  70805. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  70806. }
  70807. else {
  70808. (this._defaultModel.getChildren()[1]).position.y = 0;
  70809. }
  70810. }
  70811. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70812. return;
  70813. case 4:
  70814. if (this._defaultModel) {
  70815. if (notifyObject.pressed) {
  70816. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70817. }
  70818. else {
  70819. (this._defaultModel.getChildren()[2]).position.y = 0;
  70820. }
  70821. }
  70822. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70823. return;
  70824. case 5:
  70825. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  70826. return;
  70827. }
  70828. };
  70829. /**
  70830. * Base Url for the controller model.
  70831. */
  70832. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  70833. /**
  70834. * File name for the left controller model.
  70835. */
  70836. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  70837. /**
  70838. * File name for the right controller model.
  70839. */
  70840. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  70841. return OculusTouchController;
  70842. }(BABYLON.WebVRController));
  70843. BABYLON.OculusTouchController = OculusTouchController;
  70844. })(BABYLON || (BABYLON = {}));
  70845. //# sourceMappingURL=babylon.oculusTouchController.js.map
  70846. var BABYLON;
  70847. (function (BABYLON) {
  70848. /**
  70849. * Vive Controller
  70850. */
  70851. var ViveController = /** @class */ (function (_super) {
  70852. __extends(ViveController, _super);
  70853. /**
  70854. * Creates a new ViveController from a gamepad
  70855. * @param vrGamepad the gamepad that the controller should be created from
  70856. */
  70857. function ViveController(vrGamepad) {
  70858. var _this = _super.call(this, vrGamepad) || this;
  70859. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  70860. _this._invertLeftStickY = true;
  70861. return _this;
  70862. }
  70863. /**
  70864. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70865. * @param scene scene in which to add meshes
  70866. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70867. */
  70868. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70869. var _this = this;
  70870. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  70871. /*
  70872. Parent Mesh name: ViveWand
  70873. - body
  70874. - r_gripper
  70875. - l_gripper
  70876. - menu_button
  70877. - system_button
  70878. - trackpad
  70879. - trigger
  70880. - LED
  70881. */
  70882. _this._defaultModel = newMeshes[1];
  70883. _this.attachToMesh(_this._defaultModel);
  70884. if (meshLoaded) {
  70885. meshLoaded(_this._defaultModel);
  70886. }
  70887. });
  70888. };
  70889. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  70890. /**
  70891. * Fired when the left button on this controller is modified
  70892. */
  70893. get: function () {
  70894. return this.onMainButtonStateChangedObservable;
  70895. },
  70896. enumerable: true,
  70897. configurable: true
  70898. });
  70899. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  70900. /**
  70901. * Fired when the right button on this controller is modified
  70902. */
  70903. get: function () {
  70904. return this.onMainButtonStateChangedObservable;
  70905. },
  70906. enumerable: true,
  70907. configurable: true
  70908. });
  70909. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  70910. /**
  70911. * Fired when the menu button on this controller is modified
  70912. */
  70913. get: function () {
  70914. return this.onSecondaryButtonStateChangedObservable;
  70915. },
  70916. enumerable: true,
  70917. configurable: true
  70918. });
  70919. /**
  70920. * Called once for each button that changed state since the last frame
  70921. * Vive mapping:
  70922. * 0: touchpad
  70923. * 1: trigger
  70924. * 2: left AND right buttons
  70925. * 3: menu button
  70926. * @param buttonIdx Which button index changed
  70927. * @param state New state of the button
  70928. * @param changes Which properties on the state changed since last frame
  70929. */
  70930. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  70931. var notifyObject = state; //{ state: state, changes: changes };
  70932. switch (buttonIdx) {
  70933. case 0:
  70934. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  70935. return;
  70936. case 1: // index trigger
  70937. if (this._defaultModel) {
  70938. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  70939. }
  70940. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  70941. return;
  70942. case 2: // left AND right button
  70943. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  70944. return;
  70945. case 3:
  70946. if (this._defaultModel) {
  70947. if (notifyObject.pressed) {
  70948. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  70949. }
  70950. else {
  70951. (this._defaultModel.getChildren()[2]).position.y = 0;
  70952. }
  70953. }
  70954. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  70955. return;
  70956. }
  70957. };
  70958. /**
  70959. * Base Url for the controller model.
  70960. */
  70961. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  70962. /**
  70963. * File name for the controller model.
  70964. */
  70965. ViveController.MODEL_FILENAME = 'wand.babylon';
  70966. return ViveController;
  70967. }(BABYLON.WebVRController));
  70968. BABYLON.ViveController = ViveController;
  70969. })(BABYLON || (BABYLON = {}));
  70970. //# sourceMappingURL=babylon.viveController.js.map
  70971. var BABYLON;
  70972. (function (BABYLON) {
  70973. /**
  70974. * Generic Controller
  70975. */
  70976. var GenericController = /** @class */ (function (_super) {
  70977. __extends(GenericController, _super);
  70978. /**
  70979. * Creates a new GenericController from a gamepad
  70980. * @param vrGamepad the gamepad that the controller should be created from
  70981. */
  70982. function GenericController(vrGamepad) {
  70983. return _super.call(this, vrGamepad) || this;
  70984. }
  70985. /**
  70986. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  70987. * @param scene scene in which to add meshes
  70988. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  70989. */
  70990. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  70991. var _this = this;
  70992. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  70993. _this._defaultModel = newMeshes[1];
  70994. _this.attachToMesh(_this._defaultModel);
  70995. if (meshLoaded) {
  70996. meshLoaded(_this._defaultModel);
  70997. }
  70998. });
  70999. };
  71000. /**
  71001. * Called once for each button that changed state since the last frame
  71002. * @param buttonIdx Which button index changed
  71003. * @param state New state of the button
  71004. * @param changes Which properties on the state changed since last frame
  71005. */
  71006. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71007. console.log("Button id: " + buttonIdx + "state: ");
  71008. console.dir(state);
  71009. };
  71010. /**
  71011. * Base Url for the controller model.
  71012. */
  71013. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71014. /**
  71015. * File name for the controller model.
  71016. */
  71017. GenericController.MODEL_FILENAME = 'generic.babylon';
  71018. return GenericController;
  71019. }(BABYLON.WebVRController));
  71020. BABYLON.GenericController = GenericController;
  71021. })(BABYLON || (BABYLON = {}));
  71022. //# sourceMappingURL=babylon.genericController.js.map
  71023. var BABYLON;
  71024. (function (BABYLON) {
  71025. /**
  71026. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71027. */
  71028. var LoadedMeshInfo = /** @class */ (function () {
  71029. function LoadedMeshInfo() {
  71030. /**
  71031. * Map of the button meshes contained in the controller
  71032. */
  71033. this.buttonMeshes = {};
  71034. /**
  71035. * Map of the axis meshes contained in the controller
  71036. */
  71037. this.axisMeshes = {};
  71038. }
  71039. return LoadedMeshInfo;
  71040. }());
  71041. /**
  71042. * Defines the WindowsMotionController object that the state of the windows motion controller
  71043. */
  71044. var WindowsMotionController = /** @class */ (function (_super) {
  71045. __extends(WindowsMotionController, _super);
  71046. /**
  71047. * Creates a new WindowsMotionController from a gamepad
  71048. * @param vrGamepad the gamepad that the controller should be created from
  71049. */
  71050. function WindowsMotionController(vrGamepad) {
  71051. var _this = _super.call(this, vrGamepad) || this;
  71052. _this._mapping = {
  71053. // Semantic button names
  71054. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71055. // A mapping of the button name to glTF model node name
  71056. // that should be transformed by button value.
  71057. buttonMeshNames: {
  71058. 'trigger': 'SELECT',
  71059. 'menu': 'MENU',
  71060. 'grip': 'GRASP',
  71061. 'thumbstick': 'THUMBSTICK_PRESS',
  71062. 'trackpad': 'TOUCHPAD_PRESS'
  71063. },
  71064. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71065. buttonObservableNames: {
  71066. 'trigger': 'onTriggerStateChangedObservable',
  71067. 'menu': 'onSecondaryButtonStateChangedObservable',
  71068. 'grip': 'onMainButtonStateChangedObservable',
  71069. 'thumbstick': 'onPadStateChangedObservable',
  71070. 'trackpad': 'onTrackpadChangedObservable'
  71071. },
  71072. // A mapping of the axis name to glTF model node name
  71073. // that should be transformed by axis value.
  71074. // This array mirrors the browserGamepad.axes array, such that
  71075. // the mesh corresponding to axis 0 is in this array index 0.
  71076. axisMeshNames: [
  71077. 'THUMBSTICK_X',
  71078. 'THUMBSTICK_Y',
  71079. 'TOUCHPAD_TOUCH_X',
  71080. 'TOUCHPAD_TOUCH_Y'
  71081. ],
  71082. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71083. };
  71084. /**
  71085. * Fired when the trackpad on this controller is clicked
  71086. */
  71087. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71088. /**
  71089. * Fired when the trackpad on this controller is modified
  71090. */
  71091. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71092. /**
  71093. * The current x and y values of this controller's trackpad
  71094. */
  71095. _this.trackpad = { x: 0, y: 0 };
  71096. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71097. _this._loadedMeshInfo = null;
  71098. return _this;
  71099. }
  71100. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71101. /**
  71102. * Fired when the trigger on this controller is modified
  71103. */
  71104. get: function () {
  71105. return this.onTriggerStateChangedObservable;
  71106. },
  71107. enumerable: true,
  71108. configurable: true
  71109. });
  71110. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71111. /**
  71112. * Fired when the menu button on this controller is modified
  71113. */
  71114. get: function () {
  71115. return this.onSecondaryButtonStateChangedObservable;
  71116. },
  71117. enumerable: true,
  71118. configurable: true
  71119. });
  71120. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71121. /**
  71122. * Fired when the grip button on this controller is modified
  71123. */
  71124. get: function () {
  71125. return this.onMainButtonStateChangedObservable;
  71126. },
  71127. enumerable: true,
  71128. configurable: true
  71129. });
  71130. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71131. /**
  71132. * Fired when the thumbstick button on this controller is modified
  71133. */
  71134. get: function () {
  71135. return this.onPadStateChangedObservable;
  71136. },
  71137. enumerable: true,
  71138. configurable: true
  71139. });
  71140. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71141. /**
  71142. * Fired when the touchpad button on this controller is modified
  71143. */
  71144. get: function () {
  71145. return this.onTrackpadChangedObservable;
  71146. },
  71147. enumerable: true,
  71148. configurable: true
  71149. });
  71150. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71151. /**
  71152. * Fired when the touchpad values on this controller are modified
  71153. */
  71154. get: function () {
  71155. return this.onTrackpadValuesChangedObservable;
  71156. },
  71157. enumerable: true,
  71158. configurable: true
  71159. });
  71160. /**
  71161. * Called once per frame by the engine.
  71162. */
  71163. WindowsMotionController.prototype.update = function () {
  71164. _super.prototype.update.call(this);
  71165. if (this.browserGamepad.axes) {
  71166. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71167. this.trackpad.x = this.browserGamepad["axes"][2];
  71168. this.trackpad.y = this.browserGamepad["axes"][3];
  71169. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71170. }
  71171. // Only need to animate axes if there is a loaded mesh
  71172. if (this._loadedMeshInfo) {
  71173. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71174. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71175. }
  71176. }
  71177. }
  71178. };
  71179. /**
  71180. * Called once for each button that changed state since the last frame
  71181. * @param buttonIdx Which button index changed
  71182. * @param state New state of the button
  71183. * @param changes Which properties on the state changed since last frame
  71184. */
  71185. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71186. var buttonName = this._mapping.buttons[buttonIdx];
  71187. if (!buttonName) {
  71188. return;
  71189. }
  71190. // Only emit events for buttons that we know how to map from index to name
  71191. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71192. if (observable) {
  71193. observable.notifyObservers(state);
  71194. }
  71195. this._lerpButtonTransform(buttonName, state.value);
  71196. };
  71197. /**
  71198. * Moves the buttons on the controller mesh based on their current state
  71199. * @param buttonName the name of the button to move
  71200. * @param buttonValue the value of the button which determines the buttons new position
  71201. */
  71202. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71203. // If there is no loaded mesh, there is nothing to transform.
  71204. if (!this._loadedMeshInfo) {
  71205. return;
  71206. }
  71207. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71208. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71209. return;
  71210. }
  71211. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71212. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71213. };
  71214. /**
  71215. * Moves the axis on the controller mesh based on its current state
  71216. * @param axis the index of the axis
  71217. * @param axisValue the value of the axis which determines the meshes new position
  71218. * @ignore
  71219. */
  71220. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71221. if (!this._loadedMeshInfo) {
  71222. return;
  71223. }
  71224. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71225. if (!meshInfo) {
  71226. return;
  71227. }
  71228. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71229. return;
  71230. }
  71231. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71232. var lerpValue = axisValue * 0.5 + 0.5;
  71233. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71234. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71235. };
  71236. /**
  71237. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71238. * @param scene scene in which to add meshes
  71239. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71240. */
  71241. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71242. var _this = this;
  71243. if (forceDefault === void 0) { forceDefault = false; }
  71244. var path;
  71245. var filename;
  71246. // Checking if GLB loader is present
  71247. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71248. // Determine the device specific folder based on the ID suffix
  71249. var device = 'default';
  71250. if (this.id && !forceDefault) {
  71251. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71252. device = ((match && match[0]) || device);
  71253. }
  71254. // Hand
  71255. if (this.hand === 'left') {
  71256. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71257. }
  71258. else { // Right is the default if no hand is specified
  71259. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71260. }
  71261. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71262. }
  71263. else {
  71264. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71265. path = BABYLON.GenericController.MODEL_BASE_URL;
  71266. filename = BABYLON.GenericController.MODEL_FILENAME;
  71267. }
  71268. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71269. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71270. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71271. if (!_this._loadedMeshInfo) {
  71272. return;
  71273. }
  71274. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71275. _this.attachToMesh(_this._defaultModel);
  71276. if (meshLoaded) {
  71277. meshLoaded(_this._defaultModel);
  71278. }
  71279. }, null, function (scene, message) {
  71280. BABYLON.Tools.Log(message);
  71281. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71282. if (!forceDefault) {
  71283. _this.initControllerMesh(scene, meshLoaded, true);
  71284. }
  71285. });
  71286. };
  71287. /**
  71288. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71289. * can be transformed by button presses and axes values, based on this._mapping.
  71290. *
  71291. * @param scene scene in which the meshes exist
  71292. * @param meshes list of meshes that make up the controller model to process
  71293. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71294. */
  71295. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71296. var loadedMeshInfo = null;
  71297. // Create a new mesh to contain the glTF hierarchy
  71298. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71299. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71300. var childMesh = null;
  71301. for (var i = 0; i < meshes.length; i++) {
  71302. var mesh = meshes[i];
  71303. if (!mesh.parent) {
  71304. // Exclude controller meshes from picking results
  71305. mesh.isPickable = false;
  71306. // Handle root node, attach to the new parentMesh
  71307. childMesh = mesh;
  71308. break;
  71309. }
  71310. }
  71311. if (childMesh) {
  71312. childMesh.setParent(parentMesh);
  71313. // Create our mesh info. Note that this method will always return non-null.
  71314. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71315. }
  71316. else {
  71317. BABYLON.Tools.Warn('Could not find root node in model file.');
  71318. }
  71319. return loadedMeshInfo;
  71320. };
  71321. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71322. var loadedMeshInfo = new LoadedMeshInfo();
  71323. var i;
  71324. loadedMeshInfo.rootNode = rootNode;
  71325. // Reset the caches
  71326. loadedMeshInfo.buttonMeshes = {};
  71327. loadedMeshInfo.axisMeshes = {};
  71328. // Button Meshes
  71329. for (i = 0; i < this._mapping.buttons.length; i++) {
  71330. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71331. if (!buttonMeshName) {
  71332. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71333. continue;
  71334. }
  71335. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71336. if (!buttonMesh) {
  71337. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71338. continue;
  71339. }
  71340. var buttonMeshInfo = {
  71341. index: i,
  71342. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71343. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71344. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71345. };
  71346. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71347. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71348. }
  71349. else {
  71350. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71351. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71352. '(VALUE: ' + !!buttonMeshInfo.value +
  71353. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71354. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71355. ')');
  71356. }
  71357. }
  71358. // Axis Meshes
  71359. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71360. var axisMeshName = this._mapping.axisMeshNames[i];
  71361. if (!axisMeshName) {
  71362. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71363. continue;
  71364. }
  71365. var axisMesh = getChildByName(rootNode, axisMeshName);
  71366. if (!axisMesh) {
  71367. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71368. continue;
  71369. }
  71370. var axisMeshInfo = {
  71371. index: i,
  71372. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71373. min: getImmediateChildByName(axisMesh, 'MIN'),
  71374. max: getImmediateChildByName(axisMesh, 'MAX')
  71375. };
  71376. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71377. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71378. }
  71379. else {
  71380. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71381. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71382. '(VALUE: ' + !!axisMeshInfo.value +
  71383. ', MIN: ' + !!axisMeshInfo.min +
  71384. ', MAX:' + !!axisMeshInfo.max +
  71385. ')');
  71386. }
  71387. }
  71388. // Pointing Ray
  71389. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71390. if (!loadedMeshInfo.pointingPoseNode) {
  71391. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71392. }
  71393. return loadedMeshInfo;
  71394. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71395. function getChildByName(node, name) {
  71396. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71397. }
  71398. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71399. function getImmediateChildByName(node, name) {
  71400. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71401. }
  71402. };
  71403. /**
  71404. * Gets the ray of the controller in the direction the controller is pointing
  71405. * @param length the length the resulting ray should be
  71406. * @returns a ray in the direction the controller is pointing
  71407. */
  71408. WindowsMotionController.prototype.getForwardRay = function (length) {
  71409. if (length === void 0) { length = 100; }
  71410. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71411. return _super.prototype.getForwardRay.call(this, length);
  71412. }
  71413. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71414. var origin = m.getTranslation();
  71415. var forward = new BABYLON.Vector3(0, 0, -1);
  71416. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71417. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71418. return new BABYLON.Ray(origin, direction, length);
  71419. };
  71420. /**
  71421. * Disposes of the controller
  71422. */
  71423. WindowsMotionController.prototype.dispose = function () {
  71424. _super.prototype.dispose.call(this);
  71425. this.onTrackpadChangedObservable.clear();
  71426. };
  71427. /**
  71428. * The base url used to load the left and right controller models
  71429. */
  71430. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71431. /**
  71432. * The name of the left controller model file
  71433. */
  71434. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71435. /**
  71436. * The name of the right controller model file
  71437. */
  71438. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71439. /**
  71440. * The controller name prefix for this controller type
  71441. */
  71442. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71443. /**
  71444. * The controller id pattern for this controller type
  71445. */
  71446. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71447. return WindowsMotionController;
  71448. }(BABYLON.WebVRController));
  71449. BABYLON.WindowsMotionController = WindowsMotionController;
  71450. })(BABYLON || (BABYLON = {}));
  71451. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71452. var BABYLON;
  71453. (function (BABYLON) {
  71454. /**
  71455. * Gear VR Controller
  71456. */
  71457. var GearVRController = /** @class */ (function (_super) {
  71458. __extends(GearVRController, _super);
  71459. /**
  71460. * Creates a new GearVRController from a gamepad
  71461. * @param vrGamepad the gamepad that the controller should be created from
  71462. */
  71463. function GearVRController(vrGamepad) {
  71464. var _this = _super.call(this, vrGamepad) || this;
  71465. _this._buttonIndexToObservableNameMap = [
  71466. 'onTrackpadChangedObservable',
  71467. 'onTriggerStateChangedObservable' // Trigger
  71468. ];
  71469. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71470. return _this;
  71471. }
  71472. /**
  71473. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71474. * @param scene scene in which to add meshes
  71475. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71476. */
  71477. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71478. var _this = this;
  71479. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71480. _this._defaultModel = newMeshes[1];
  71481. _this.attachToMesh(_this._defaultModel);
  71482. if (meshLoaded) {
  71483. meshLoaded(_this._defaultModel);
  71484. }
  71485. });
  71486. };
  71487. /**
  71488. * Called once for each button that changed state since the last frame
  71489. * @param buttonIdx Which button index changed
  71490. * @param state New state of the button
  71491. * @param changes Which properties on the state changed since last frame
  71492. */
  71493. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71494. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71495. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71496. // Only emit events for buttons that we know how to map from index to observable
  71497. var observable = this[observableName];
  71498. if (observable) {
  71499. observable.notifyObservers(state);
  71500. }
  71501. }
  71502. };
  71503. /**
  71504. * Base Url for the controller model.
  71505. */
  71506. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71507. /**
  71508. * File name for the controller model.
  71509. */
  71510. GearVRController.MODEL_FILENAME = 'generic.babylon';
  71511. /**
  71512. * Gamepad Id prefix used to identify this controller.
  71513. */
  71514. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  71515. return GearVRController;
  71516. }(BABYLON.WebVRController));
  71517. BABYLON.GearVRController = GearVRController;
  71518. })(BABYLON || (BABYLON = {}));
  71519. //# sourceMappingURL=babylon.gearVRController.js.map
  71520. var BABYLON;
  71521. (function (BABYLON) {
  71522. /**
  71523. * Google Daydream controller
  71524. */
  71525. var DaydreamController = /** @class */ (function (_super) {
  71526. __extends(DaydreamController, _super);
  71527. /**
  71528. * Creates a new DaydreamController from a gamepad
  71529. * @param vrGamepad the gamepad that the controller should be created from
  71530. */
  71531. function DaydreamController(vrGamepad) {
  71532. var _this = _super.call(this, vrGamepad) || this;
  71533. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  71534. return _this;
  71535. }
  71536. /**
  71537. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71538. * @param scene scene in which to add meshes
  71539. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71540. */
  71541. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71542. var _this = this;
  71543. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  71544. _this._defaultModel = newMeshes[1];
  71545. _this.attachToMesh(_this._defaultModel);
  71546. if (meshLoaded) {
  71547. meshLoaded(_this._defaultModel);
  71548. }
  71549. });
  71550. };
  71551. /**
  71552. * Called once for each button that changed state since the last frame
  71553. * @param buttonIdx Which button index changed
  71554. * @param state New state of the button
  71555. * @param changes Which properties on the state changed since last frame
  71556. */
  71557. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71558. // Daydream controller only has 1 GamepadButton (on the trackpad).
  71559. if (buttonIdx === 0) {
  71560. var observable = this.onTriggerStateChangedObservable;
  71561. if (observable) {
  71562. observable.notifyObservers(state);
  71563. }
  71564. }
  71565. else {
  71566. // If the app or home buttons are ever made available
  71567. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  71568. }
  71569. };
  71570. /**
  71571. * Base Url for the controller model.
  71572. */
  71573. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71574. /**
  71575. * File name for the controller model.
  71576. */
  71577. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  71578. /**
  71579. * Gamepad Id prefix used to identify Daydream Controller.
  71580. */
  71581. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  71582. return DaydreamController;
  71583. }(BABYLON.WebVRController));
  71584. BABYLON.DaydreamController = DaydreamController;
  71585. })(BABYLON || (BABYLON = {}));
  71586. //# sourceMappingURL=babylon.daydreamController.js.map
  71587. var BABYLON;
  71588. (function (BABYLON) {
  71589. var FollowCamera = /** @class */ (function (_super) {
  71590. __extends(FollowCamera, _super);
  71591. function FollowCamera(name, position, scene, lockedTarget) {
  71592. if (lockedTarget === void 0) { lockedTarget = null; }
  71593. var _this = _super.call(this, name, position, scene) || this;
  71594. _this.radius = 12;
  71595. _this.rotationOffset = 0;
  71596. _this.heightOffset = 4;
  71597. _this.cameraAcceleration = 0.05;
  71598. _this.maxCameraSpeed = 20;
  71599. _this.lockedTarget = lockedTarget;
  71600. return _this;
  71601. }
  71602. FollowCamera.prototype.getRadians = function (degrees) {
  71603. return degrees * Math.PI / 180;
  71604. };
  71605. FollowCamera.prototype.follow = function (cameraTarget) {
  71606. if (!cameraTarget)
  71607. return;
  71608. var yRotation;
  71609. if (cameraTarget.rotationQuaternion) {
  71610. var rotMatrix = new BABYLON.Matrix();
  71611. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  71612. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  71613. }
  71614. else {
  71615. yRotation = cameraTarget.rotation.y;
  71616. }
  71617. var radians = this.getRadians(this.rotationOffset) + yRotation;
  71618. var targetPosition = cameraTarget.getAbsolutePosition();
  71619. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  71620. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  71621. var dx = targetX - this.position.x;
  71622. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  71623. var dz = (targetZ) - this.position.z;
  71624. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  71625. var vy = dy * this.cameraAcceleration;
  71626. var vz = dz * this.cameraAcceleration * 2;
  71627. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  71628. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71629. }
  71630. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  71631. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71632. }
  71633. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  71634. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  71635. }
  71636. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  71637. this.setTarget(targetPosition);
  71638. };
  71639. FollowCamera.prototype._checkInputs = function () {
  71640. _super.prototype._checkInputs.call(this);
  71641. if (this.lockedTarget) {
  71642. this.follow(this.lockedTarget);
  71643. }
  71644. };
  71645. FollowCamera.prototype.getClassName = function () {
  71646. return "FollowCamera";
  71647. };
  71648. __decorate([
  71649. BABYLON.serialize()
  71650. ], FollowCamera.prototype, "radius", void 0);
  71651. __decorate([
  71652. BABYLON.serialize()
  71653. ], FollowCamera.prototype, "rotationOffset", void 0);
  71654. __decorate([
  71655. BABYLON.serialize()
  71656. ], FollowCamera.prototype, "heightOffset", void 0);
  71657. __decorate([
  71658. BABYLON.serialize()
  71659. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  71660. __decorate([
  71661. BABYLON.serialize()
  71662. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  71663. __decorate([
  71664. BABYLON.serializeAsMeshReference("lockedTargetId")
  71665. ], FollowCamera.prototype, "lockedTarget", void 0);
  71666. return FollowCamera;
  71667. }(BABYLON.TargetCamera));
  71668. BABYLON.FollowCamera = FollowCamera;
  71669. var ArcFollowCamera = /** @class */ (function (_super) {
  71670. __extends(ArcFollowCamera, _super);
  71671. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  71672. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  71673. _this.alpha = alpha;
  71674. _this.beta = beta;
  71675. _this.radius = radius;
  71676. _this.target = target;
  71677. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  71678. _this.follow();
  71679. return _this;
  71680. }
  71681. ArcFollowCamera.prototype.follow = function () {
  71682. if (!this.target) {
  71683. return;
  71684. }
  71685. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  71686. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  71687. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  71688. var targetPosition = this.target.getAbsolutePosition();
  71689. this.position = targetPosition.add(this._cartesianCoordinates);
  71690. this.setTarget(targetPosition);
  71691. };
  71692. ArcFollowCamera.prototype._checkInputs = function () {
  71693. _super.prototype._checkInputs.call(this);
  71694. this.follow();
  71695. };
  71696. ArcFollowCamera.prototype.getClassName = function () {
  71697. return "ArcFollowCamera";
  71698. };
  71699. return ArcFollowCamera;
  71700. }(BABYLON.TargetCamera));
  71701. BABYLON.ArcFollowCamera = ArcFollowCamera;
  71702. })(BABYLON || (BABYLON = {}));
  71703. //# sourceMappingURL=babylon.followCamera.js.map
  71704. var BABYLON;
  71705. (function (BABYLON) {
  71706. // We're mainly based on the logic defined into the FreeCamera code
  71707. var UniversalCamera = /** @class */ (function (_super) {
  71708. __extends(UniversalCamera, _super);
  71709. //-- end properties for backward compatibility for inputs
  71710. function UniversalCamera(name, position, scene) {
  71711. var _this = _super.call(this, name, position, scene) || this;
  71712. _this.inputs.addGamepad();
  71713. return _this;
  71714. }
  71715. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  71716. //-- Begin properties for backward compatibility for inputs
  71717. get: function () {
  71718. var gamepad = this.inputs.attached["gamepad"];
  71719. if (gamepad)
  71720. return gamepad.gamepadAngularSensibility;
  71721. return 0;
  71722. },
  71723. set: function (value) {
  71724. var gamepad = this.inputs.attached["gamepad"];
  71725. if (gamepad)
  71726. gamepad.gamepadAngularSensibility = value;
  71727. },
  71728. enumerable: true,
  71729. configurable: true
  71730. });
  71731. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  71732. get: function () {
  71733. var gamepad = this.inputs.attached["gamepad"];
  71734. if (gamepad)
  71735. return gamepad.gamepadMoveSensibility;
  71736. return 0;
  71737. },
  71738. set: function (value) {
  71739. var gamepad = this.inputs.attached["gamepad"];
  71740. if (gamepad)
  71741. gamepad.gamepadMoveSensibility = value;
  71742. },
  71743. enumerable: true,
  71744. configurable: true
  71745. });
  71746. UniversalCamera.prototype.getClassName = function () {
  71747. return "UniversalCamera";
  71748. };
  71749. return UniversalCamera;
  71750. }(BABYLON.TouchCamera));
  71751. BABYLON.UniversalCamera = UniversalCamera;
  71752. })(BABYLON || (BABYLON = {}));
  71753. //# sourceMappingURL=babylon.universalCamera.js.map
  71754. var BABYLON;
  71755. (function (BABYLON) {
  71756. // We're mainly based on the logic defined into the FreeCamera code
  71757. var GamepadCamera = /** @class */ (function (_super) {
  71758. __extends(GamepadCamera, _super);
  71759. //-- end properties for backward compatibility for inputs
  71760. function GamepadCamera(name, position, scene) {
  71761. return _super.call(this, name, position, scene) || this;
  71762. }
  71763. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  71764. //-- Begin properties for backward compatibility for inputs
  71765. get: function () {
  71766. var gamepad = this.inputs.attached["gamepad"];
  71767. if (gamepad)
  71768. return gamepad.gamepadAngularSensibility;
  71769. return 0;
  71770. },
  71771. set: function (value) {
  71772. var gamepad = this.inputs.attached["gamepad"];
  71773. if (gamepad)
  71774. gamepad.gamepadAngularSensibility = value;
  71775. },
  71776. enumerable: true,
  71777. configurable: true
  71778. });
  71779. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  71780. get: function () {
  71781. var gamepad = this.inputs.attached["gamepad"];
  71782. if (gamepad)
  71783. return gamepad.gamepadMoveSensibility;
  71784. return 0;
  71785. },
  71786. set: function (value) {
  71787. var gamepad = this.inputs.attached["gamepad"];
  71788. if (gamepad)
  71789. gamepad.gamepadMoveSensibility = value;
  71790. },
  71791. enumerable: true,
  71792. configurable: true
  71793. });
  71794. GamepadCamera.prototype.getClassName = function () {
  71795. return "GamepadCamera";
  71796. };
  71797. return GamepadCamera;
  71798. }(BABYLON.UniversalCamera));
  71799. BABYLON.GamepadCamera = GamepadCamera;
  71800. })(BABYLON || (BABYLON = {}));
  71801. //# sourceMappingURL=babylon.gamepadCamera.js.map
  71802. var BABYLON;
  71803. (function (BABYLON) {
  71804. var PostProcessRenderPipelineManager = /** @class */ (function () {
  71805. function PostProcessRenderPipelineManager() {
  71806. this._renderPipelines = {};
  71807. }
  71808. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  71809. this._renderPipelines[renderPipeline._name] = renderPipeline;
  71810. };
  71811. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  71812. if (unique === void 0) { unique = false; }
  71813. var renderPipeline = this._renderPipelines[renderPipelineName];
  71814. if (!renderPipeline) {
  71815. return;
  71816. }
  71817. renderPipeline._attachCameras(cameras, unique);
  71818. };
  71819. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  71820. var renderPipeline = this._renderPipelines[renderPipelineName];
  71821. if (!renderPipeline) {
  71822. return;
  71823. }
  71824. renderPipeline._detachCameras(cameras);
  71825. };
  71826. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71827. var renderPipeline = this._renderPipelines[renderPipelineName];
  71828. if (!renderPipeline) {
  71829. return;
  71830. }
  71831. renderPipeline._enableEffect(renderEffectName, cameras);
  71832. };
  71833. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  71834. var renderPipeline = this._renderPipelines[renderPipelineName];
  71835. if (!renderPipeline) {
  71836. return;
  71837. }
  71838. renderPipeline._disableEffect(renderEffectName, cameras);
  71839. };
  71840. PostProcessRenderPipelineManager.prototype.update = function () {
  71841. for (var renderPipelineName in this._renderPipelines) {
  71842. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71843. var pipeline = this._renderPipelines[renderPipelineName];
  71844. if (!pipeline.isSupported) {
  71845. pipeline.dispose();
  71846. delete this._renderPipelines[renderPipelineName];
  71847. }
  71848. else {
  71849. pipeline._update();
  71850. }
  71851. }
  71852. }
  71853. };
  71854. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  71855. for (var renderPipelineName in this._renderPipelines) {
  71856. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71857. var pipeline = this._renderPipelines[renderPipelineName];
  71858. pipeline._rebuild();
  71859. }
  71860. }
  71861. };
  71862. PostProcessRenderPipelineManager.prototype.dispose = function () {
  71863. for (var renderPipelineName in this._renderPipelines) {
  71864. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  71865. var pipeline = this._renderPipelines[renderPipelineName];
  71866. pipeline.dispose();
  71867. }
  71868. }
  71869. };
  71870. return PostProcessRenderPipelineManager;
  71871. }());
  71872. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  71873. })(BABYLON || (BABYLON = {}));
  71874. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  71875. var BABYLON;
  71876. (function (BABYLON) {
  71877. /**
  71878. * This represents a set of one or more post processes in Babylon.
  71879. * A post process can be used to apply a shader to a texture after it is rendered.
  71880. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  71881. */
  71882. var PostProcessRenderEffect = /** @class */ (function () {
  71883. /**
  71884. * Instantiates a post process render effect.
  71885. * A post process can be used to apply a shader to a texture after it is rendered.
  71886. * @param engine The engine the effect is tied to
  71887. * @param name The name of the effect
  71888. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  71889. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  71890. */
  71891. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  71892. this._name = name;
  71893. this._singleInstance = singleInstance || true;
  71894. this._getPostProcesses = getPostProcesses;
  71895. this._cameras = {};
  71896. this._indicesForCamera = {};
  71897. this._postProcesses = {};
  71898. }
  71899. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  71900. /**
  71901. * Checks if all the post processes in the effect are supported.
  71902. */
  71903. get: function () {
  71904. for (var index in this._postProcesses) {
  71905. if (this._postProcesses.hasOwnProperty(index)) {
  71906. var pps = this._postProcesses[index];
  71907. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  71908. if (!pps[ppIndex].isSupported) {
  71909. return false;
  71910. }
  71911. }
  71912. }
  71913. }
  71914. return true;
  71915. },
  71916. enumerable: true,
  71917. configurable: true
  71918. });
  71919. /**
  71920. * Updates the current state of the effect
  71921. */
  71922. PostProcessRenderEffect.prototype._update = function () {
  71923. };
  71924. /**
  71925. * Attaches the effect on cameras
  71926. * @param cameras The camera to attach to.
  71927. */
  71928. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  71929. var _this = this;
  71930. var cameraKey;
  71931. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71932. if (!cams) {
  71933. return;
  71934. }
  71935. for (var i = 0; i < cams.length; i++) {
  71936. var camera = cams[i];
  71937. var cameraName = camera.name;
  71938. if (this._singleInstance) {
  71939. cameraKey = 0;
  71940. }
  71941. else {
  71942. cameraKey = cameraName;
  71943. }
  71944. if (!this._postProcesses[cameraKey]) {
  71945. var postProcess = this._getPostProcesses();
  71946. if (postProcess) {
  71947. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  71948. }
  71949. }
  71950. if (!this._indicesForCamera[cameraName]) {
  71951. this._indicesForCamera[cameraName] = [];
  71952. }
  71953. this._postProcesses[cameraKey].forEach(function (postProcess) {
  71954. var index = camera.attachPostProcess(postProcess);
  71955. _this._indicesForCamera[cameraName].push(index);
  71956. });
  71957. if (!this._cameras[cameraName]) {
  71958. this._cameras[cameraName] = camera;
  71959. }
  71960. }
  71961. };
  71962. /**
  71963. * Detatches the effect on cameras
  71964. * @param cameras The camera to detatch from.
  71965. */
  71966. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  71967. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71968. if (!cams) {
  71969. return;
  71970. }
  71971. for (var i = 0; i < cams.length; i++) {
  71972. var camera = cams[i];
  71973. var cameraName = camera.name;
  71974. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71975. camera.detachPostProcess(postProcess);
  71976. });
  71977. if (this._cameras[cameraName]) {
  71978. //this._indicesForCamera.splice(index, 1);
  71979. this._cameras[cameraName] = null;
  71980. }
  71981. }
  71982. };
  71983. /**
  71984. * Enables the effect on given cameras
  71985. * @param cameras The camera to enable.
  71986. */
  71987. PostProcessRenderEffect.prototype._enable = function (cameras) {
  71988. var _this = this;
  71989. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  71990. if (!cams) {
  71991. return;
  71992. }
  71993. for (var i = 0; i < cams.length; i++) {
  71994. var camera = cams[i];
  71995. var cameraName = camera.name;
  71996. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  71997. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  71998. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  71999. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72000. });
  72001. }
  72002. }
  72003. }
  72004. };
  72005. /**
  72006. * Disables the effect on the given cameras
  72007. * @param cameras The camera to disable.
  72008. */
  72009. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72010. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72011. if (!cams) {
  72012. return;
  72013. }
  72014. for (var i = 0; i < cams.length; i++) {
  72015. var camera = cams[i];
  72016. var cameraName = camera.name;
  72017. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72018. camera.detachPostProcess(postProcess);
  72019. });
  72020. }
  72021. };
  72022. /**
  72023. * Gets a list of the post processes contained in the effect.
  72024. * @param camera The camera to get the post processes on.
  72025. * @returns The list of the post processes in the effect.
  72026. */
  72027. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72028. if (this._singleInstance) {
  72029. return this._postProcesses[0];
  72030. }
  72031. else {
  72032. if (!camera) {
  72033. return null;
  72034. }
  72035. return this._postProcesses[camera.name];
  72036. }
  72037. };
  72038. return PostProcessRenderEffect;
  72039. }());
  72040. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72041. })(BABYLON || (BABYLON = {}));
  72042. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72043. var BABYLON;
  72044. (function (BABYLON) {
  72045. var PostProcessRenderPipeline = /** @class */ (function () {
  72046. function PostProcessRenderPipeline(engine, name) {
  72047. this.engine = engine;
  72048. this._name = name;
  72049. this._renderEffects = {};
  72050. this._renderEffectsForIsolatedPass = new Array();
  72051. this._cameras = [];
  72052. }
  72053. PostProcessRenderPipeline.prototype.getClassName = function () {
  72054. return "PostProcessRenderPipeline";
  72055. };
  72056. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72057. get: function () {
  72058. for (var renderEffectName in this._renderEffects) {
  72059. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72060. if (!this._renderEffects[renderEffectName].isSupported) {
  72061. return false;
  72062. }
  72063. }
  72064. }
  72065. return true;
  72066. },
  72067. enumerable: true,
  72068. configurable: true
  72069. });
  72070. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72071. this._renderEffects[renderEffect._name] = renderEffect;
  72072. };
  72073. // private
  72074. PostProcessRenderPipeline.prototype._rebuild = function () {
  72075. };
  72076. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72077. var renderEffects = this._renderEffects[renderEffectName];
  72078. if (!renderEffects) {
  72079. return;
  72080. }
  72081. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72082. };
  72083. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72084. var renderEffects = this._renderEffects[renderEffectName];
  72085. if (!renderEffects) {
  72086. return;
  72087. }
  72088. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72089. };
  72090. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72091. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72092. if (!cams) {
  72093. return;
  72094. }
  72095. var indicesToDelete = [];
  72096. var i;
  72097. for (i = 0; i < cams.length; i++) {
  72098. var camera = cams[i];
  72099. var cameraName = camera.name;
  72100. if (this._cameras.indexOf(camera) === -1) {
  72101. this._cameras[cameraName] = camera;
  72102. }
  72103. else if (unique) {
  72104. indicesToDelete.push(i);
  72105. }
  72106. }
  72107. for (i = 0; i < indicesToDelete.length; i++) {
  72108. cameras.splice(indicesToDelete[i], 1);
  72109. }
  72110. for (var renderEffectName in this._renderEffects) {
  72111. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72112. this._renderEffects[renderEffectName]._attachCameras(cams);
  72113. }
  72114. }
  72115. };
  72116. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72117. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72118. if (!cams) {
  72119. return;
  72120. }
  72121. for (var renderEffectName in this._renderEffects) {
  72122. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72123. this._renderEffects[renderEffectName]._detachCameras(cams);
  72124. }
  72125. }
  72126. for (var i = 0; i < cams.length; i++) {
  72127. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72128. }
  72129. };
  72130. PostProcessRenderPipeline.prototype._update = function () {
  72131. for (var renderEffectName in this._renderEffects) {
  72132. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72133. this._renderEffects[renderEffectName]._update();
  72134. }
  72135. }
  72136. for (var i = 0; i < this._cameras.length; i++) {
  72137. var cameraName = this._cameras[i].name;
  72138. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72139. this._renderEffectsForIsolatedPass[cameraName]._update();
  72140. }
  72141. }
  72142. };
  72143. PostProcessRenderPipeline.prototype._reset = function () {
  72144. this._renderEffects = {};
  72145. this._renderEffectsForIsolatedPass = new Array();
  72146. };
  72147. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72148. // 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)
  72149. var effectKeys = Object.keys(this._renderEffects);
  72150. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72151. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72152. if (postProcesses) {
  72153. postProcesses[0].samples = sampleCount;
  72154. return true;
  72155. }
  72156. }
  72157. return false;
  72158. };
  72159. PostProcessRenderPipeline.prototype.dispose = function () {
  72160. // Must be implemented by children
  72161. };
  72162. __decorate([
  72163. BABYLON.serialize()
  72164. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72165. return PostProcessRenderPipeline;
  72166. }());
  72167. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72168. })(BABYLON || (BABYLON = {}));
  72169. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72170. var BABYLON;
  72171. (function (BABYLON) {
  72172. /**
  72173. * This represents a depth renderer in Babylon.
  72174. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72175. */
  72176. var DepthRenderer = /** @class */ (function () {
  72177. /**
  72178. * Instantiates a depth renderer
  72179. * @param scene The scene the renderer belongs to
  72180. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72181. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72182. */
  72183. function DepthRenderer(scene, type, camera) {
  72184. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72185. if (camera === void 0) { camera = null; }
  72186. var _this = this;
  72187. this._scene = scene;
  72188. this._camera = camera;
  72189. var engine = scene.getEngine();
  72190. // Render target
  72191. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72192. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72193. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72194. this._depthMap.refreshRate = 1;
  72195. this._depthMap.renderParticles = false;
  72196. this._depthMap.renderList = null;
  72197. // Camera to get depth map from to support multiple concurrent cameras
  72198. this._depthMap.activeCamera = this._camera;
  72199. this._depthMap.ignoreCameraViewport = true;
  72200. this._depthMap.useCameraPostProcesses = false;
  72201. // set default depth value to 1.0 (far away)
  72202. this._depthMap.onClearObservable.add(function (engine) {
  72203. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72204. });
  72205. // Custom render function
  72206. var renderSubMesh = function (subMesh) {
  72207. var mesh = subMesh.getRenderingMesh();
  72208. var scene = _this._scene;
  72209. var engine = scene.getEngine();
  72210. var material = subMesh.getMaterial();
  72211. if (!material) {
  72212. return;
  72213. }
  72214. // Culling and reverse (right handed system)
  72215. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72216. // Managing instances
  72217. var batch = mesh._getInstancesRenderList(subMesh._id);
  72218. if (batch.mustReturn) {
  72219. return;
  72220. }
  72221. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72222. var camera = _this._camera || scene.activeCamera;
  72223. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72224. engine.enableEffect(_this._effect);
  72225. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72226. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72227. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72228. // Alpha test
  72229. if (material && material.needAlphaTesting()) {
  72230. var alphaTexture = material.getAlphaTestTexture();
  72231. if (alphaTexture) {
  72232. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72233. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72234. }
  72235. }
  72236. // Bones
  72237. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72238. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72239. }
  72240. // Draw
  72241. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72242. }
  72243. };
  72244. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72245. var index;
  72246. if (depthOnlySubMeshes.length) {
  72247. engine.setColorWrite(false);
  72248. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72249. renderSubMesh(depthOnlySubMeshes.data[index]);
  72250. }
  72251. engine.setColorWrite(true);
  72252. }
  72253. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72254. renderSubMesh(opaqueSubMeshes.data[index]);
  72255. }
  72256. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72257. renderSubMesh(alphaTestSubMeshes.data[index]);
  72258. }
  72259. };
  72260. }
  72261. /**
  72262. * Creates the depth rendering effect and checks if the effect is ready.
  72263. * @param subMesh The submesh to be used to render the depth map of
  72264. * @param useInstances If multiple world instances should be used
  72265. * @returns if the depth renderer is ready to render the depth map
  72266. */
  72267. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72268. var material = subMesh.getMaterial();
  72269. if (material.disableDepthWrite) {
  72270. return false;
  72271. }
  72272. var defines = [];
  72273. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72274. var mesh = subMesh.getMesh();
  72275. // Alpha test
  72276. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72277. defines.push("#define ALPHATEST");
  72278. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72279. attribs.push(BABYLON.VertexBuffer.UVKind);
  72280. defines.push("#define UV1");
  72281. }
  72282. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72283. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72284. defines.push("#define UV2");
  72285. }
  72286. }
  72287. // Bones
  72288. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72289. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72290. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72291. if (mesh.numBoneInfluencers > 4) {
  72292. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72293. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72294. }
  72295. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72296. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72297. }
  72298. else {
  72299. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72300. }
  72301. // Instances
  72302. if (useInstances) {
  72303. defines.push("#define INSTANCES");
  72304. attribs.push("world0");
  72305. attribs.push("world1");
  72306. attribs.push("world2");
  72307. attribs.push("world3");
  72308. }
  72309. // Get correct effect
  72310. var join = defines.join("\n");
  72311. if (this._cachedDefines !== join) {
  72312. this._cachedDefines = join;
  72313. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72314. }
  72315. return this._effect.isReady();
  72316. };
  72317. /**
  72318. * Gets the texture which the depth map will be written to.
  72319. * @returns The depth map texture
  72320. */
  72321. DepthRenderer.prototype.getDepthMap = function () {
  72322. return this._depthMap;
  72323. };
  72324. /**
  72325. * Disposes of the depth renderer.
  72326. */
  72327. DepthRenderer.prototype.dispose = function () {
  72328. this._depthMap.dispose();
  72329. };
  72330. return DepthRenderer;
  72331. }());
  72332. BABYLON.DepthRenderer = DepthRenderer;
  72333. })(BABYLON || (BABYLON = {}));
  72334. //# sourceMappingURL=babylon.depthRenderer.js.map
  72335. var BABYLON;
  72336. (function (BABYLON) {
  72337. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72338. __extends(SSAORenderingPipeline, _super);
  72339. /**
  72340. * @constructor
  72341. * @param {string} name - The rendering pipeline name
  72342. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72343. * @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 }
  72344. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72345. */
  72346. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72347. var _this = _super.call(this, scene.getEngine(), name) || this;
  72348. // Members
  72349. /**
  72350. * The PassPostProcess id in the pipeline that contains the original scene color
  72351. */
  72352. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72353. /**
  72354. * The SSAO PostProcess id in the pipeline
  72355. */
  72356. _this.SSAORenderEffect = "SSAORenderEffect";
  72357. /**
  72358. * The horizontal blur PostProcess id in the pipeline
  72359. */
  72360. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72361. /**
  72362. * The vertical blur PostProcess id in the pipeline
  72363. */
  72364. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72365. /**
  72366. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72367. */
  72368. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72369. /**
  72370. * The output strength of the SSAO post-process. Default value is 1.0.
  72371. */
  72372. _this.totalStrength = 1.0;
  72373. /**
  72374. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72375. */
  72376. _this.radius = 0.0001;
  72377. /**
  72378. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72379. * Must not be equal to fallOff and superior to fallOff.
  72380. * Default value is 0.975
  72381. */
  72382. _this.area = 0.0075;
  72383. /**
  72384. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72385. * Must not be equal to area and inferior to area.
  72386. * Default value is 0.0
  72387. */
  72388. _this.fallOff = 0.000001;
  72389. /**
  72390. * The base color of the SSAO post-process
  72391. * The final result is "base + ssao" between [0, 1]
  72392. */
  72393. _this.base = 0.5;
  72394. _this._firstUpdate = true;
  72395. _this._scene = scene;
  72396. // Set up assets
  72397. _this._createRandomTexture();
  72398. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72399. var ssaoRatio = ratio.ssaoRatio || ratio;
  72400. var combineRatio = ratio.combineRatio || ratio;
  72401. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72402. _this._createSSAOPostProcess(ssaoRatio);
  72403. _this._createBlurPostProcess(ssaoRatio);
  72404. _this._createSSAOCombinePostProcess(combineRatio);
  72405. // Set up pipeline
  72406. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72407. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72408. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72409. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72410. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72411. // Finish
  72412. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72413. if (cameras)
  72414. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72415. return _this;
  72416. }
  72417. // Public Methods
  72418. /**
  72419. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72420. */
  72421. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72422. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72423. for (var i = 0; i < this._scene.cameras.length; i++) {
  72424. var camera = this._scene.cameras[i];
  72425. this._originalColorPostProcess.dispose(camera);
  72426. this._ssaoPostProcess.dispose(camera);
  72427. this._blurHPostProcess.dispose(camera);
  72428. this._blurVPostProcess.dispose(camera);
  72429. this._ssaoCombinePostProcess.dispose(camera);
  72430. }
  72431. this._randomTexture.dispose();
  72432. if (disableDepthRender)
  72433. this._scene.disableDepthRenderer();
  72434. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72435. _super.prototype.dispose.call(this);
  72436. };
  72437. // Private Methods
  72438. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72439. var _this = this;
  72440. var size = 16;
  72441. 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);
  72442. 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);
  72443. this._blurHPostProcess.onActivateObservable.add(function () {
  72444. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72445. _this._blurHPostProcess.kernel = size * dw;
  72446. });
  72447. this._blurVPostProcess.onActivateObservable.add(function () {
  72448. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72449. _this._blurVPostProcess.kernel = size * dw;
  72450. });
  72451. };
  72452. SSAORenderingPipeline.prototype._rebuild = function () {
  72453. this._firstUpdate = true;
  72454. _super.prototype._rebuild.call(this);
  72455. };
  72456. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72457. var _this = this;
  72458. var numSamples = 16;
  72459. var sampleSphere = [
  72460. 0.5381, 0.1856, -0.4319,
  72461. 0.1379, 0.2486, 0.4430,
  72462. 0.3371, 0.5679, -0.0057,
  72463. -0.6999, -0.0451, -0.0019,
  72464. 0.0689, -0.1598, -0.8547,
  72465. 0.0560, 0.0069, -0.1843,
  72466. -0.0146, 0.1402, 0.0762,
  72467. 0.0100, -0.1924, -0.0344,
  72468. -0.3577, -0.5301, -0.4358,
  72469. -0.3169, 0.1063, 0.0158,
  72470. 0.0103, -0.5869, 0.0046,
  72471. -0.0897, -0.4940, 0.3287,
  72472. 0.7119, -0.0154, -0.0918,
  72473. -0.0533, 0.0596, -0.5411,
  72474. 0.0352, -0.0631, 0.5460,
  72475. -0.4776, 0.2847, -0.0271
  72476. ];
  72477. var samplesFactor = 1.0 / numSamples;
  72478. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72479. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72480. "area", "fallOff", "base", "range", "viewport"
  72481. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72482. this._ssaoPostProcess.onApply = function (effect) {
  72483. if (_this._firstUpdate) {
  72484. effect.setArray3("sampleSphere", sampleSphere);
  72485. effect.setFloat("samplesFactor", samplesFactor);
  72486. effect.setFloat("randTextureTiles", 4.0);
  72487. }
  72488. effect.setFloat("totalStrength", _this.totalStrength);
  72489. effect.setFloat("radius", _this.radius);
  72490. effect.setFloat("area", _this.area);
  72491. effect.setFloat("fallOff", _this.fallOff);
  72492. effect.setFloat("base", _this.base);
  72493. effect.setTexture("textureSampler", _this._depthTexture);
  72494. effect.setTexture("randomSampler", _this._randomTexture);
  72495. };
  72496. };
  72497. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72498. var _this = this;
  72499. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72500. this._ssaoCombinePostProcess.onApply = function (effect) {
  72501. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72502. };
  72503. };
  72504. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  72505. var size = 512;
  72506. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72507. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72508. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72509. var context = this._randomTexture.getContext();
  72510. var rand = function (min, max) {
  72511. return Math.random() * (max - min) + min;
  72512. };
  72513. var randVector = BABYLON.Vector3.Zero();
  72514. for (var x = 0; x < size; x++) {
  72515. for (var y = 0; y < size; y++) {
  72516. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  72517. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  72518. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  72519. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72520. context.fillRect(x, y, 1, 1);
  72521. }
  72522. }
  72523. this._randomTexture.update(false);
  72524. };
  72525. __decorate([
  72526. BABYLON.serialize()
  72527. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  72528. __decorate([
  72529. BABYLON.serialize()
  72530. ], SSAORenderingPipeline.prototype, "radius", void 0);
  72531. __decorate([
  72532. BABYLON.serialize()
  72533. ], SSAORenderingPipeline.prototype, "area", void 0);
  72534. __decorate([
  72535. BABYLON.serialize()
  72536. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  72537. __decorate([
  72538. BABYLON.serialize()
  72539. ], SSAORenderingPipeline.prototype, "base", void 0);
  72540. return SSAORenderingPipeline;
  72541. }(BABYLON.PostProcessRenderPipeline));
  72542. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  72543. })(BABYLON || (BABYLON = {}));
  72544. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  72545. var BABYLON;
  72546. (function (BABYLON) {
  72547. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  72548. __extends(SSAO2RenderingPipeline, _super);
  72549. /**
  72550. * @constructor
  72551. * @param {string} name - The rendering pipeline name
  72552. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72553. * @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 }
  72554. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72555. */
  72556. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  72557. var _this = _super.call(this, scene.getEngine(), name) || this;
  72558. // Members
  72559. /**
  72560. * The PassPostProcess id in the pipeline that contains the original scene color
  72561. */
  72562. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72563. /**
  72564. * The SSAO PostProcess id in the pipeline
  72565. */
  72566. _this.SSAORenderEffect = "SSAORenderEffect";
  72567. /**
  72568. * The horizontal blur PostProcess id in the pipeline
  72569. */
  72570. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72571. /**
  72572. * The vertical blur PostProcess id in the pipeline
  72573. */
  72574. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72575. /**
  72576. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72577. */
  72578. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72579. /**
  72580. * The output strength of the SSAO post-process. Default value is 1.0.
  72581. */
  72582. _this.totalStrength = 1.0;
  72583. /**
  72584. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  72585. */
  72586. _this.maxZ = 100.0;
  72587. /**
  72588. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  72589. */
  72590. _this.minZAspect = 0.2;
  72591. /**
  72592. * Number of samples used for the SSAO calculations. Default value is 8
  72593. */
  72594. _this._samples = 8;
  72595. /**
  72596. * Are we using bilateral blur ?
  72597. */
  72598. _this._expensiveBlur = true;
  72599. /**
  72600. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  72601. */
  72602. _this.radius = 2.0;
  72603. /**
  72604. * The base color of the SSAO post-process
  72605. * The final result is "base + ssao" between [0, 1]
  72606. */
  72607. _this.base = 0.1;
  72608. _this._firstUpdate = true;
  72609. _this._scene = scene;
  72610. if (!_this.isSupported) {
  72611. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  72612. return _this;
  72613. }
  72614. var ssaoRatio = ratio.ssaoRatio || ratio;
  72615. var blurRatio = ratio.blurRatio || ratio;
  72616. // Set up assets
  72617. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  72618. _this._createRandomTexture();
  72619. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  72620. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  72621. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72622. _this._createSSAOPostProcess(1.0);
  72623. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  72624. _this._createSSAOCombinePostProcess(blurRatio);
  72625. // Set up pipeline
  72626. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72627. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72628. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72629. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72630. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72631. // Finish
  72632. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72633. if (cameras)
  72634. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72635. return _this;
  72636. }
  72637. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  72638. get: function () {
  72639. return this._samples;
  72640. },
  72641. set: function (n) {
  72642. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  72643. this._samples = n;
  72644. this._sampleSphere = this._generateHemisphere();
  72645. this._firstUpdate = true;
  72646. },
  72647. enumerable: true,
  72648. configurable: true
  72649. });
  72650. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  72651. get: function () {
  72652. return this._expensiveBlur;
  72653. },
  72654. set: function (b) {
  72655. 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"]);
  72656. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  72657. this._expensiveBlur = b;
  72658. this._firstUpdate = true;
  72659. },
  72660. enumerable: true,
  72661. configurable: true
  72662. });
  72663. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  72664. /**
  72665. * Support test.
  72666. */
  72667. get: function () {
  72668. var engine = BABYLON.Engine.LastCreatedEngine;
  72669. if (!engine) {
  72670. return false;
  72671. }
  72672. return engine.getCaps().drawBuffersExtension;
  72673. },
  72674. enumerable: true,
  72675. configurable: true
  72676. });
  72677. // Public Methods
  72678. /**
  72679. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72680. */
  72681. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  72682. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  72683. for (var i = 0; i < this._scene.cameras.length; i++) {
  72684. var camera = this._scene.cameras[i];
  72685. this._originalColorPostProcess.dispose(camera);
  72686. this._ssaoPostProcess.dispose(camera);
  72687. this._blurHPostProcess.dispose(camera);
  72688. this._blurVPostProcess.dispose(camera);
  72689. this._ssaoCombinePostProcess.dispose(camera);
  72690. }
  72691. this._randomTexture.dispose();
  72692. if (disableGeometryBufferRenderer)
  72693. this._scene.disableGeometryBufferRenderer();
  72694. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72695. _super.prototype.dispose.call(this);
  72696. };
  72697. // Private Methods
  72698. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  72699. var _this = this;
  72700. this._samplerOffsets = [];
  72701. var expensive = this.expensiveBlur;
  72702. for (var i = -8; i < 8; i++) {
  72703. this._samplerOffsets.push(i * 2 + 0.5);
  72704. }
  72705. 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");
  72706. this._blurHPostProcess.onApply = function (effect) {
  72707. if (!_this._scene.activeCamera) {
  72708. return;
  72709. }
  72710. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  72711. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72712. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72713. effect.setFloat("radius", _this.radius);
  72714. effect.setTexture("depthSampler", _this._depthTexture);
  72715. if (_this._firstUpdate) {
  72716. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72717. }
  72718. };
  72719. 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");
  72720. this._blurVPostProcess.onApply = function (effect) {
  72721. if (!_this._scene.activeCamera) {
  72722. return;
  72723. }
  72724. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  72725. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72726. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72727. effect.setFloat("radius", _this.radius);
  72728. effect.setTexture("depthSampler", _this._depthTexture);
  72729. if (_this._firstUpdate) {
  72730. effect.setArray("samplerOffsets", _this._samplerOffsets);
  72731. _this._firstUpdate = false;
  72732. }
  72733. };
  72734. };
  72735. SSAO2RenderingPipeline.prototype._rebuild = function () {
  72736. this._firstUpdate = true;
  72737. _super.prototype._rebuild.call(this);
  72738. };
  72739. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  72740. var numSamples = this.samples;
  72741. var result = [];
  72742. var vector, scale;
  72743. var rand = function (min, max) {
  72744. return Math.random() * (max - min) + min;
  72745. };
  72746. var i = 0;
  72747. while (i < numSamples) {
  72748. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  72749. vector.normalize();
  72750. scale = i / numSamples;
  72751. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  72752. vector.scaleInPlace(scale);
  72753. result.push(vector.x, vector.y, vector.z);
  72754. i++;
  72755. }
  72756. return result;
  72757. };
  72758. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72759. var _this = this;
  72760. var numSamples = this.samples;
  72761. this._sampleSphere = this._generateHemisphere();
  72762. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  72763. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72764. "base", "range", "projection", "near", "far", "texelSize",
  72765. "xViewport", "yViewport", "maxZ", "minZAspect"
  72766. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72767. this._ssaoPostProcess.onApply = function (effect) {
  72768. if (_this._firstUpdate) {
  72769. effect.setArray3("sampleSphere", _this._sampleSphere);
  72770. effect.setFloat("randTextureTiles", 4.0);
  72771. }
  72772. if (!_this._scene.activeCamera) {
  72773. return;
  72774. }
  72775. effect.setFloat("samplesFactor", 1 / _this.samples);
  72776. effect.setFloat("totalStrength", _this.totalStrength);
  72777. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  72778. effect.setFloat("radius", _this.radius);
  72779. effect.setFloat("maxZ", _this.maxZ);
  72780. effect.setFloat("minZAspect", _this.minZAspect);
  72781. effect.setFloat("base", _this.base);
  72782. effect.setFloat("near", _this._scene.activeCamera.minZ);
  72783. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  72784. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  72785. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  72786. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  72787. effect.setTexture("textureSampler", _this._depthTexture);
  72788. effect.setTexture("normalSampler", _this._normalTexture);
  72789. effect.setTexture("randomSampler", _this._randomTexture);
  72790. };
  72791. };
  72792. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72793. var _this = this;
  72794. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72795. this._ssaoCombinePostProcess.onApply = function (effect) {
  72796. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  72797. };
  72798. };
  72799. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  72800. var size = 512;
  72801. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  72802. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  72803. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  72804. var context = this._randomTexture.getContext();
  72805. var rand = function (min, max) {
  72806. return Math.random() * (max - min) + min;
  72807. };
  72808. var randVector = BABYLON.Vector3.Zero();
  72809. for (var x = 0; x < size; x++) {
  72810. for (var y = 0; y < size; y++) {
  72811. randVector.x = rand(0.0, 1.0);
  72812. randVector.y = rand(0.0, 1.0);
  72813. randVector.z = 0.0;
  72814. randVector.normalize();
  72815. randVector.scaleInPlace(255);
  72816. randVector.x = Math.floor(randVector.x);
  72817. randVector.y = Math.floor(randVector.y);
  72818. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  72819. context.fillRect(x, y, 1, 1);
  72820. }
  72821. }
  72822. this._randomTexture.update(false);
  72823. };
  72824. __decorate([
  72825. BABYLON.serialize()
  72826. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  72827. __decorate([
  72828. BABYLON.serialize()
  72829. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  72830. __decorate([
  72831. BABYLON.serialize()
  72832. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  72833. __decorate([
  72834. BABYLON.serialize("samples")
  72835. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  72836. __decorate([
  72837. BABYLON.serialize("expensiveBlur")
  72838. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  72839. __decorate([
  72840. BABYLON.serialize()
  72841. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  72842. __decorate([
  72843. BABYLON.serialize()
  72844. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  72845. return SSAO2RenderingPipeline;
  72846. }(BABYLON.PostProcessRenderPipeline));
  72847. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  72848. })(BABYLON || (BABYLON = {}));
  72849. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  72850. // BABYLON.JS Chromatic Aberration GLSL Shader
  72851. // Author: Olivier Guyot
  72852. // Separates very slightly R, G and B colors on the edges of the screen
  72853. // Inspired by Francois Tarlier & Martins Upitis
  72854. var BABYLON;
  72855. (function (BABYLON) {
  72856. var LensRenderingPipeline = /** @class */ (function (_super) {
  72857. __extends(LensRenderingPipeline, _super);
  72858. /**
  72859. * @constructor
  72860. *
  72861. * Effect parameters are as follow:
  72862. * {
  72863. * chromatic_aberration: number; // from 0 to x (1 for realism)
  72864. * edge_blur: number; // from 0 to x (1 for realism)
  72865. * distortion: number; // from 0 to x (1 for realism)
  72866. * grain_amount: number; // from 0 to 1
  72867. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  72868. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  72869. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  72870. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  72871. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  72872. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  72873. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  72874. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  72875. * }
  72876. * Note: if an effect parameter is unset, effect is disabled
  72877. *
  72878. * @param {string} name - The rendering pipeline name
  72879. * @param {object} parameters - An object containing all parameters (see above)
  72880. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72881. * @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)
  72882. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72883. */
  72884. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  72885. if (ratio === void 0) { ratio = 1.0; }
  72886. var _this = _super.call(this, scene.getEngine(), name) || this;
  72887. // Lens effects can be of the following:
  72888. // - chromatic aberration (slight shift of RGB colors)
  72889. // - blur on the edge of the lens
  72890. // - lens distortion
  72891. // - depth-of-field blur & highlights enhancing
  72892. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  72893. // - grain effect (noise or custom texture)
  72894. // Two additional texture samplers are needed:
  72895. // - depth map (for depth-of-field)
  72896. // - grain texture
  72897. /**
  72898. * The chromatic aberration PostProcess id in the pipeline
  72899. */
  72900. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  72901. /**
  72902. * The highlights enhancing PostProcess id in the pipeline
  72903. */
  72904. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  72905. /**
  72906. * The depth-of-field PostProcess id in the pipeline
  72907. */
  72908. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  72909. _this._scene = scene;
  72910. // Fetch texture samplers
  72911. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72912. if (parameters.grain_texture) {
  72913. _this._grainTexture = parameters.grain_texture;
  72914. }
  72915. else {
  72916. _this._createGrainTexture();
  72917. }
  72918. // save parameters
  72919. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  72920. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  72921. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  72922. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  72923. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  72924. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  72925. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  72926. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  72927. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  72928. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  72929. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  72930. // Create effects
  72931. _this._createChromaticAberrationPostProcess(ratio);
  72932. _this._createHighlightsPostProcess(ratio);
  72933. _this._createDepthOfFieldPostProcess(ratio / 4);
  72934. // Set up pipeline
  72935. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  72936. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  72937. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  72938. if (_this._highlightsGain === -1) {
  72939. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  72940. }
  72941. // Finish
  72942. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72943. if (cameras) {
  72944. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72945. }
  72946. return _this;
  72947. }
  72948. // public methods (self explanatory)
  72949. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  72950. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  72951. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  72952. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  72953. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  72954. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  72955. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  72956. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  72957. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  72958. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  72959. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  72960. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  72961. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  72962. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  72963. };
  72964. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  72965. this._highlightsPostProcess.updateEffect();
  72966. };
  72967. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  72968. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  72969. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  72970. this._highlightsGain = amount;
  72971. };
  72972. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  72973. if (this._highlightsGain === -1) {
  72974. this._highlightsGain = 1.0;
  72975. }
  72976. this._highlightsThreshold = amount;
  72977. };
  72978. LensRenderingPipeline.prototype.disableHighlights = function () {
  72979. this._highlightsGain = -1;
  72980. };
  72981. /**
  72982. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  72983. */
  72984. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72985. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72986. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72987. this._chromaticAberrationPostProcess = null;
  72988. this._highlightsPostProcess = null;
  72989. this._depthOfFieldPostProcess = null;
  72990. this._grainTexture.dispose();
  72991. if (disableDepthRender)
  72992. this._scene.disableDepthRenderer();
  72993. };
  72994. // colors shifting and distortion
  72995. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  72996. var _this = this;
  72997. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  72998. [], // samplers
  72999. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73000. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73001. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73002. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73003. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73004. effect.setFloat('radialIntensity', 1);
  73005. effect.setFloat2('direction', 17, 17);
  73006. effect.setFloat2('centerPosition', 0.5, 0.5);
  73007. };
  73008. };
  73009. // highlights enhancing
  73010. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73011. var _this = this;
  73012. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73013. [], // samplers
  73014. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73015. this._highlightsPostProcess.onApply = function (effect) {
  73016. effect.setFloat('gain', _this._highlightsGain);
  73017. effect.setFloat('threshold', _this._highlightsThreshold);
  73018. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73019. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73020. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73021. };
  73022. };
  73023. // colors shifting and distortion
  73024. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73025. var _this = this;
  73026. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73027. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73028. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73029. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73030. this._depthOfFieldPostProcess.onApply = function (effect) {
  73031. effect.setTexture("depthSampler", _this._depthTexture);
  73032. effect.setTexture("grainSampler", _this._grainTexture);
  73033. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73034. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73035. effect.setFloat('grain_amount', _this._grainAmount);
  73036. effect.setBool('blur_noise', _this._blurNoise);
  73037. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73038. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73039. effect.setFloat('distortion', _this._distortion);
  73040. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73041. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73042. effect.setFloat('aperture', _this._dofAperture);
  73043. effect.setFloat('darken', _this._dofDarken);
  73044. effect.setFloat('edge_blur', _this._edgeBlur);
  73045. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73046. if (_this._scene.activeCamera) {
  73047. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73048. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73049. }
  73050. };
  73051. };
  73052. // creates a black and white random noise texture, 512x512
  73053. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73054. var size = 512;
  73055. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73056. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73057. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73058. var context = this._grainTexture.getContext();
  73059. var rand = function (min, max) {
  73060. return Math.random() * (max - min) + min;
  73061. };
  73062. var value;
  73063. for (var x = 0; x < size; x++) {
  73064. for (var y = 0; y < size; y++) {
  73065. value = Math.floor(rand(0.42, 0.58) * 255);
  73066. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73067. context.fillRect(x, y, 1, 1);
  73068. }
  73069. }
  73070. this._grainTexture.update(false);
  73071. };
  73072. return LensRenderingPipeline;
  73073. }(BABYLON.PostProcessRenderPipeline));
  73074. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73075. })(BABYLON || (BABYLON = {}));
  73076. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73077. var BABYLON;
  73078. (function (BABYLON) {
  73079. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73080. __extends(StandardRenderingPipeline, _super);
  73081. /**
  73082. * @constructor
  73083. * @param {string} name - The rendering pipeline name
  73084. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73085. * @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)
  73086. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73087. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73088. */
  73089. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73090. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73091. var _this = _super.call(this, scene.getEngine(), name) || this;
  73092. _this.downSampleX4PostProcess = null;
  73093. _this.brightPassPostProcess = null;
  73094. _this.blurHPostProcesses = [];
  73095. _this.blurVPostProcesses = [];
  73096. _this.textureAdderPostProcess = null;
  73097. _this.volumetricLightPostProcess = null;
  73098. _this.volumetricLightSmoothXPostProcess = null;
  73099. _this.volumetricLightSmoothYPostProcess = null;
  73100. _this.volumetricLightMergePostProces = null;
  73101. _this.volumetricLightFinalPostProcess = null;
  73102. _this.luminancePostProcess = null;
  73103. _this.luminanceDownSamplePostProcesses = [];
  73104. _this.hdrPostProcess = null;
  73105. _this.textureAdderFinalPostProcess = null;
  73106. _this.lensFlareFinalPostProcess = null;
  73107. _this.hdrFinalPostProcess = null;
  73108. _this.lensFlarePostProcess = null;
  73109. _this.lensFlareComposePostProcess = null;
  73110. _this.motionBlurPostProcess = null;
  73111. _this.depthOfFieldPostProcess = null;
  73112. // Values
  73113. _this.brightThreshold = 1.0;
  73114. _this.blurWidth = 512.0;
  73115. _this.horizontalBlur = false;
  73116. _this.exposure = 1.0;
  73117. _this.lensTexture = null;
  73118. _this.volumetricLightCoefficient = 0.2;
  73119. _this.volumetricLightPower = 4.0;
  73120. _this.volumetricLightBlurScale = 64.0;
  73121. _this.sourceLight = null;
  73122. _this.hdrMinimumLuminance = 1.0;
  73123. _this.hdrDecreaseRate = 0.5;
  73124. _this.hdrIncreaseRate = 0.5;
  73125. _this.lensColorTexture = null;
  73126. _this.lensFlareStrength = 20.0;
  73127. _this.lensFlareGhostDispersal = 1.4;
  73128. _this.lensFlareHaloWidth = 0.7;
  73129. _this.lensFlareDistortionStrength = 16.0;
  73130. _this.lensStarTexture = null;
  73131. _this.lensFlareDirtTexture = null;
  73132. _this.depthOfFieldDistance = 10.0;
  73133. _this.depthOfFieldBlurWidth = 64.0;
  73134. _this.motionStrength = 1.0;
  73135. // IAnimatable
  73136. _this.animations = [];
  73137. _this._currentDepthOfFieldSource = null;
  73138. _this._hdrCurrentLuminance = 1.0;
  73139. // Getters and setters
  73140. _this._bloomEnabled = true;
  73141. _this._depthOfFieldEnabled = false;
  73142. _this._vlsEnabled = false;
  73143. _this._lensFlareEnabled = false;
  73144. _this._hdrEnabled = false;
  73145. _this._motionBlurEnabled = false;
  73146. _this._motionBlurSamples = 64.0;
  73147. _this._volumetricLightStepsCount = 50.0;
  73148. _this._cameras = cameras || [];
  73149. // Initialize
  73150. _this._scene = scene;
  73151. _this._basePostProcess = originalPostProcess;
  73152. _this._ratio = ratio;
  73153. // Misc
  73154. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73155. // Finish
  73156. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73157. _this._buildPipeline();
  73158. return _this;
  73159. }
  73160. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73161. get: function () {
  73162. return this._bloomEnabled;
  73163. },
  73164. set: function (enabled) {
  73165. if (this._bloomEnabled === enabled) {
  73166. return;
  73167. }
  73168. this._bloomEnabled = enabled;
  73169. this._buildPipeline();
  73170. },
  73171. enumerable: true,
  73172. configurable: true
  73173. });
  73174. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73175. get: function () {
  73176. return this._depthOfFieldEnabled;
  73177. },
  73178. set: function (enabled) {
  73179. if (this._depthOfFieldEnabled === enabled) {
  73180. return;
  73181. }
  73182. this._depthOfFieldEnabled = enabled;
  73183. this._buildPipeline();
  73184. },
  73185. enumerable: true,
  73186. configurable: true
  73187. });
  73188. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73189. get: function () {
  73190. return this._lensFlareEnabled;
  73191. },
  73192. set: function (enabled) {
  73193. if (this._lensFlareEnabled === enabled) {
  73194. return;
  73195. }
  73196. this._lensFlareEnabled = enabled;
  73197. this._buildPipeline();
  73198. },
  73199. enumerable: true,
  73200. configurable: true
  73201. });
  73202. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73203. get: function () {
  73204. return this._hdrEnabled;
  73205. },
  73206. set: function (enabled) {
  73207. if (this._hdrEnabled === enabled) {
  73208. return;
  73209. }
  73210. this._hdrEnabled = enabled;
  73211. this._buildPipeline();
  73212. },
  73213. enumerable: true,
  73214. configurable: true
  73215. });
  73216. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73217. get: function () {
  73218. return this._vlsEnabled;
  73219. },
  73220. set: function (enabled) {
  73221. if (this._vlsEnabled === enabled) {
  73222. return;
  73223. }
  73224. if (enabled) {
  73225. var geometry = this._scene.enableGeometryBufferRenderer();
  73226. if (!geometry) {
  73227. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73228. return;
  73229. }
  73230. }
  73231. this._vlsEnabled = enabled;
  73232. this._buildPipeline();
  73233. },
  73234. enumerable: true,
  73235. configurable: true
  73236. });
  73237. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73238. get: function () {
  73239. return this._motionBlurEnabled;
  73240. },
  73241. set: function (enabled) {
  73242. if (this._motionBlurEnabled === enabled) {
  73243. return;
  73244. }
  73245. this._motionBlurEnabled = enabled;
  73246. this._buildPipeline();
  73247. },
  73248. enumerable: true,
  73249. configurable: true
  73250. });
  73251. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73252. get: function () {
  73253. return this._volumetricLightStepsCount;
  73254. },
  73255. set: function (count) {
  73256. if (this.volumetricLightPostProcess) {
  73257. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73258. }
  73259. this._volumetricLightStepsCount = count;
  73260. },
  73261. enumerable: true,
  73262. configurable: true
  73263. });
  73264. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73265. get: function () {
  73266. return this._motionBlurSamples;
  73267. },
  73268. set: function (samples) {
  73269. if (this.motionBlurPostProcess) {
  73270. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73271. }
  73272. this._motionBlurSamples = samples;
  73273. },
  73274. enumerable: true,
  73275. configurable: true
  73276. });
  73277. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73278. var _this = this;
  73279. var ratio = this._ratio;
  73280. var scene = this._scene;
  73281. this._disposePostProcesses();
  73282. this._reset();
  73283. // Create pass post-process
  73284. if (!this._basePostProcess) {
  73285. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73286. this.originalPostProcess.onApply = function (effect) {
  73287. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73288. };
  73289. }
  73290. else {
  73291. this.originalPostProcess = this._basePostProcess;
  73292. }
  73293. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73294. this._currentDepthOfFieldSource = this.originalPostProcess;
  73295. if (this._vlsEnabled) {
  73296. // Create volumetric light
  73297. this._createVolumetricLightPostProcess(scene, ratio);
  73298. // Create volumetric light final post-process
  73299. 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);
  73300. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73301. }
  73302. if (this._bloomEnabled) {
  73303. // Create down sample X4 post-process
  73304. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73305. // Create bright pass post-process
  73306. this._createBrightPassPostProcess(scene, ratio / 2);
  73307. // Create gaussian blur post-processes (down sampling blurs)
  73308. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73309. // Create texture adder post-process
  73310. this._createTextureAdderPostProcess(scene, ratio);
  73311. // Create depth-of-field source post-process
  73312. 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);
  73313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73314. }
  73315. if (this._lensFlareEnabled) {
  73316. // Create lens flare post-process
  73317. this._createLensFlarePostProcess(scene, ratio);
  73318. // Create depth-of-field source post-process post lens-flare and disable it now
  73319. 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);
  73320. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73321. }
  73322. if (this._hdrEnabled) {
  73323. // Create luminance
  73324. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73325. // Create HDR
  73326. this._createHdrPostProcess(scene, ratio);
  73327. // Create depth-of-field source post-process post hdr and disable it now
  73328. 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);
  73329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73330. }
  73331. if (this._depthOfFieldEnabled) {
  73332. // Create gaussian blur used by depth-of-field
  73333. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73334. // Create depth-of-field post-process
  73335. this._createDepthOfFieldPostProcess(scene, ratio);
  73336. }
  73337. if (this._motionBlurEnabled) {
  73338. // Create motion blur post-process
  73339. this._createMotionBlurPostProcess(scene, ratio);
  73340. }
  73341. if (this._cameras !== null) {
  73342. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73343. }
  73344. };
  73345. // Down Sample X4 Post-Processs
  73346. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73347. var _this = this;
  73348. var downSampleX4Offsets = new Array(32);
  73349. 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);
  73350. this.downSampleX4PostProcess.onApply = function (effect) {
  73351. var id = 0;
  73352. var width = _this.downSampleX4PostProcess.width;
  73353. var height = _this.downSampleX4PostProcess.height;
  73354. for (var i = -2; i < 2; i++) {
  73355. for (var j = -2; j < 2; j++) {
  73356. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73357. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73358. id += 2;
  73359. }
  73360. }
  73361. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73362. };
  73363. // Add to pipeline
  73364. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73365. };
  73366. // Brightpass Post-Process
  73367. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73368. var _this = this;
  73369. var brightOffsets = new Array(8);
  73370. 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);
  73371. this.brightPassPostProcess.onApply = function (effect) {
  73372. var sU = (1.0 / _this.brightPassPostProcess.width);
  73373. var sV = (1.0 / _this.brightPassPostProcess.height);
  73374. brightOffsets[0] = -0.5 * sU;
  73375. brightOffsets[1] = 0.5 * sV;
  73376. brightOffsets[2] = 0.5 * sU;
  73377. brightOffsets[3] = 0.5 * sV;
  73378. brightOffsets[4] = -0.5 * sU;
  73379. brightOffsets[5] = -0.5 * sV;
  73380. brightOffsets[6] = 0.5 * sU;
  73381. brightOffsets[7] = -0.5 * sV;
  73382. effect.setArray2("dsOffsets", brightOffsets);
  73383. effect.setFloat("brightThreshold", _this.brightThreshold);
  73384. };
  73385. // Add to pipeline
  73386. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73387. };
  73388. // Create blur H&V post-processes
  73389. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73390. var _this = this;
  73391. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73392. var engine = scene.getEngine();
  73393. 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);
  73394. 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);
  73395. blurX.onActivateObservable.add(function () {
  73396. var dw = blurX.width / engine.getRenderWidth();
  73397. blurX.kernel = _this[blurWidthKey] * dw;
  73398. });
  73399. blurY.onActivateObservable.add(function () {
  73400. var dw = blurY.height / engine.getRenderHeight();
  73401. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73402. });
  73403. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73404. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73405. this.blurHPostProcesses.push(blurX);
  73406. this.blurVPostProcesses.push(blurY);
  73407. };
  73408. // Create texture adder post-process
  73409. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73410. var _this = this;
  73411. 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);
  73412. this.textureAdderPostProcess.onApply = function (effect) {
  73413. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73414. effect.setTexture("lensSampler", _this.lensTexture);
  73415. effect.setFloat("exposure", _this.exposure);
  73416. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73417. };
  73418. // Add to pipeline
  73419. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73420. };
  73421. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73422. var _this = this;
  73423. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73424. geometryRenderer.enablePosition = true;
  73425. var geometry = geometryRenderer.getGBuffer();
  73426. // Base post-process
  73427. 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));
  73428. var depthValues = BABYLON.Vector2.Zero();
  73429. this.volumetricLightPostProcess.onApply = function (effect) {
  73430. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73431. var generator = _this.sourceLight.getShadowGenerator();
  73432. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73433. effect.setTexture("positionSampler", geometry.textures[2]);
  73434. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73435. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73436. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73437. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73438. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73439. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73440. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73441. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73442. effect.setVector2("depthValues", depthValues);
  73443. }
  73444. };
  73445. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73446. // Smooth
  73447. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73448. // Merge
  73449. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73450. this.volumetricLightMergePostProces.onApply = function (effect) {
  73451. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  73452. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73453. };
  73454. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73455. };
  73456. // Create luminance
  73457. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73458. var _this = this;
  73459. // Create luminance
  73460. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73461. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73462. var offsets = [];
  73463. this.luminancePostProcess.onApply = function (effect) {
  73464. var sU = (1.0 / _this.luminancePostProcess.width);
  73465. var sV = (1.0 / _this.luminancePostProcess.height);
  73466. offsets[0] = -0.5 * sU;
  73467. offsets[1] = 0.5 * sV;
  73468. offsets[2] = 0.5 * sU;
  73469. offsets[3] = 0.5 * sV;
  73470. offsets[4] = -0.5 * sU;
  73471. offsets[5] = -0.5 * sV;
  73472. offsets[6] = 0.5 * sU;
  73473. offsets[7] = -0.5 * sV;
  73474. effect.setArray2("lumOffsets", offsets);
  73475. };
  73476. // Add to pipeline
  73477. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73478. // Create down sample luminance
  73479. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  73480. var size = Math.pow(3, i);
  73481. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  73482. if (i === 0) {
  73483. defines += "#define FINAL_DOWN_SAMPLER";
  73484. }
  73485. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  73486. this.luminanceDownSamplePostProcesses.push(postProcess);
  73487. }
  73488. // Create callbacks and add effects
  73489. var lastLuminance = this.luminancePostProcess;
  73490. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  73491. var downSampleOffsets = new Array(18);
  73492. pp.onApply = function (effect) {
  73493. if (!lastLuminance) {
  73494. return;
  73495. }
  73496. var id = 0;
  73497. for (var x = -1; x < 2; x++) {
  73498. for (var y = -1; y < 2; y++) {
  73499. downSampleOffsets[id] = x / lastLuminance.width;
  73500. downSampleOffsets[id + 1] = y / lastLuminance.height;
  73501. id += 2;
  73502. }
  73503. }
  73504. effect.setArray2("dsOffsets", downSampleOffsets);
  73505. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  73506. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73507. lastLuminance = _this.luminancePostProcess;
  73508. }
  73509. else {
  73510. lastLuminance = pp;
  73511. }
  73512. };
  73513. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  73514. pp.onAfterRender = function (effect) {
  73515. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  73516. 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);
  73517. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  73518. };
  73519. }
  73520. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  73521. });
  73522. };
  73523. // Create HDR post-process
  73524. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  73525. var _this = this;
  73526. 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);
  73527. var outputLiminance = 1;
  73528. var time = 0;
  73529. var lastTime = 0;
  73530. this.hdrPostProcess.onApply = function (effect) {
  73531. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  73532. time += scene.getEngine().getDeltaTime();
  73533. if (outputLiminance < 0) {
  73534. outputLiminance = _this._hdrCurrentLuminance;
  73535. }
  73536. else {
  73537. var dt = (lastTime - time) / 1000.0;
  73538. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  73539. outputLiminance += _this.hdrDecreaseRate * dt;
  73540. }
  73541. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  73542. outputLiminance -= _this.hdrIncreaseRate * dt;
  73543. }
  73544. else {
  73545. outputLiminance = _this._hdrCurrentLuminance;
  73546. }
  73547. }
  73548. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  73549. effect.setFloat("averageLuminance", outputLiminance);
  73550. lastTime = time;
  73551. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  73552. };
  73553. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  73554. };
  73555. // Create lens flare post-process
  73556. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  73557. var _this = this;
  73558. 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);
  73559. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  73560. this._createBlurPostProcesses(scene, ratio / 4, 2);
  73561. 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);
  73562. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  73563. var resolution = new BABYLON.Vector2(0, 0);
  73564. // Lens flare
  73565. this.lensFlarePostProcess.onApply = function (effect) {
  73566. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  73567. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  73568. effect.setFloat("strength", _this.lensFlareStrength);
  73569. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  73570. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  73571. // Shift
  73572. resolution.x = _this.lensFlarePostProcess.width;
  73573. resolution.y = _this.lensFlarePostProcess.height;
  73574. effect.setVector2("resolution", resolution);
  73575. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  73576. };
  73577. // Compose
  73578. 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);
  73579. 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);
  73580. this.lensFlareComposePostProcess.onApply = function (effect) {
  73581. if (!_this._scene.activeCamera) {
  73582. return;
  73583. }
  73584. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73585. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  73586. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  73587. // Lens start rotation matrix
  73588. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  73589. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  73590. 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));
  73591. camRot *= 4.0;
  73592. 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);
  73593. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  73594. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  73595. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  73596. };
  73597. };
  73598. // Create depth-of-field post-process
  73599. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  73600. var _this = this;
  73601. 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);
  73602. this.depthOfFieldPostProcess.onApply = function (effect) {
  73603. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  73604. effect.setTexture("depthSampler", _this._getDepthTexture());
  73605. effect.setFloat("distance", _this.depthOfFieldDistance);
  73606. };
  73607. // Add to pipeline
  73608. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  73609. };
  73610. // Create motion blur post-process
  73611. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  73612. var _this = this;
  73613. 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);
  73614. var motionScale = 0;
  73615. var prevViewProjection = BABYLON.Matrix.Identity();
  73616. var invViewProjection = BABYLON.Matrix.Identity();
  73617. var viewProjection = BABYLON.Matrix.Identity();
  73618. var screenSize = BABYLON.Vector2.Zero();
  73619. this.motionBlurPostProcess.onApply = function (effect) {
  73620. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  73621. viewProjection.invertToRef(invViewProjection);
  73622. effect.setMatrix("inverseViewProjection", invViewProjection);
  73623. effect.setMatrix("prevViewProjection", prevViewProjection);
  73624. prevViewProjection = viewProjection;
  73625. screenSize.x = _this.motionBlurPostProcess.width;
  73626. screenSize.y = _this.motionBlurPostProcess.height;
  73627. effect.setVector2("screenSize", screenSize);
  73628. motionScale = scene.getEngine().getFps() / 60.0;
  73629. effect.setFloat("motionScale", motionScale);
  73630. effect.setFloat("motionStrength", _this.motionStrength);
  73631. effect.setTexture("depthSampler", _this._getDepthTexture());
  73632. };
  73633. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  73634. };
  73635. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  73636. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  73637. var renderer = this._scene.enableGeometryBufferRenderer();
  73638. return renderer.getGBuffer().textures[0];
  73639. }
  73640. return this._scene.enableDepthRenderer().getDepthMap();
  73641. };
  73642. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  73643. for (var i = 0; i < this._cameras.length; i++) {
  73644. var camera = this._cameras[i];
  73645. if (this.originalPostProcess) {
  73646. this.originalPostProcess.dispose(camera);
  73647. }
  73648. if (this.downSampleX4PostProcess) {
  73649. this.downSampleX4PostProcess.dispose(camera);
  73650. }
  73651. if (this.brightPassPostProcess) {
  73652. this.brightPassPostProcess.dispose(camera);
  73653. }
  73654. if (this.textureAdderPostProcess) {
  73655. this.textureAdderPostProcess.dispose(camera);
  73656. }
  73657. if (this.textureAdderFinalPostProcess) {
  73658. this.textureAdderFinalPostProcess.dispose(camera);
  73659. }
  73660. if (this.volumetricLightPostProcess) {
  73661. this.volumetricLightPostProcess.dispose(camera);
  73662. }
  73663. if (this.volumetricLightSmoothXPostProcess) {
  73664. this.volumetricLightSmoothXPostProcess.dispose(camera);
  73665. }
  73666. if (this.volumetricLightSmoothYPostProcess) {
  73667. this.volumetricLightSmoothYPostProcess.dispose(camera);
  73668. }
  73669. if (this.volumetricLightMergePostProces) {
  73670. this.volumetricLightMergePostProces.dispose(camera);
  73671. }
  73672. if (this.volumetricLightFinalPostProcess) {
  73673. this.volumetricLightFinalPostProcess.dispose(camera);
  73674. }
  73675. if (this.lensFlarePostProcess) {
  73676. this.lensFlarePostProcess.dispose(camera);
  73677. }
  73678. if (this.lensFlareComposePostProcess) {
  73679. this.lensFlareComposePostProcess.dispose(camera);
  73680. }
  73681. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  73682. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  73683. }
  73684. if (this.luminancePostProcess) {
  73685. this.luminancePostProcess.dispose(camera);
  73686. }
  73687. if (this.hdrPostProcess) {
  73688. this.hdrPostProcess.dispose(camera);
  73689. }
  73690. if (this.hdrFinalPostProcess) {
  73691. this.hdrFinalPostProcess.dispose(camera);
  73692. }
  73693. if (this.depthOfFieldPostProcess) {
  73694. this.depthOfFieldPostProcess.dispose(camera);
  73695. }
  73696. if (this.motionBlurPostProcess) {
  73697. this.motionBlurPostProcess.dispose(camera);
  73698. }
  73699. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  73700. this.blurHPostProcesses[j].dispose(camera);
  73701. }
  73702. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  73703. this.blurVPostProcesses[j].dispose(camera);
  73704. }
  73705. }
  73706. this.originalPostProcess = null;
  73707. this.downSampleX4PostProcess = null;
  73708. this.brightPassPostProcess = null;
  73709. this.textureAdderPostProcess = null;
  73710. this.textureAdderFinalPostProcess = null;
  73711. this.volumetricLightPostProcess = null;
  73712. this.volumetricLightSmoothXPostProcess = null;
  73713. this.volumetricLightSmoothYPostProcess = null;
  73714. this.volumetricLightMergePostProces = null;
  73715. this.volumetricLightFinalPostProcess = null;
  73716. this.lensFlarePostProcess = null;
  73717. this.lensFlareComposePostProcess = null;
  73718. this.luminancePostProcess = null;
  73719. this.hdrPostProcess = null;
  73720. this.hdrFinalPostProcess = null;
  73721. this.depthOfFieldPostProcess = null;
  73722. this.motionBlurPostProcess = null;
  73723. this.luminanceDownSamplePostProcesses = [];
  73724. this.blurHPostProcesses = [];
  73725. this.blurVPostProcesses = [];
  73726. };
  73727. // Dispose
  73728. StandardRenderingPipeline.prototype.dispose = function () {
  73729. this._disposePostProcesses();
  73730. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  73731. _super.prototype.dispose.call(this);
  73732. };
  73733. // Serialize rendering pipeline
  73734. StandardRenderingPipeline.prototype.serialize = function () {
  73735. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73736. serializationObject.customType = "StandardRenderingPipeline";
  73737. return serializationObject;
  73738. };
  73739. /**
  73740. * Static members
  73741. */
  73742. // Parse serialized pipeline
  73743. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  73744. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73745. };
  73746. // Luminance steps
  73747. StandardRenderingPipeline.LuminanceSteps = 6;
  73748. __decorate([
  73749. BABYLON.serialize()
  73750. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  73751. __decorate([
  73752. BABYLON.serialize()
  73753. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  73754. __decorate([
  73755. BABYLON.serialize()
  73756. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  73757. __decorate([
  73758. BABYLON.serialize()
  73759. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  73760. __decorate([
  73761. BABYLON.serializeAsTexture("lensTexture")
  73762. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  73763. __decorate([
  73764. BABYLON.serialize()
  73765. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  73766. __decorate([
  73767. BABYLON.serialize()
  73768. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  73769. __decorate([
  73770. BABYLON.serialize()
  73771. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  73772. __decorate([
  73773. BABYLON.serialize()
  73774. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  73775. __decorate([
  73776. BABYLON.serialize()
  73777. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  73778. __decorate([
  73779. BABYLON.serialize()
  73780. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  73781. __decorate([
  73782. BABYLON.serializeAsTexture("lensColorTexture")
  73783. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  73784. __decorate([
  73785. BABYLON.serialize()
  73786. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  73787. __decorate([
  73788. BABYLON.serialize()
  73789. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  73790. __decorate([
  73791. BABYLON.serialize()
  73792. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  73793. __decorate([
  73794. BABYLON.serialize()
  73795. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  73796. __decorate([
  73797. BABYLON.serializeAsTexture("lensStarTexture")
  73798. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  73799. __decorate([
  73800. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  73801. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  73802. __decorate([
  73803. BABYLON.serialize()
  73804. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  73805. __decorate([
  73806. BABYLON.serialize()
  73807. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  73808. __decorate([
  73809. BABYLON.serialize()
  73810. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  73811. __decorate([
  73812. BABYLON.serialize()
  73813. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  73814. __decorate([
  73815. BABYLON.serialize()
  73816. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  73817. __decorate([
  73818. BABYLON.serialize()
  73819. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  73820. __decorate([
  73821. BABYLON.serialize()
  73822. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  73823. __decorate([
  73824. BABYLON.serialize()
  73825. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  73826. __decorate([
  73827. BABYLON.serialize()
  73828. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  73829. __decorate([
  73830. BABYLON.serialize()
  73831. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  73832. __decorate([
  73833. BABYLON.serialize()
  73834. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  73835. __decorate([
  73836. BABYLON.serialize()
  73837. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  73838. return StandardRenderingPipeline;
  73839. }(BABYLON.PostProcessRenderPipeline));
  73840. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  73841. })(BABYLON || (BABYLON = {}));
  73842. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  73843. var BABYLON;
  73844. (function (BABYLON) {
  73845. var FxaaPostProcess = /** @class */ (function (_super) {
  73846. __extends(FxaaPostProcess, _super);
  73847. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  73848. if (camera === void 0) { camera = null; }
  73849. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73850. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  73851. _this.onApplyObservable.add(function (effect) {
  73852. var texelSize = _this.texelSize;
  73853. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  73854. });
  73855. return _this;
  73856. }
  73857. return FxaaPostProcess;
  73858. }(BABYLON.PostProcess));
  73859. BABYLON.FxaaPostProcess = FxaaPostProcess;
  73860. })(BABYLON || (BABYLON = {}));
  73861. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  73862. var BABYLON;
  73863. (function (BABYLON) {
  73864. /**
  73865. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  73866. */
  73867. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  73868. __extends(ChromaticAberrationPostProcess, _super);
  73869. /**
  73870. * Creates a new instance ChromaticAberrationPostProcess
  73871. * @param name The name of the effect.
  73872. * @param screenWidth The width of the screen to apply the effect on.
  73873. * @param screenHeight The height of the screen to apply the effect on.
  73874. * @param options The required width/height ratio to downsize to before computing the render pass.
  73875. * @param camera The camera to apply the render pass to.
  73876. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73877. * @param engine The engine which the post process will be applied. (default: current engine)
  73878. * @param reusable If the post process can be reused on the same frame. (default: false)
  73879. * @param textureType Type of textures used when performing the post process. (default: 0)
  73880. * @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)
  73881. */
  73882. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73883. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73884. if (blockCompilation === void 0) { blockCompilation = false; }
  73885. 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;
  73886. /**
  73887. * The amount of seperation of rgb channels (default: 30)
  73888. */
  73889. _this.aberrationAmount = 30;
  73890. /**
  73891. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  73892. */
  73893. _this.radialIntensity = 0;
  73894. /**
  73895. * 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))
  73896. */
  73897. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  73898. /**
  73899. * 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))
  73900. */
  73901. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  73902. _this.onApplyObservable.add(function (effect) {
  73903. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  73904. effect.setFloat('screen_width', screenWidth);
  73905. effect.setFloat('screen_height', screenHeight);
  73906. effect.setFloat('radialIntensity', _this.radialIntensity);
  73907. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  73908. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  73909. });
  73910. return _this;
  73911. }
  73912. return ChromaticAberrationPostProcess;
  73913. }(BABYLON.PostProcess));
  73914. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  73915. })(BABYLON || (BABYLON = {}));
  73916. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  73917. var BABYLON;
  73918. (function (BABYLON) {
  73919. /**
  73920. * The GrainPostProcess adds noise to the image at mid luminance levels
  73921. */
  73922. var GrainPostProcess = /** @class */ (function (_super) {
  73923. __extends(GrainPostProcess, _super);
  73924. /**
  73925. * Creates a new instance of @see GrainPostProcess
  73926. * @param name The name of the effect.
  73927. * @param options The required width/height ratio to downsize to before computing the render pass.
  73928. * @param camera The camera to apply the render pass to.
  73929. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73930. * @param engine The engine which the post process will be applied. (default: current engine)
  73931. * @param reusable If the post process can be reused on the same frame. (default: false)
  73932. * @param textureType Type of textures used when performing the post process. (default: 0)
  73933. * @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)
  73934. */
  73935. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73936. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73937. if (blockCompilation === void 0) { blockCompilation = false; }
  73938. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73939. /**
  73940. * The intensity of the grain added (default: 30)
  73941. */
  73942. _this.intensity = 30;
  73943. /**
  73944. * If the grain should be randomized on every frame
  73945. */
  73946. _this.animated = false;
  73947. _this.onApplyObservable.add(function (effect) {
  73948. effect.setFloat('intensity', _this.intensity);
  73949. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  73950. });
  73951. return _this;
  73952. }
  73953. return GrainPostProcess;
  73954. }(BABYLON.PostProcess));
  73955. BABYLON.GrainPostProcess = GrainPostProcess;
  73956. })(BABYLON || (BABYLON = {}));
  73957. //# sourceMappingURL=babylon.grainPostProcess.js.map
  73958. var BABYLON;
  73959. (function (BABYLON) {
  73960. /**
  73961. * The SharpenPostProcess applies a sharpen kernel to every pixel
  73962. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  73963. */
  73964. var SharpenPostProcess = /** @class */ (function (_super) {
  73965. __extends(SharpenPostProcess, _super);
  73966. /**
  73967. * Creates a new instance ConvolutionPostProcess
  73968. * @param name The name of the effect.
  73969. * @param options The required width/height ratio to downsize to before computing the render pass.
  73970. * @param camera The camera to apply the render pass to.
  73971. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73972. * @param engine The engine which the post process will be applied. (default: current engine)
  73973. * @param reusable If the post process can be reused on the same frame. (default: false)
  73974. * @param textureType Type of textures used when performing the post process. (default: 0)
  73975. * @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)
  73976. */
  73977. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  73978. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73979. if (blockCompilation === void 0) { blockCompilation = false; }
  73980. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  73981. /**
  73982. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  73983. */
  73984. _this.colorAmount = 1.0;
  73985. /**
  73986. * How much sharpness should be applied (default: 0.3)
  73987. */
  73988. _this.edgeAmount = 0.3;
  73989. _this.onApply = function (effect) {
  73990. effect.setFloat2("screenSize", _this.width, _this.height);
  73991. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  73992. };
  73993. return _this;
  73994. }
  73995. return SharpenPostProcess;
  73996. }(BABYLON.PostProcess));
  73997. BABYLON.SharpenPostProcess = SharpenPostProcess;
  73998. })(BABYLON || (BABYLON = {}));
  73999. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74000. var BABYLON;
  74001. (function (BABYLON) {
  74002. /**
  74003. * The Blur Post Process which blurs an image based on a kernel and direction.
  74004. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74005. */
  74006. var BlurPostProcess = /** @class */ (function (_super) {
  74007. __extends(BlurPostProcess, _super);
  74008. /**
  74009. * Creates a new instance BlurPostProcess
  74010. * @param name The name of the effect.
  74011. * @param direction The direction in which to blur the image.
  74012. * @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.
  74013. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74014. * @param camera The camera to apply the render pass to.
  74015. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74016. * @param engine The engine which the post process will be applied. (default: current engine)
  74017. * @param reusable If the post process can be reused on the same frame. (default: false)
  74018. * @param textureType Type of textures used when performing the post process. (default: 0)
  74019. * @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)
  74020. */
  74021. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74022. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74023. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74024. if (defines === void 0) { defines = ""; }
  74025. if (blockCompilation === void 0) { blockCompilation = false; }
  74026. 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;
  74027. _this.direction = direction;
  74028. _this.blockCompilation = blockCompilation;
  74029. _this._packedFloat = false;
  74030. _this._staticDefines = "";
  74031. _this._staticDefines = defines;
  74032. _this.onApplyObservable.add(function (effect) {
  74033. if (_this._outputTexture) {
  74034. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74035. }
  74036. else {
  74037. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74038. }
  74039. });
  74040. _this.kernel = kernel;
  74041. return _this;
  74042. }
  74043. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74044. /**
  74045. * Gets the length in pixels of the blur sample region
  74046. */
  74047. get: function () {
  74048. return this._idealKernel;
  74049. },
  74050. /**
  74051. * Sets the length in pixels of the blur sample region
  74052. */
  74053. set: function (v) {
  74054. if (this._idealKernel === v) {
  74055. return;
  74056. }
  74057. v = Math.max(v, 1);
  74058. this._idealKernel = v;
  74059. this._kernel = this._nearestBestKernel(v);
  74060. if (!this.blockCompilation) {
  74061. this._updateParameters();
  74062. }
  74063. },
  74064. enumerable: true,
  74065. configurable: true
  74066. });
  74067. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74068. /**
  74069. * Gets wether or not the blur is unpacking/repacking floats
  74070. */
  74071. get: function () {
  74072. return this._packedFloat;
  74073. },
  74074. /**
  74075. * Sets wether or not the blur needs to unpack/repack floats
  74076. */
  74077. set: function (v) {
  74078. if (this._packedFloat === v) {
  74079. return;
  74080. }
  74081. this._packedFloat = v;
  74082. if (!this.blockCompilation) {
  74083. this._updateParameters();
  74084. }
  74085. },
  74086. enumerable: true,
  74087. configurable: true
  74088. });
  74089. /**
  74090. * Updates the effect with the current post process compile time values and recompiles the shader.
  74091. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74092. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74093. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74094. * @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
  74095. * @param onCompiled Called when the shader has been compiled.
  74096. * @param onError Called if there is an error when compiling a shader.
  74097. */
  74098. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74099. if (defines === void 0) { defines = null; }
  74100. if (uniforms === void 0) { uniforms = null; }
  74101. if (samplers === void 0) { samplers = null; }
  74102. this._updateParameters(onCompiled, onError);
  74103. };
  74104. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74105. // Generate sampling offsets and weights
  74106. var N = this._kernel;
  74107. var centerIndex = (N - 1) / 2;
  74108. // Generate Gaussian sampling weights over kernel
  74109. var offsets = [];
  74110. var weights = [];
  74111. var totalWeight = 0;
  74112. for (var i = 0; i < N; i++) {
  74113. var u = i / (N - 1);
  74114. var w = this._gaussianWeight(u * 2.0 - 1);
  74115. offsets[i] = (i - centerIndex);
  74116. weights[i] = w;
  74117. totalWeight += w;
  74118. }
  74119. // Normalize weights
  74120. for (var i = 0; i < weights.length; i++) {
  74121. weights[i] /= totalWeight;
  74122. }
  74123. // Optimize: combine samples to take advantage of hardware linear sampling
  74124. // Walk from left to center, combining pairs (symmetrically)
  74125. var linearSamplingWeights = [];
  74126. var linearSamplingOffsets = [];
  74127. var linearSamplingMap = [];
  74128. for (var i = 0; i <= centerIndex; i += 2) {
  74129. var j = Math.min(i + 1, Math.floor(centerIndex));
  74130. var singleCenterSample = i === j;
  74131. if (singleCenterSample) {
  74132. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74133. }
  74134. else {
  74135. var sharedCell = j === centerIndex;
  74136. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74137. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74138. if (offsetLinear === 0) {
  74139. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74140. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74141. }
  74142. else {
  74143. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74144. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74145. }
  74146. }
  74147. }
  74148. for (var i = 0; i < linearSamplingMap.length; i++) {
  74149. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74150. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74151. }
  74152. // Replace with optimized
  74153. offsets = linearSamplingOffsets;
  74154. weights = linearSamplingWeights;
  74155. // Generate shaders
  74156. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74157. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74158. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74159. var defines = "";
  74160. defines += this._staticDefines;
  74161. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74162. if (this._staticDefines.indexOf("DOF") != -1) {
  74163. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74164. varyingCount--;
  74165. }
  74166. for (var i = 0; i < varyingCount; i++) {
  74167. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74168. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74169. }
  74170. var depCount = 0;
  74171. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74172. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74173. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74174. depCount++;
  74175. }
  74176. if (this.packedFloat) {
  74177. defines += "#define PACKEDFLOAT 1";
  74178. }
  74179. this.blockCompilation = false;
  74180. _super.prototype.updateEffect.call(this, defines, null, null, {
  74181. varyingCount: varyingCount,
  74182. depCount: depCount
  74183. }, onCompiled, onError);
  74184. };
  74185. /**
  74186. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74187. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74188. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74189. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74190. * The gaps between physical kernels are compensated for in the weighting of the samples
  74191. * @param idealKernel Ideal blur kernel.
  74192. * @return Nearest best kernel.
  74193. */
  74194. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74195. var v = Math.round(idealKernel);
  74196. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74197. var k = _a[_i];
  74198. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74199. return Math.max(k, 3);
  74200. }
  74201. }
  74202. return Math.max(v, 3);
  74203. };
  74204. /**
  74205. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74206. * @param x The point on the Gaussian distribution to sample.
  74207. * @return the value of the Gaussian function at x.
  74208. */
  74209. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74210. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74211. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74212. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74213. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74214. // truncated at around 1.3% of peak strength.
  74215. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74216. var sigma = (1 / 3);
  74217. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74218. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74219. var weight = (1.0 / denominator) * Math.exp(exponent);
  74220. return weight;
  74221. };
  74222. /**
  74223. * Generates a string that can be used as a floating point number in GLSL.
  74224. * @param x Value to print.
  74225. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74226. * @return GLSL float string.
  74227. */
  74228. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74229. if (decimalFigures === void 0) { decimalFigures = 8; }
  74230. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74231. };
  74232. return BlurPostProcess;
  74233. }(BABYLON.PostProcess));
  74234. BABYLON.BlurPostProcess = BlurPostProcess;
  74235. })(BABYLON || (BABYLON = {}));
  74236. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74237. var BABYLON;
  74238. (function (BABYLON) {
  74239. /**
  74240. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74241. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74242. * based on samples that have a large difference in distance than the center pixel.
  74243. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74244. */
  74245. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74246. __extends(DepthOfFieldBlurPostProcess, _super);
  74247. /**
  74248. * Creates a new instance CircleOfConfusionPostProcess
  74249. * @param name The name of the effect.
  74250. * @param scene The scene the effect belongs to.
  74251. * @param direction The direction the blur should be applied.
  74252. * @param kernel The size of the kernel used to blur.
  74253. * @param options The required width/height ratio to downsize to before computing the render pass.
  74254. * @param camera The camera to apply the render pass to.
  74255. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74256. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74257. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74258. * @param engine The engine which the post process will be applied. (default: current engine)
  74259. * @param reusable If the post process can be reused on the same frame. (default: false)
  74260. * @param textureType Type of textures used when performing the post process. (default: 0)
  74261. * @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)
  74262. */
  74263. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74264. if (imageToBlur === void 0) { imageToBlur = null; }
  74265. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74266. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74267. if (blockCompilation === void 0) { blockCompilation = false; }
  74268. 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;
  74269. _this.direction = direction;
  74270. _this.onApplyObservable.add(function (effect) {
  74271. if (imageToBlur != null) {
  74272. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74273. }
  74274. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74275. if (scene.activeCamera) {
  74276. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74277. }
  74278. });
  74279. return _this;
  74280. }
  74281. return DepthOfFieldBlurPostProcess;
  74282. }(BABYLON.BlurPostProcess));
  74283. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74284. })(BABYLON || (BABYLON = {}));
  74285. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74286. var BABYLON;
  74287. (function (BABYLON) {
  74288. /**
  74289. * Options to be set when merging outputs from the default pipeline.
  74290. */
  74291. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74292. function DepthOfFieldMergePostProcessOptions() {
  74293. }
  74294. return DepthOfFieldMergePostProcessOptions;
  74295. }());
  74296. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74297. /**
  74298. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74299. */
  74300. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74301. __extends(DepthOfFieldMergePostProcess, _super);
  74302. /**
  74303. * Creates a new instance of DepthOfFieldMergePostProcess
  74304. * @param name The name of the effect.
  74305. * @param originalFromInput Post process which's input will be used for the merge.
  74306. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74307. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74308. * @param options The required width/height ratio to downsize to before computing the render pass.
  74309. * @param camera The camera to apply the render pass to.
  74310. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74311. * @param engine The engine which the post process will be applied. (default: current engine)
  74312. * @param reusable If the post process can be reused on the same frame. (default: false)
  74313. * @param textureType Type of textures used when performing the post process. (default: 0)
  74314. * @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)
  74315. */
  74316. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74317. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74318. if (blockCompilation === void 0) { blockCompilation = false; }
  74319. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74320. _this.blurSteps = blurSteps;
  74321. _this.onApplyObservable.add(function (effect) {
  74322. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74323. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74324. blurSteps.forEach(function (step, index) {
  74325. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74326. });
  74327. });
  74328. if (!blockCompilation) {
  74329. _this.updateEffect();
  74330. }
  74331. return _this;
  74332. }
  74333. /**
  74334. * Updates the effect with the current post process compile time values and recompiles the shader.
  74335. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74336. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74337. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74338. * @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
  74339. * @param onCompiled Called when the shader has been compiled.
  74340. * @param onError Called if there is an error when compiling a shader.
  74341. */
  74342. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74343. if (defines === void 0) { defines = null; }
  74344. if (uniforms === void 0) { uniforms = null; }
  74345. if (samplers === void 0) { samplers = null; }
  74346. if (!defines) {
  74347. defines = "";
  74348. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74349. }
  74350. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74351. };
  74352. return DepthOfFieldMergePostProcess;
  74353. }(BABYLON.PostProcess));
  74354. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74355. })(BABYLON || (BABYLON = {}));
  74356. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74357. var BABYLON;
  74358. (function (BABYLON) {
  74359. /**
  74360. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74361. */
  74362. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74363. __extends(CircleOfConfusionPostProcess, _super);
  74364. /**
  74365. * Creates a new instance CircleOfConfusionPostProcess
  74366. * @param name The name of the effect.
  74367. * @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.
  74368. * @param options The required width/height ratio to downsize to before computing the render pass.
  74369. * @param camera The camera to apply the render pass to.
  74370. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74371. * @param engine The engine which the post process will be applied. (default: current engine)
  74372. * @param reusable If the post process can be reused on the same frame. (default: false)
  74373. * @param textureType Type of textures used when performing the post process. (default: 0)
  74374. * @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)
  74375. */
  74376. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74377. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74378. if (blockCompilation === void 0) { blockCompilation = false; }
  74379. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74380. /**
  74381. * 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.
  74382. */
  74383. _this.lensSize = 50;
  74384. /**
  74385. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74386. */
  74387. _this.fStop = 1.4;
  74388. /**
  74389. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74390. */
  74391. _this.focusDistance = 2000;
  74392. /**
  74393. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74394. */
  74395. _this.focalLength = 50;
  74396. _this._depthTexture = null;
  74397. _this._depthTexture = depthTexture;
  74398. _this.onApplyObservable.add(function (effect) {
  74399. if (!_this._depthTexture) {
  74400. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74401. return;
  74402. }
  74403. effect.setTexture("depthSampler", _this._depthTexture);
  74404. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74405. var aperture = _this.lensSize / _this.fStop;
  74406. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74407. effect.setFloat('focusDistance', _this.focusDistance);
  74408. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74409. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74410. });
  74411. return _this;
  74412. }
  74413. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74414. /**
  74415. * 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.
  74416. */
  74417. set: function (value) {
  74418. this._depthTexture = value;
  74419. },
  74420. enumerable: true,
  74421. configurable: true
  74422. });
  74423. return CircleOfConfusionPostProcess;
  74424. }(BABYLON.PostProcess));
  74425. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74426. })(BABYLON || (BABYLON = {}));
  74427. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74428. var BABYLON;
  74429. (function (BABYLON) {
  74430. /**
  74431. * Specifies the level of max blur that should be applied when using the depth of field effect
  74432. */
  74433. var DepthOfFieldEffectBlurLevel;
  74434. (function (DepthOfFieldEffectBlurLevel) {
  74435. /**
  74436. * Subtle blur
  74437. */
  74438. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74439. /**
  74440. * Medium blur
  74441. */
  74442. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74443. /**
  74444. * Large blur
  74445. */
  74446. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74447. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74448. ;
  74449. /**
  74450. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74451. */
  74452. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74453. __extends(DepthOfFieldEffect, _super);
  74454. /**
  74455. * Creates a new instance DepthOfFieldEffect
  74456. * @param scene The scene the effect belongs to.
  74457. * @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.
  74458. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74459. * @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)
  74460. */
  74461. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74462. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74463. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74464. if (blockCompilation === void 0) { blockCompilation = false; }
  74465. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  74466. return _this._effects;
  74467. }, true) || this;
  74468. /**
  74469. * Internal post processes in depth of field effect
  74470. */
  74471. _this._effects = [];
  74472. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  74473. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74474. // 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)
  74475. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  74476. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74477. _this._depthOfFieldBlurY = [];
  74478. _this._depthOfFieldBlurX = [];
  74479. var blurCount = 1;
  74480. var kernelSize = 15;
  74481. switch (blurLevel) {
  74482. case DepthOfFieldEffectBlurLevel.High: {
  74483. blurCount = 3;
  74484. kernelSize = 51;
  74485. break;
  74486. }
  74487. case DepthOfFieldEffectBlurLevel.Medium: {
  74488. blurCount = 2;
  74489. kernelSize = 31;
  74490. break;
  74491. }
  74492. default: {
  74493. kernelSize = 15;
  74494. blurCount = 1;
  74495. break;
  74496. }
  74497. }
  74498. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  74499. var ratio = 1.0;
  74500. for (var i = 0; i < blurCount; i++) {
  74501. 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);
  74502. blurY.autoClear = false;
  74503. ratio = 0.75 / Math.pow(2, i);
  74504. 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);
  74505. blurX.autoClear = false;
  74506. _this._depthOfFieldBlurY.push(blurY);
  74507. _this._depthOfFieldBlurX.push(blurX);
  74508. }
  74509. // Set all post processes on the effect.
  74510. _this._effects = [_this._circleOfConfusion];
  74511. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  74512. _this._effects.push(_this._depthOfFieldBlurY[i]);
  74513. _this._effects.push(_this._depthOfFieldBlurX[i]);
  74514. }
  74515. // Merge blurred images with original image based on circleOfConfusion
  74516. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74517. _this._dofMerge.autoClear = false;
  74518. _this._effects.push(_this._dofMerge);
  74519. return _this;
  74520. }
  74521. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  74522. get: function () {
  74523. return this._circleOfConfusion.focalLength;
  74524. },
  74525. /**
  74526. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  74527. */
  74528. set: function (value) {
  74529. this._circleOfConfusion.focalLength = value;
  74530. },
  74531. enumerable: true,
  74532. configurable: true
  74533. });
  74534. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  74535. get: function () {
  74536. return this._circleOfConfusion.fStop;
  74537. },
  74538. /**
  74539. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74540. */
  74541. set: function (value) {
  74542. this._circleOfConfusion.fStop = value;
  74543. },
  74544. enumerable: true,
  74545. configurable: true
  74546. });
  74547. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  74548. get: function () {
  74549. return this._circleOfConfusion.focusDistance;
  74550. },
  74551. /**
  74552. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74553. */
  74554. set: function (value) {
  74555. this._circleOfConfusion.focusDistance = value;
  74556. },
  74557. enumerable: true,
  74558. configurable: true
  74559. });
  74560. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  74561. get: function () {
  74562. return this._circleOfConfusion.lensSize;
  74563. },
  74564. /**
  74565. * 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.
  74566. */
  74567. set: function (value) {
  74568. this._circleOfConfusion.lensSize = value;
  74569. },
  74570. enumerable: true,
  74571. configurable: true
  74572. });
  74573. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  74574. /**
  74575. * 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.
  74576. */
  74577. set: function (value) {
  74578. this._circleOfConfusion.depthTexture = value;
  74579. },
  74580. enumerable: true,
  74581. configurable: true
  74582. });
  74583. /**
  74584. * Disposes each of the internal effects for a given camera.
  74585. * @param camera The camera to dispose the effect on.
  74586. */
  74587. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  74588. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74589. this._effects[effectIndex].dispose(camera);
  74590. }
  74591. };
  74592. /**
  74593. * Internal
  74594. */
  74595. DepthOfFieldEffect.prototype._updateEffects = function () {
  74596. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74597. this._effects[effectIndex].updateEffect();
  74598. }
  74599. };
  74600. /**
  74601. * Internal
  74602. * @returns if all the contained post processes are ready.
  74603. */
  74604. DepthOfFieldEffect.prototype._isReady = function () {
  74605. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74606. if (!this._effects[effectIndex].isReady()) {
  74607. return false;
  74608. }
  74609. }
  74610. return true;
  74611. };
  74612. return DepthOfFieldEffect;
  74613. }(BABYLON.PostProcessRenderEffect));
  74614. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  74615. })(BABYLON || (BABYLON = {}));
  74616. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  74617. var BABYLON;
  74618. (function (BABYLON) {
  74619. /**
  74620. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74621. */
  74622. var BloomMergePostProcess = /** @class */ (function (_super) {
  74623. __extends(BloomMergePostProcess, _super);
  74624. /**
  74625. * Creates a new instance of @see BloomMergePostProcess
  74626. * @param name The name of the effect.
  74627. * @param originalFromInput Post process which's input will be used for the merge.
  74628. * @param blurred Blurred highlights post process which's output will be used.
  74629. * @param weight Weight of the bloom to be added to the original input.
  74630. * @param options The required width/height ratio to downsize to before computing the render pass.
  74631. * @param camera The camera to apply the render pass to.
  74632. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74633. * @param engine The engine which the post process will be applied. (default: current engine)
  74634. * @param reusable If the post process can be reused on the same frame. (default: false)
  74635. * @param textureType Type of textures used when performing the post process. (default: 0)
  74636. * @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)
  74637. */
  74638. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74639. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74640. if (blockCompilation === void 0) { blockCompilation = false; }
  74641. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74642. _this.weight = weight;
  74643. _this.onApplyObservable.add(function (effect) {
  74644. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74645. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  74646. effect.setFloat("bloomWeight", _this.weight);
  74647. });
  74648. if (!blockCompilation) {
  74649. _this.updateEffect();
  74650. }
  74651. return _this;
  74652. }
  74653. return BloomMergePostProcess;
  74654. }(BABYLON.PostProcess));
  74655. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  74656. })(BABYLON || (BABYLON = {}));
  74657. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  74658. var BABYLON;
  74659. (function (BABYLON) {
  74660. /**
  74661. * 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.
  74662. */
  74663. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  74664. __extends(ExtractHighlightsPostProcess, _super);
  74665. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74666. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74667. if (blockCompilation === void 0) { blockCompilation = false; }
  74668. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74669. /**
  74670. * The luminance threshold, pixels below this value will be set to black.
  74671. */
  74672. _this.threshold = 0.9;
  74673. /**
  74674. * Internal
  74675. */
  74676. _this._exposure = 1;
  74677. /**
  74678. * Post process which has the input texture to be used when performing highlight extraction
  74679. */
  74680. _this._inputPostProcess = null;
  74681. _this.onApplyObservable.add(function (effect) {
  74682. if (_this._inputPostProcess) {
  74683. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  74684. }
  74685. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  74686. effect.setFloat('exposure', _this._exposure);
  74687. });
  74688. return _this;
  74689. }
  74690. return ExtractHighlightsPostProcess;
  74691. }(BABYLON.PostProcess));
  74692. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  74693. })(BABYLON || (BABYLON = {}));
  74694. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  74695. var BABYLON;
  74696. (function (BABYLON) {
  74697. /**
  74698. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  74699. */
  74700. var BloomEffect = /** @class */ (function (_super) {
  74701. __extends(BloomEffect, _super);
  74702. /**
  74703. * Creates a new instance of @see BloomEffect
  74704. * @param scene The scene the effect belongs to.
  74705. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  74706. * @param bloomKernel The size of the kernel to be used when applying the blur.
  74707. * @param bloomWeight The the strength of bloom.
  74708. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74709. * @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)
  74710. */
  74711. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  74712. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  74713. if (blockCompilation === void 0) { blockCompilation = false; }
  74714. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  74715. return _this._effects;
  74716. }, true) || this;
  74717. _this.bloomScale = bloomScale;
  74718. /**
  74719. * Internal
  74720. */
  74721. _this._effects = [];
  74722. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74723. _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);
  74724. _this._blurX.alwaysForcePOT = true;
  74725. _this._blurX.autoClear = false;
  74726. _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);
  74727. _this._blurY.alwaysForcePOT = true;
  74728. _this._blurY.autoClear = false;
  74729. _this.kernel = bloomKernel;
  74730. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  74731. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  74732. _this._merge.autoClear = false;
  74733. _this._effects.push(_this._merge);
  74734. return _this;
  74735. }
  74736. Object.defineProperty(BloomEffect.prototype, "threshold", {
  74737. /**
  74738. * The luminance threshold to find bright areas of the image to bloom.
  74739. */
  74740. get: function () {
  74741. return this._downscale.threshold;
  74742. },
  74743. set: function (value) {
  74744. this._downscale.threshold = value;
  74745. },
  74746. enumerable: true,
  74747. configurable: true
  74748. });
  74749. Object.defineProperty(BloomEffect.prototype, "weight", {
  74750. /**
  74751. * The strength of the bloom.
  74752. */
  74753. get: function () {
  74754. return this._merge.weight;
  74755. },
  74756. set: function (value) {
  74757. this._merge.weight = value;
  74758. },
  74759. enumerable: true,
  74760. configurable: true
  74761. });
  74762. Object.defineProperty(BloomEffect.prototype, "kernel", {
  74763. /**
  74764. * Specifies the size of the bloom blur kernel, relative to the final output size
  74765. */
  74766. get: function () {
  74767. return this._blurX.kernel / this.bloomScale;
  74768. },
  74769. set: function (value) {
  74770. this._blurX.kernel = value * this.bloomScale;
  74771. this._blurY.kernel = value * this.bloomScale;
  74772. },
  74773. enumerable: true,
  74774. configurable: true
  74775. });
  74776. /**
  74777. * Disposes each of the internal effects for a given camera.
  74778. * @param camera The camera to dispose the effect on.
  74779. */
  74780. BloomEffect.prototype.disposeEffects = function (camera) {
  74781. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74782. this._effects[effectIndex].dispose(camera);
  74783. }
  74784. };
  74785. /**
  74786. * Internal
  74787. */
  74788. BloomEffect.prototype._updateEffects = function () {
  74789. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74790. this._effects[effectIndex].updateEffect();
  74791. }
  74792. };
  74793. /**
  74794. * Internal
  74795. * @returns if all the contained post processes are ready.
  74796. */
  74797. BloomEffect.prototype._isReady = function () {
  74798. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  74799. if (!this._effects[effectIndex].isReady()) {
  74800. return false;
  74801. }
  74802. }
  74803. return true;
  74804. };
  74805. return BloomEffect;
  74806. }(BABYLON.PostProcessRenderEffect));
  74807. BABYLON.BloomEffect = BloomEffect;
  74808. })(BABYLON || (BABYLON = {}));
  74809. //# sourceMappingURL=babylon.bloomEffect.js.map
  74810. var BABYLON;
  74811. (function (BABYLON) {
  74812. /**
  74813. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  74814. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  74815. */
  74816. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  74817. __extends(DefaultRenderingPipeline, _super);
  74818. /**
  74819. * @constructor
  74820. * @param {string} name - The rendering pipeline name
  74821. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74822. * @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)
  74823. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74824. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  74825. */
  74826. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  74827. if (automaticBuild === void 0) { automaticBuild = true; }
  74828. var _this = _super.call(this, scene.getEngine(), name) || this;
  74829. _this._originalCameras = [];
  74830. /**
  74831. * ID of the sharpen post process,
  74832. */
  74833. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  74834. /**
  74835. * ID of the image processing post process;
  74836. */
  74837. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  74838. /**
  74839. * ID of the Fast Approximate Anti-Aliasing post process;
  74840. */
  74841. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  74842. /**
  74843. * ID of the chromatic aberration post process,
  74844. */
  74845. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  74846. /**
  74847. * ID of the grain post process
  74848. */
  74849. _this.GrainPostProcessId = "GrainPostProcessEffect";
  74850. /**
  74851. * Animations which can be used to tweak settings over a period of time
  74852. */
  74853. _this.animations = [];
  74854. _this._imageProcessingConfigurationObserver = null;
  74855. // Values
  74856. _this._sharpenEnabled = false;
  74857. _this._bloomEnabled = false;
  74858. _this._depthOfFieldEnabled = false;
  74859. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  74860. _this._fxaaEnabled = false;
  74861. _this._imageProcessingEnabled = true;
  74862. _this._bloomScale = 0.5;
  74863. _this._chromaticAberrationEnabled = false;
  74864. _this._grainEnabled = false;
  74865. _this._buildAllowed = true;
  74866. _this._resizeObserver = null;
  74867. _this._hardwareScaleLevel = 1.0;
  74868. _this._bloomKernel = 64;
  74869. /**
  74870. * Specifies the weight of the bloom in the final rendering
  74871. */
  74872. _this._bloomWeight = 0.15;
  74873. /**
  74874. * Specifies the luma threshold for the area that will be blurred by the bloom
  74875. */
  74876. _this._bloomThreshold = 0.9;
  74877. _this._samples = 1;
  74878. _this._hasCleared = false;
  74879. _this._prevPostProcess = null;
  74880. _this._prevPrevPostProcess = null;
  74881. _this._cameras = cameras || [];
  74882. _this._originalCameras = _this._cameras.slice();
  74883. _this._buildAllowed = automaticBuild;
  74884. // Initialize
  74885. _this._scene = scene;
  74886. var caps = _this._scene.getEngine().getCaps();
  74887. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  74888. // Misc
  74889. if (_this._hdr) {
  74890. if (caps.textureHalfFloatRender) {
  74891. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74892. }
  74893. else if (caps.textureFloatRender) {
  74894. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74895. }
  74896. }
  74897. else {
  74898. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74899. }
  74900. // Attach
  74901. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74902. var engine = _this._scene.getEngine();
  74903. // Create post processes before hand so they can be modified before enabled.
  74904. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  74905. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74906. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  74907. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  74908. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  74909. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74910. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  74911. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  74912. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  74913. _this._resizeObserver = engine.onResizeObservable.add(function () {
  74914. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  74915. _this.bloomKernel = _this.bloomKernel;
  74916. });
  74917. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  74918. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  74919. });
  74920. _this._buildPipeline();
  74921. return _this;
  74922. }
  74923. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  74924. get: function () {
  74925. return this._sharpenEnabled;
  74926. },
  74927. /**
  74928. * Enable or disable the sharpen process from the pipeline
  74929. */
  74930. set: function (enabled) {
  74931. if (this._sharpenEnabled === enabled) {
  74932. return;
  74933. }
  74934. this._sharpenEnabled = enabled;
  74935. this._buildPipeline();
  74936. },
  74937. enumerable: true,
  74938. configurable: true
  74939. });
  74940. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  74941. /**
  74942. * Specifies the size of the bloom blur kernel, relative to the final output size
  74943. */
  74944. get: function () {
  74945. return this._bloomKernel;
  74946. },
  74947. set: function (value) {
  74948. this._bloomKernel = value;
  74949. this.bloom.kernel = value / this._hardwareScaleLevel;
  74950. },
  74951. enumerable: true,
  74952. configurable: true
  74953. });
  74954. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  74955. get: function () {
  74956. return this._bloomWeight;
  74957. },
  74958. /**
  74959. * The strength of the bloom.
  74960. */
  74961. set: function (value) {
  74962. if (this._bloomWeight === value) {
  74963. return;
  74964. }
  74965. this.bloom.weight = value;
  74966. this._bloomWeight = value;
  74967. },
  74968. enumerable: true,
  74969. configurable: true
  74970. });
  74971. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  74972. get: function () {
  74973. return this._bloomThreshold;
  74974. },
  74975. /**
  74976. * The strength of the bloom.
  74977. */
  74978. set: function (value) {
  74979. if (this._bloomThreshold === value) {
  74980. return;
  74981. }
  74982. this.bloom.threshold = value;
  74983. this._bloomThreshold = value;
  74984. },
  74985. enumerable: true,
  74986. configurable: true
  74987. });
  74988. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  74989. get: function () {
  74990. return this._bloomScale;
  74991. },
  74992. /**
  74993. * The scale of the bloom, lower value will provide better performance.
  74994. */
  74995. set: function (value) {
  74996. if (this._bloomScale === value) {
  74997. return;
  74998. }
  74999. this._bloomScale = value;
  75000. // recreate bloom and dispose old as this setting is not dynamic
  75001. this._rebuildBloom();
  75002. this._buildPipeline();
  75003. },
  75004. enumerable: true,
  75005. configurable: true
  75006. });
  75007. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75008. get: function () {
  75009. return this._bloomEnabled;
  75010. },
  75011. /**
  75012. * Enable or disable the bloom from the pipeline
  75013. */
  75014. set: function (enabled) {
  75015. if (this._bloomEnabled === enabled) {
  75016. return;
  75017. }
  75018. this._bloomEnabled = enabled;
  75019. this._buildPipeline();
  75020. },
  75021. enumerable: true,
  75022. configurable: true
  75023. });
  75024. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75025. // recreate bloom and dispose old as this setting is not dynamic
  75026. var oldBloom = this.bloom;
  75027. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75028. this.bloom.threshold = oldBloom.threshold;
  75029. for (var i = 0; i < this._cameras.length; i++) {
  75030. oldBloom.disposeEffects(this._cameras[i]);
  75031. }
  75032. };
  75033. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75034. /**
  75035. * If the depth of field is enabled.
  75036. */
  75037. get: function () {
  75038. return this._depthOfFieldEnabled;
  75039. },
  75040. set: function (enabled) {
  75041. if (this._depthOfFieldEnabled === enabled) {
  75042. return;
  75043. }
  75044. this._depthOfFieldEnabled = enabled;
  75045. this._buildPipeline();
  75046. },
  75047. enumerable: true,
  75048. configurable: true
  75049. });
  75050. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75051. /**
  75052. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75053. */
  75054. get: function () {
  75055. return this._depthOfFieldBlurLevel;
  75056. },
  75057. set: function (value) {
  75058. if (this._depthOfFieldBlurLevel === value) {
  75059. return;
  75060. }
  75061. this._depthOfFieldBlurLevel = value;
  75062. // recreate dof and dispose old as this setting is not dynamic
  75063. var oldDof = this.depthOfField;
  75064. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75065. this.depthOfField.focalLength = oldDof.focalLength;
  75066. this.depthOfField.focusDistance = oldDof.focusDistance;
  75067. this.depthOfField.fStop = oldDof.fStop;
  75068. this.depthOfField.lensSize = oldDof.lensSize;
  75069. for (var i = 0; i < this._cameras.length; i++) {
  75070. oldDof.disposeEffects(this._cameras[i]);
  75071. }
  75072. this._buildPipeline();
  75073. },
  75074. enumerable: true,
  75075. configurable: true
  75076. });
  75077. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75078. get: function () {
  75079. return this._fxaaEnabled;
  75080. },
  75081. /**
  75082. * If the anti aliasing is enabled.
  75083. */
  75084. set: function (enabled) {
  75085. if (this._fxaaEnabled === enabled) {
  75086. return;
  75087. }
  75088. this._fxaaEnabled = enabled;
  75089. this._buildPipeline();
  75090. },
  75091. enumerable: true,
  75092. configurable: true
  75093. });
  75094. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75095. get: function () {
  75096. return this._samples;
  75097. },
  75098. /**
  75099. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75100. */
  75101. set: function (sampleCount) {
  75102. if (this._samples === sampleCount) {
  75103. return;
  75104. }
  75105. this._samples = sampleCount;
  75106. this._buildPipeline();
  75107. },
  75108. enumerable: true,
  75109. configurable: true
  75110. });
  75111. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75112. get: function () {
  75113. return this._imageProcessingEnabled;
  75114. },
  75115. /**
  75116. * If image processing is enabled.
  75117. */
  75118. set: function (enabled) {
  75119. if (this._imageProcessingEnabled === enabled) {
  75120. return;
  75121. }
  75122. this._imageProcessingEnabled = enabled;
  75123. this._buildPipeline();
  75124. },
  75125. enumerable: true,
  75126. configurable: true
  75127. });
  75128. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75129. get: function () {
  75130. return this._chromaticAberrationEnabled;
  75131. },
  75132. /**
  75133. * Enable or disable the chromaticAberration process from the pipeline
  75134. */
  75135. set: function (enabled) {
  75136. if (this._chromaticAberrationEnabled === enabled) {
  75137. return;
  75138. }
  75139. this._chromaticAberrationEnabled = enabled;
  75140. this._buildPipeline();
  75141. },
  75142. enumerable: true,
  75143. configurable: true
  75144. });
  75145. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75146. get: function () {
  75147. return this._grainEnabled;
  75148. },
  75149. /**
  75150. * Enable or disable the grain process from the pipeline
  75151. */
  75152. set: function (enabled) {
  75153. if (this._grainEnabled === enabled) {
  75154. return;
  75155. }
  75156. this._grainEnabled = enabled;
  75157. this._buildPipeline();
  75158. },
  75159. enumerable: true,
  75160. configurable: true
  75161. });
  75162. /**
  75163. * Force the compilation of the entire pipeline.
  75164. */
  75165. DefaultRenderingPipeline.prototype.prepare = function () {
  75166. var previousState = this._buildAllowed;
  75167. this._buildAllowed = true;
  75168. this._buildPipeline();
  75169. this._buildAllowed = previousState;
  75170. };
  75171. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75172. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75173. if (this._hasCleared) {
  75174. postProcess.autoClear = false;
  75175. }
  75176. else {
  75177. postProcess.autoClear = true;
  75178. this._scene.autoClear = false;
  75179. this._hasCleared = true;
  75180. }
  75181. if (!skipTextureSharing) {
  75182. if (this._prevPrevPostProcess) {
  75183. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75184. }
  75185. else {
  75186. postProcess.useOwnOutput();
  75187. }
  75188. if (this._prevPostProcess) {
  75189. this._prevPrevPostProcess = this._prevPostProcess;
  75190. }
  75191. this._prevPostProcess = postProcess;
  75192. }
  75193. };
  75194. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75195. var _this = this;
  75196. if (!this._buildAllowed) {
  75197. return;
  75198. }
  75199. this._scene.autoClear = true;
  75200. var engine = this._scene.getEngine();
  75201. this._disposePostProcesses();
  75202. if (this._cameras !== null) {
  75203. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75204. // get back cameras to be used to reattach pipeline
  75205. this._cameras = this._originalCameras.slice();
  75206. }
  75207. this._reset();
  75208. this._prevPostProcess = null;
  75209. this._prevPrevPostProcess = null;
  75210. this._hasCleared = false;
  75211. if (this.depthOfFieldEnabled) {
  75212. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75213. this.depthOfField.depthTexture = depthTexture;
  75214. if (!this.depthOfField._isReady()) {
  75215. this.depthOfField._updateEffects();
  75216. }
  75217. this.addEffect(this.depthOfField);
  75218. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75219. }
  75220. if (this.bloomEnabled) {
  75221. if (!this.bloom._isReady()) {
  75222. this.bloom._updateEffects();
  75223. }
  75224. this.addEffect(this.bloom);
  75225. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75226. }
  75227. if (this._imageProcessingEnabled) {
  75228. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75229. if (this._hdr) {
  75230. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75231. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75232. }
  75233. else {
  75234. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75235. }
  75236. }
  75237. if (this.sharpenEnabled) {
  75238. if (!this.sharpen.isReady()) {
  75239. this.sharpen.updateEffect();
  75240. }
  75241. this.addEffect(this._sharpenEffect);
  75242. this._setAutoClearAndTextureSharing(this.sharpen);
  75243. }
  75244. if (this.grainEnabled) {
  75245. if (!this.grain.isReady()) {
  75246. this.grain.updateEffect();
  75247. }
  75248. this.addEffect(this._grainEffect);
  75249. this._setAutoClearAndTextureSharing(this.grain);
  75250. }
  75251. if (this.chromaticAberrationEnabled) {
  75252. if (!this.chromaticAberration.isReady()) {
  75253. this.chromaticAberration.updateEffect();
  75254. }
  75255. this.addEffect(this._chromaticAberrationEffect);
  75256. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75257. }
  75258. if (this.fxaaEnabled) {
  75259. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75260. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75261. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75262. }
  75263. if (this._cameras !== null) {
  75264. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75265. }
  75266. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75267. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75268. }
  75269. };
  75270. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75271. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75272. for (var i = 0; i < this._cameras.length; i++) {
  75273. var camera = this._cameras[i];
  75274. if (this.imageProcessing) {
  75275. this.imageProcessing.dispose(camera);
  75276. }
  75277. if (this.fxaa) {
  75278. this.fxaa.dispose(camera);
  75279. }
  75280. // These are created in the constructor and should not be disposed on every pipeline change
  75281. if (disposeNonRecreated) {
  75282. if (this.sharpen) {
  75283. this.sharpen.dispose(camera);
  75284. }
  75285. if (this.depthOfField) {
  75286. this.depthOfField.disposeEffects(camera);
  75287. }
  75288. if (this.bloom) {
  75289. this.bloom.disposeEffects(camera);
  75290. }
  75291. if (this.chromaticAberration) {
  75292. this.chromaticAberration.dispose(camera);
  75293. }
  75294. if (this.grain) {
  75295. this.grain.dispose(camera);
  75296. }
  75297. }
  75298. }
  75299. this.imageProcessing = null;
  75300. this.fxaa = null;
  75301. if (disposeNonRecreated) {
  75302. this.sharpen = null;
  75303. this._sharpenEffect = null;
  75304. this.depthOfField = null;
  75305. this.bloom = null;
  75306. this.chromaticAberration = null;
  75307. this._chromaticAberrationEffect = null;
  75308. this.grain = null;
  75309. this._grainEffect = null;
  75310. }
  75311. };
  75312. /**
  75313. * Dispose of the pipeline and stop all post processes
  75314. */
  75315. DefaultRenderingPipeline.prototype.dispose = function () {
  75316. this._disposePostProcesses(true);
  75317. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75318. this._scene.autoClear = true;
  75319. if (this._resizeObserver) {
  75320. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75321. this._resizeObserver = null;
  75322. }
  75323. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75324. _super.prototype.dispose.call(this);
  75325. };
  75326. /**
  75327. * Serialize the rendering pipeline (Used when exporting)
  75328. * @returns the serialized object
  75329. */
  75330. DefaultRenderingPipeline.prototype.serialize = function () {
  75331. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75332. serializationObject.customType = "DefaultRenderingPipeline";
  75333. return serializationObject;
  75334. };
  75335. /**
  75336. * Parse the serialized pipeline
  75337. * @param source Source pipeline.
  75338. * @param scene The scene to load the pipeline to.
  75339. * @param rootUrl The URL of the serialized pipeline.
  75340. * @returns An instantiated pipeline from the serialized object.
  75341. */
  75342. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75343. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75344. };
  75345. __decorate([
  75346. BABYLON.serialize()
  75347. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75348. __decorate([
  75349. BABYLON.serialize()
  75350. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75351. __decorate([
  75352. BABYLON.serialize()
  75353. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75354. __decorate([
  75355. BABYLON.serialize()
  75356. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75357. __decorate([
  75358. BABYLON.serialize()
  75359. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75360. __decorate([
  75361. BABYLON.serialize()
  75362. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75363. __decorate([
  75364. BABYLON.serialize()
  75365. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75366. __decorate([
  75367. BABYLON.serialize()
  75368. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75369. __decorate([
  75370. BABYLON.serialize()
  75371. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75372. __decorate([
  75373. BABYLON.serialize()
  75374. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75375. __decorate([
  75376. BABYLON.serialize()
  75377. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75378. __decorate([
  75379. BABYLON.serialize()
  75380. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75381. __decorate([
  75382. BABYLON.serialize()
  75383. ], DefaultRenderingPipeline.prototype, "samples", null);
  75384. __decorate([
  75385. BABYLON.serialize()
  75386. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75387. __decorate([
  75388. BABYLON.serialize()
  75389. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75390. __decorate([
  75391. BABYLON.serialize()
  75392. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75393. return DefaultRenderingPipeline;
  75394. }(BABYLON.PostProcessRenderPipeline));
  75395. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75396. })(BABYLON || (BABYLON = {}));
  75397. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75398. var BABYLON;
  75399. (function (BABYLON) {
  75400. /**
  75401. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75402. */
  75403. var GeometryBufferRenderer = /** @class */ (function () {
  75404. /**
  75405. * Creates a new G Buffer for the scene
  75406. * @param scene The scene the buffer belongs to
  75407. * @param ratio How big is the buffer related to the main canvas.
  75408. */
  75409. function GeometryBufferRenderer(scene, ratio) {
  75410. if (ratio === void 0) { ratio = 1; }
  75411. this._enablePosition = false;
  75412. this._scene = scene;
  75413. this._ratio = ratio;
  75414. // Render target
  75415. this._createRenderTargets();
  75416. }
  75417. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75418. /**
  75419. * Set the render list (meshes to be rendered) used in the G buffer.
  75420. */
  75421. set: function (meshes) {
  75422. this._multiRenderTarget.renderList = meshes;
  75423. },
  75424. enumerable: true,
  75425. configurable: true
  75426. });
  75427. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75428. /**
  75429. * Gets wether or not G buffer are supported by the running hardware.
  75430. * This requires draw buffer supports
  75431. */
  75432. get: function () {
  75433. return this._multiRenderTarget.isSupported;
  75434. },
  75435. enumerable: true,
  75436. configurable: true
  75437. });
  75438. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75439. /**
  75440. * Gets wether or not position are enabled for the G buffer.
  75441. */
  75442. get: function () {
  75443. return this._enablePosition;
  75444. },
  75445. /**
  75446. * Sets wether or not position are enabled for the G buffer.
  75447. */
  75448. set: function (enable) {
  75449. this._enablePosition = enable;
  75450. this.dispose();
  75451. this._createRenderTargets();
  75452. },
  75453. enumerable: true,
  75454. configurable: true
  75455. });
  75456. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75457. /**
  75458. * Gets the scene associated with the buffer.
  75459. */
  75460. get: function () {
  75461. return this._scene;
  75462. },
  75463. enumerable: true,
  75464. configurable: true
  75465. });
  75466. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  75467. /**
  75468. * Gets the ratio used by the buffer during its creation.
  75469. * How big is the buffer related to the main canvas.
  75470. */
  75471. get: function () {
  75472. return this._ratio;
  75473. },
  75474. enumerable: true,
  75475. configurable: true
  75476. });
  75477. /**
  75478. * Checks wether everything is ready to render a submesh to the G buffer.
  75479. * @param subMesh the submesh to check readiness for
  75480. * @param useInstances is the mesh drawn using instance or not
  75481. * @returns true if ready otherwise false
  75482. */
  75483. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  75484. var material = subMesh.getMaterial();
  75485. if (material && material.disableDepthWrite) {
  75486. return false;
  75487. }
  75488. var defines = [];
  75489. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  75490. var mesh = subMesh.getMesh();
  75491. // Alpha test
  75492. if (material && material.needAlphaTesting()) {
  75493. defines.push("#define ALPHATEST");
  75494. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75495. attribs.push(BABYLON.VertexBuffer.UVKind);
  75496. defines.push("#define UV1");
  75497. }
  75498. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75499. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75500. defines.push("#define UV2");
  75501. }
  75502. }
  75503. // Buffers
  75504. if (this._enablePosition) {
  75505. defines.push("#define POSITION");
  75506. }
  75507. // Bones
  75508. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75509. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75510. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75511. if (mesh.numBoneInfluencers > 4) {
  75512. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75513. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75514. }
  75515. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75516. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  75517. }
  75518. else {
  75519. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75520. }
  75521. // Instances
  75522. if (useInstances) {
  75523. defines.push("#define INSTANCES");
  75524. attribs.push("world0");
  75525. attribs.push("world1");
  75526. attribs.push("world2");
  75527. attribs.push("world3");
  75528. }
  75529. // Get correct effect
  75530. var join = defines.join("\n");
  75531. if (this._cachedDefines !== join) {
  75532. this._cachedDefines = join;
  75533. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  75534. }
  75535. return this._effect.isReady();
  75536. };
  75537. /**
  75538. * Gets the current underlying G Buffer.
  75539. * @returns the buffer
  75540. */
  75541. GeometryBufferRenderer.prototype.getGBuffer = function () {
  75542. return this._multiRenderTarget;
  75543. };
  75544. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  75545. /**
  75546. * Gets the number of samples used to render the buffer (anti aliasing).
  75547. */
  75548. get: function () {
  75549. return this._multiRenderTarget.samples;
  75550. },
  75551. /**
  75552. * Sets the number of samples used to render the buffer (anti aliasing).
  75553. */
  75554. set: function (value) {
  75555. this._multiRenderTarget.samples = value;
  75556. },
  75557. enumerable: true,
  75558. configurable: true
  75559. });
  75560. /**
  75561. * Disposes the renderer and frees up associated resources.
  75562. */
  75563. GeometryBufferRenderer.prototype.dispose = function () {
  75564. this.getGBuffer().dispose();
  75565. };
  75566. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  75567. var _this = this;
  75568. var engine = this._scene.getEngine();
  75569. var count = this._enablePosition ? 3 : 2;
  75570. 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 });
  75571. if (!this.isSupported) {
  75572. return;
  75573. }
  75574. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75575. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75576. this._multiRenderTarget.refreshRate = 1;
  75577. this._multiRenderTarget.renderParticles = false;
  75578. this._multiRenderTarget.renderList = null;
  75579. // set default depth value to 1.0 (far away)
  75580. this._multiRenderTarget.onClearObservable.add(function (engine) {
  75581. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  75582. });
  75583. // Custom render function
  75584. var renderSubMesh = function (subMesh) {
  75585. var mesh = subMesh.getRenderingMesh();
  75586. var scene = _this._scene;
  75587. var engine = scene.getEngine();
  75588. var material = subMesh.getMaterial();
  75589. if (!material) {
  75590. return;
  75591. }
  75592. // Culling
  75593. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  75594. // Managing instances
  75595. var batch = mesh._getInstancesRenderList(subMesh._id);
  75596. if (batch.mustReturn) {
  75597. return;
  75598. }
  75599. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  75600. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  75601. engine.enableEffect(_this._effect);
  75602. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  75603. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  75604. _this._effect.setMatrix("view", scene.getViewMatrix());
  75605. // Alpha test
  75606. if (material && material.needAlphaTesting()) {
  75607. var alphaTexture = material.getAlphaTestTexture();
  75608. if (alphaTexture) {
  75609. _this._effect.setTexture("diffuseSampler", alphaTexture);
  75610. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  75611. }
  75612. }
  75613. // Bones
  75614. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  75615. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  75616. }
  75617. // Draw
  75618. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75619. }
  75620. };
  75621. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75622. var index;
  75623. if (depthOnlySubMeshes.length) {
  75624. engine.setColorWrite(false);
  75625. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75626. renderSubMesh(depthOnlySubMeshes.data[index]);
  75627. }
  75628. engine.setColorWrite(true);
  75629. }
  75630. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75631. renderSubMesh(opaqueSubMeshes.data[index]);
  75632. }
  75633. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75634. renderSubMesh(alphaTestSubMeshes.data[index]);
  75635. }
  75636. };
  75637. };
  75638. return GeometryBufferRenderer;
  75639. }());
  75640. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  75641. })(BABYLON || (BABYLON = {}));
  75642. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  75643. var BABYLON;
  75644. (function (BABYLON) {
  75645. var RefractionPostProcess = /** @class */ (function (_super) {
  75646. __extends(RefractionPostProcess, _super);
  75647. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  75648. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  75649. _this.color = color;
  75650. _this.depth = depth;
  75651. _this.colorLevel = colorLevel;
  75652. _this._ownRefractionTexture = true;
  75653. _this.onActivateObservable.add(function (cam) {
  75654. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  75655. });
  75656. _this.onApplyObservable.add(function (effect) {
  75657. effect.setColor3("baseColor", _this.color);
  75658. effect.setFloat("depth", _this.depth);
  75659. effect.setFloat("colorLevel", _this.colorLevel);
  75660. effect.setTexture("refractionSampler", _this._refTexture);
  75661. });
  75662. return _this;
  75663. }
  75664. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  75665. /**
  75666. * Gets or sets the refraction texture
  75667. * Please note that you are responsible for disposing the texture if you set it manually
  75668. */
  75669. get: function () {
  75670. return this._refTexture;
  75671. },
  75672. set: function (value) {
  75673. if (this._refTexture && this._ownRefractionTexture) {
  75674. this._refTexture.dispose();
  75675. }
  75676. this._refTexture = value;
  75677. this._ownRefractionTexture = false;
  75678. },
  75679. enumerable: true,
  75680. configurable: true
  75681. });
  75682. // Methods
  75683. RefractionPostProcess.prototype.dispose = function (camera) {
  75684. if (this._refTexture && this._ownRefractionTexture) {
  75685. this._refTexture.dispose();
  75686. this._refTexture = null;
  75687. }
  75688. _super.prototype.dispose.call(this, camera);
  75689. };
  75690. return RefractionPostProcess;
  75691. }(BABYLON.PostProcess));
  75692. BABYLON.RefractionPostProcess = RefractionPostProcess;
  75693. })(BABYLON || (BABYLON = {}));
  75694. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  75695. var BABYLON;
  75696. (function (BABYLON) {
  75697. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  75698. __extends(BlackAndWhitePostProcess, _super);
  75699. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  75700. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  75701. _this.degree = 1;
  75702. _this.onApplyObservable.add(function (effect) {
  75703. effect.setFloat("degree", _this.degree);
  75704. });
  75705. return _this;
  75706. }
  75707. return BlackAndWhitePostProcess;
  75708. }(BABYLON.PostProcess));
  75709. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  75710. })(BABYLON || (BABYLON = {}));
  75711. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  75712. var BABYLON;
  75713. (function (BABYLON) {
  75714. /**
  75715. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  75716. * input texture to perform effects such as edge detection or sharpening
  75717. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75718. */
  75719. var ConvolutionPostProcess = /** @class */ (function (_super) {
  75720. __extends(ConvolutionPostProcess, _super);
  75721. /**
  75722. * Creates a new instance ConvolutionPostProcess
  75723. * @param name The name of the effect.
  75724. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  75725. * @param options The required width/height ratio to downsize to before computing the render pass.
  75726. * @param camera The camera to apply the render pass to.
  75727. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75728. * @param engine The engine which the post process will be applied. (default: current engine)
  75729. * @param reusable If the post process can be reused on the same frame. (default: false)
  75730. * @param textureType Type of textures used when performing the post process. (default: 0)
  75731. */
  75732. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  75733. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75734. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  75735. _this.kernel = kernel;
  75736. _this.onApply = function (effect) {
  75737. effect.setFloat2("screenSize", _this.width, _this.height);
  75738. effect.setArray("kernel", _this.kernel);
  75739. };
  75740. return _this;
  75741. }
  75742. // Statics
  75743. /**
  75744. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75745. */
  75746. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  75747. /**
  75748. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75749. */
  75750. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  75751. /**
  75752. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75753. */
  75754. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  75755. /**
  75756. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75757. */
  75758. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  75759. /**
  75760. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75761. */
  75762. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  75763. /**
  75764. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  75765. */
  75766. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  75767. return ConvolutionPostProcess;
  75768. }(BABYLON.PostProcess));
  75769. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  75770. })(BABYLON || (BABYLON = {}));
  75771. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  75772. var BABYLON;
  75773. (function (BABYLON) {
  75774. var FilterPostProcess = /** @class */ (function (_super) {
  75775. __extends(FilterPostProcess, _super);
  75776. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  75777. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  75778. _this.kernelMatrix = kernelMatrix;
  75779. _this.onApply = function (effect) {
  75780. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  75781. };
  75782. return _this;
  75783. }
  75784. return FilterPostProcess;
  75785. }(BABYLON.PostProcess));
  75786. BABYLON.FilterPostProcess = FilterPostProcess;
  75787. })(BABYLON || (BABYLON = {}));
  75788. //# sourceMappingURL=babylon.filterPostProcess.js.map
  75789. var BABYLON;
  75790. (function (BABYLON) {
  75791. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  75792. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  75793. __extends(VolumetricLightScatteringPostProcess, _super);
  75794. /**
  75795. * @constructor
  75796. * @param {string} name - The post-process name
  75797. * @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)
  75798. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  75799. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  75800. * @param {number} samples - The post-process quality, default 100
  75801. * @param {number} samplingMode - The post-process filtering mode
  75802. * @param {BABYLON.Engine} engine - The babylon engine
  75803. * @param {boolean} reusable - If the post-process is reusable
  75804. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  75805. */
  75806. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  75807. if (samples === void 0) { samples = 100; }
  75808. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75809. 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;
  75810. _this._screenCoordinates = BABYLON.Vector2.Zero();
  75811. /**
  75812. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  75813. */
  75814. _this.customMeshPosition = BABYLON.Vector3.Zero();
  75815. /**
  75816. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  75817. */
  75818. _this.useCustomMeshPosition = false;
  75819. /**
  75820. * If the post-process should inverse the light scattering direction
  75821. */
  75822. _this.invert = true;
  75823. /**
  75824. * Array containing the excluded meshes not rendered in the internal pass
  75825. */
  75826. _this.excludedMeshes = new Array();
  75827. /**
  75828. * Controls the overall intensity of the post-process
  75829. */
  75830. _this.exposure = 0.3;
  75831. /**
  75832. * Dissipates each sample's contribution in range [0, 1]
  75833. */
  75834. _this.decay = 0.96815;
  75835. /**
  75836. * Controls the overall intensity of each sample
  75837. */
  75838. _this.weight = 0.58767;
  75839. /**
  75840. * Controls the density of each sample
  75841. */
  75842. _this.density = 0.926;
  75843. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  75844. engine = scene.getEngine();
  75845. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  75846. // Configure mesh
  75847. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  75848. // Configure
  75849. _this._createPass(scene, ratio.passRatio || ratio);
  75850. _this.onActivate = function (camera) {
  75851. if (!_this.isSupported) {
  75852. _this.dispose(camera);
  75853. }
  75854. _this.onActivate = null;
  75855. };
  75856. _this.onApplyObservable.add(function (effect) {
  75857. _this._updateMeshScreenCoordinates(scene);
  75858. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  75859. effect.setFloat("exposure", _this.exposure);
  75860. effect.setFloat("decay", _this.decay);
  75861. effect.setFloat("weight", _this.weight);
  75862. effect.setFloat("density", _this.density);
  75863. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  75864. });
  75865. return _this;
  75866. }
  75867. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  75868. get: function () {
  75869. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75870. return false;
  75871. },
  75872. set: function (useDiffuseColor) {
  75873. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  75874. },
  75875. enumerable: true,
  75876. configurable: true
  75877. });
  75878. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  75879. return "VolumetricLightScatteringPostProcess";
  75880. };
  75881. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  75882. var mesh = subMesh.getMesh();
  75883. // Render this.mesh as default
  75884. if (mesh === this.mesh && mesh.material) {
  75885. return mesh.material.isReady(mesh);
  75886. }
  75887. var defines = [];
  75888. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75889. var material = subMesh.getMaterial();
  75890. // Alpha test
  75891. if (material) {
  75892. if (material.needAlphaTesting()) {
  75893. defines.push("#define ALPHATEST");
  75894. }
  75895. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75896. attribs.push(BABYLON.VertexBuffer.UVKind);
  75897. defines.push("#define UV1");
  75898. }
  75899. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75900. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75901. defines.push("#define UV2");
  75902. }
  75903. }
  75904. // Bones
  75905. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75906. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75907. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75908. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75909. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  75910. }
  75911. else {
  75912. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75913. }
  75914. // Instances
  75915. if (useInstances) {
  75916. defines.push("#define INSTANCES");
  75917. attribs.push("world0");
  75918. attribs.push("world1");
  75919. attribs.push("world2");
  75920. attribs.push("world3");
  75921. }
  75922. // Get correct effect
  75923. var join = defines.join("\n");
  75924. if (this._cachedDefines !== join) {
  75925. this._cachedDefines = join;
  75926. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  75927. }
  75928. return this._volumetricLightScatteringPass.isReady();
  75929. };
  75930. /**
  75931. * Sets the new light position for light scattering effect
  75932. * @param {BABYLON.Vector3} The new custom light position
  75933. */
  75934. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  75935. this.customMeshPosition = position;
  75936. };
  75937. /**
  75938. * Returns the light position for light scattering effect
  75939. * @return {BABYLON.Vector3} The custom light position
  75940. */
  75941. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  75942. return this.customMeshPosition;
  75943. };
  75944. /**
  75945. * Disposes the internal assets and detaches the post-process from the camera
  75946. */
  75947. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  75948. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  75949. if (rttIndex !== -1) {
  75950. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  75951. }
  75952. this._volumetricLightScatteringRTT.dispose();
  75953. _super.prototype.dispose.call(this, camera);
  75954. };
  75955. /**
  75956. * Returns the render target texture used by the post-process
  75957. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  75958. */
  75959. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  75960. return this._volumetricLightScatteringRTT;
  75961. };
  75962. // Private methods
  75963. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  75964. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  75965. return true;
  75966. }
  75967. return false;
  75968. };
  75969. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  75970. var _this = this;
  75971. var engine = scene.getEngine();
  75972. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  75973. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75974. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75975. this._volumetricLightScatteringRTT.renderList = null;
  75976. this._volumetricLightScatteringRTT.renderParticles = false;
  75977. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  75978. var camera = this.getCamera();
  75979. if (camera) {
  75980. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75981. }
  75982. else {
  75983. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  75984. }
  75985. // Custom render function for submeshes
  75986. var renderSubMesh = function (subMesh) {
  75987. var mesh = subMesh.getRenderingMesh();
  75988. if (_this._meshExcluded(mesh)) {
  75989. return;
  75990. }
  75991. var material = subMesh.getMaterial();
  75992. if (!material) {
  75993. return;
  75994. }
  75995. var scene = mesh.getScene();
  75996. var engine = scene.getEngine();
  75997. // Culling
  75998. engine.setState(material.backFaceCulling);
  75999. // Managing instances
  76000. var batch = mesh._getInstancesRenderList(subMesh._id);
  76001. if (batch.mustReturn) {
  76002. return;
  76003. }
  76004. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76005. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76006. var effect = _this._volumetricLightScatteringPass;
  76007. if (mesh === _this.mesh) {
  76008. if (subMesh.effect) {
  76009. effect = subMesh.effect;
  76010. }
  76011. else {
  76012. effect = material.getEffect();
  76013. }
  76014. }
  76015. engine.enableEffect(effect);
  76016. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76017. if (mesh === _this.mesh) {
  76018. material.bind(mesh.getWorldMatrix(), mesh);
  76019. }
  76020. else {
  76021. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76022. // Alpha test
  76023. if (material && material.needAlphaTesting()) {
  76024. var alphaTexture = material.getAlphaTestTexture();
  76025. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76026. if (alphaTexture) {
  76027. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76028. }
  76029. }
  76030. // Bones
  76031. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76032. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76033. }
  76034. }
  76035. // Draw
  76036. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76037. }
  76038. };
  76039. // Render target texture callbacks
  76040. var savedSceneClearColor;
  76041. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76042. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76043. savedSceneClearColor = scene.clearColor;
  76044. scene.clearColor = sceneClearColor;
  76045. });
  76046. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76047. scene.clearColor = savedSceneClearColor;
  76048. });
  76049. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76050. var engine = scene.getEngine();
  76051. var index;
  76052. if (depthOnlySubMeshes.length) {
  76053. engine.setColorWrite(false);
  76054. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76055. renderSubMesh(depthOnlySubMeshes.data[index]);
  76056. }
  76057. engine.setColorWrite(true);
  76058. }
  76059. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76060. renderSubMesh(opaqueSubMeshes.data[index]);
  76061. }
  76062. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76063. renderSubMesh(alphaTestSubMeshes.data[index]);
  76064. }
  76065. if (transparentSubMeshes.length) {
  76066. // Sort sub meshes
  76067. for (index = 0; index < transparentSubMeshes.length; index++) {
  76068. var submesh = transparentSubMeshes.data[index];
  76069. var boundingInfo = submesh.getBoundingInfo();
  76070. if (boundingInfo && scene.activeCamera) {
  76071. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76072. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76073. }
  76074. }
  76075. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76076. sortedArray.sort(function (a, b) {
  76077. // Alpha index first
  76078. if (a._alphaIndex > b._alphaIndex) {
  76079. return 1;
  76080. }
  76081. if (a._alphaIndex < b._alphaIndex) {
  76082. return -1;
  76083. }
  76084. // Then distance to camera
  76085. if (a._distanceToCamera < b._distanceToCamera) {
  76086. return 1;
  76087. }
  76088. if (a._distanceToCamera > b._distanceToCamera) {
  76089. return -1;
  76090. }
  76091. return 0;
  76092. });
  76093. // Render sub meshes
  76094. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76095. for (index = 0; index < sortedArray.length; index++) {
  76096. renderSubMesh(sortedArray[index]);
  76097. }
  76098. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76099. }
  76100. };
  76101. };
  76102. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76103. var transform = scene.getTransformMatrix();
  76104. var meshPosition;
  76105. if (this.useCustomMeshPosition) {
  76106. meshPosition = this.customMeshPosition;
  76107. }
  76108. else if (this.attachedNode) {
  76109. meshPosition = this.attachedNode.position;
  76110. }
  76111. else {
  76112. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76113. }
  76114. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76115. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76116. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76117. if (this.invert)
  76118. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76119. };
  76120. // Static methods
  76121. /**
  76122. * Creates a default mesh for the Volumeric Light Scattering post-process
  76123. * @param {string} The mesh name
  76124. * @param {BABYLON.Scene} The scene where to create the mesh
  76125. * @return {BABYLON.Mesh} the default mesh
  76126. */
  76127. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76128. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76129. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76130. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76131. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76132. mesh.material = material;
  76133. return mesh;
  76134. };
  76135. __decorate([
  76136. BABYLON.serializeAsVector3()
  76137. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76138. __decorate([
  76139. BABYLON.serialize()
  76140. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76141. __decorate([
  76142. BABYLON.serialize()
  76143. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76144. __decorate([
  76145. BABYLON.serializeAsMeshReference()
  76146. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76147. __decorate([
  76148. BABYLON.serialize()
  76149. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76150. __decorate([
  76151. BABYLON.serialize()
  76152. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76153. __decorate([
  76154. BABYLON.serialize()
  76155. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76156. __decorate([
  76157. BABYLON.serialize()
  76158. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76159. __decorate([
  76160. BABYLON.serialize()
  76161. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76162. return VolumetricLightScatteringPostProcess;
  76163. }(BABYLON.PostProcess));
  76164. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76165. })(BABYLON || (BABYLON = {}));
  76166. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76167. //
  76168. // This post-process allows the modification of rendered colors by using
  76169. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76170. //
  76171. // The object needs to be provided an url to a texture containing the color
  76172. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76173. // Use an image editing software to tweak the LUT to match your needs.
  76174. //
  76175. // For an example of a color LUT, see here:
  76176. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76177. // For explanations on color grading, see here:
  76178. // http://udn.epicgames.com/Three/ColorGrading.html
  76179. //
  76180. var BABYLON;
  76181. (function (BABYLON) {
  76182. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76183. __extends(ColorCorrectionPostProcess, _super);
  76184. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76185. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76186. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76187. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76188. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76189. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76190. _this.onApply = function (effect) {
  76191. effect.setTexture("colorTable", _this._colorTableTexture);
  76192. };
  76193. return _this;
  76194. }
  76195. return ColorCorrectionPostProcess;
  76196. }(BABYLON.PostProcess));
  76197. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76198. })(BABYLON || (BABYLON = {}));
  76199. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76200. var BABYLON;
  76201. (function (BABYLON) {
  76202. /** Defines operator used for tonemapping */
  76203. var TonemappingOperator;
  76204. (function (TonemappingOperator) {
  76205. /** Hable */
  76206. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76207. /** Reinhard */
  76208. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76209. /** HejiDawson */
  76210. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76211. /** Photographic */
  76212. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76213. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76214. ;
  76215. /**
  76216. * Defines a post process to apply tone mapping
  76217. */
  76218. var TonemapPostProcess = /** @class */ (function (_super) {
  76219. __extends(TonemapPostProcess, _super);
  76220. /**
  76221. * Creates a new TonemapPostProcess
  76222. * @param name defines the name of the postprocess
  76223. * @param _operator defines the operator to use
  76224. * @param exposureAdjustment defines the required exposure adjustement
  76225. * @param camera defines the camera to use (can be null)
  76226. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76227. * @param engine defines the hosting engine (can be ignore if camera is set)
  76228. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76229. */
  76230. function TonemapPostProcess(name, _operator,
  76231. /** Defines the required exposure adjustement */
  76232. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76233. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76234. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76235. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76236. _this._operator = _operator;
  76237. _this.exposureAdjustment = exposureAdjustment;
  76238. var defines = "#define ";
  76239. if (_this._operator === TonemappingOperator.Hable)
  76240. defines += "HABLE_TONEMAPPING";
  76241. else if (_this._operator === TonemappingOperator.Reinhard)
  76242. defines += "REINHARD_TONEMAPPING";
  76243. else if (_this._operator === TonemappingOperator.HejiDawson)
  76244. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76245. else if (_this._operator === TonemappingOperator.Photographic)
  76246. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76247. //sadly a second call to create the effect.
  76248. _this.updateEffect(defines);
  76249. _this.onApply = function (effect) {
  76250. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76251. };
  76252. return _this;
  76253. }
  76254. return TonemapPostProcess;
  76255. }(BABYLON.PostProcess));
  76256. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76257. })(BABYLON || (BABYLON = {}));
  76258. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76259. var BABYLON;
  76260. (function (BABYLON) {
  76261. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76262. __extends(DisplayPassPostProcess, _super);
  76263. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76264. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76265. }
  76266. return DisplayPassPostProcess;
  76267. }(BABYLON.PostProcess));
  76268. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76269. })(BABYLON || (BABYLON = {}));
  76270. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76271. var BABYLON;
  76272. (function (BABYLON) {
  76273. var HighlightsPostProcess = /** @class */ (function (_super) {
  76274. __extends(HighlightsPostProcess, _super);
  76275. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76276. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76277. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76278. }
  76279. return HighlightsPostProcess;
  76280. }(BABYLON.PostProcess));
  76281. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76282. })(BABYLON || (BABYLON = {}));
  76283. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76284. var BABYLON;
  76285. (function (BABYLON) {
  76286. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76287. __extends(ImageProcessingPostProcess, _super);
  76288. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76289. if (camera === void 0) { camera = null; }
  76290. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76291. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76292. _this._fromLinearSpace = true;
  76293. /**
  76294. * Defines cache preventing GC.
  76295. */
  76296. _this._defines = {
  76297. IMAGEPROCESSING: false,
  76298. VIGNETTE: false,
  76299. VIGNETTEBLENDMODEMULTIPLY: false,
  76300. VIGNETTEBLENDMODEOPAQUE: false,
  76301. TONEMAPPING: false,
  76302. CONTRAST: false,
  76303. COLORCURVES: false,
  76304. COLORGRADING: false,
  76305. COLORGRADING3D: false,
  76306. FROMLINEARSPACE: false,
  76307. SAMPLER3DGREENDEPTH: false,
  76308. SAMPLER3DBGRMAP: false,
  76309. IMAGEPROCESSINGPOSTPROCESS: false,
  76310. EXPOSURE: false,
  76311. };
  76312. // Setup the configuration as forced by the constructor. This would then not force the
  76313. // scene materials output in linear space and let untouched the default forward pass.
  76314. if (imageProcessingConfiguration) {
  76315. imageProcessingConfiguration.applyByPostProcess = true;
  76316. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76317. // This will cause the shader to be compiled
  76318. _this.fromLinearSpace = false;
  76319. }
  76320. // Setup the default processing configuration to the scene.
  76321. else {
  76322. _this._attachImageProcessingConfiguration(null, true);
  76323. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76324. }
  76325. _this.onApply = function (effect) {
  76326. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76327. };
  76328. return _this;
  76329. }
  76330. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76331. /**
  76332. * Gets the image processing configuration used either in this material.
  76333. */
  76334. get: function () {
  76335. return this._imageProcessingConfiguration;
  76336. },
  76337. /**
  76338. * Sets the Default image processing configuration used either in the this material.
  76339. *
  76340. * If sets to null, the scene one is in use.
  76341. */
  76342. set: function (value) {
  76343. this._attachImageProcessingConfiguration(value);
  76344. },
  76345. enumerable: true,
  76346. configurable: true
  76347. });
  76348. /**
  76349. * Attaches a new image processing configuration to the PBR Material.
  76350. * @param configuration
  76351. */
  76352. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76353. var _this = this;
  76354. if (doNotBuild === void 0) { doNotBuild = false; }
  76355. if (configuration === this._imageProcessingConfiguration) {
  76356. return;
  76357. }
  76358. // Detaches observer.
  76359. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76360. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76361. }
  76362. // Pick the scene configuration if needed.
  76363. if (!configuration) {
  76364. var scene = null;
  76365. var engine = this.getEngine();
  76366. var camera = this.getCamera();
  76367. if (camera) {
  76368. scene = camera.getScene();
  76369. }
  76370. else if (engine && engine.scenes) {
  76371. var scenes = engine.scenes;
  76372. scene = scenes[scenes.length - 1];
  76373. }
  76374. else {
  76375. scene = BABYLON.Engine.LastCreatedScene;
  76376. }
  76377. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76378. }
  76379. else {
  76380. this._imageProcessingConfiguration = configuration;
  76381. }
  76382. // Attaches observer.
  76383. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76384. _this._updateParameters();
  76385. });
  76386. // Ensure the effect will be rebuilt.
  76387. if (!doNotBuild) {
  76388. this._updateParameters();
  76389. }
  76390. };
  76391. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76392. /**
  76393. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76394. */
  76395. get: function () {
  76396. return this.imageProcessingConfiguration.colorCurves;
  76397. },
  76398. /**
  76399. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76400. */
  76401. set: function (value) {
  76402. this.imageProcessingConfiguration.colorCurves = value;
  76403. },
  76404. enumerable: true,
  76405. configurable: true
  76406. });
  76407. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76408. /**
  76409. * Gets wether the color curves effect is enabled.
  76410. */
  76411. get: function () {
  76412. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76413. },
  76414. /**
  76415. * Sets wether the color curves effect is enabled.
  76416. */
  76417. set: function (value) {
  76418. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76419. },
  76420. enumerable: true,
  76421. configurable: true
  76422. });
  76423. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76424. /**
  76425. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76426. */
  76427. get: function () {
  76428. return this.imageProcessingConfiguration.colorGradingTexture;
  76429. },
  76430. /**
  76431. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76432. */
  76433. set: function (value) {
  76434. this.imageProcessingConfiguration.colorGradingTexture = value;
  76435. },
  76436. enumerable: true,
  76437. configurable: true
  76438. });
  76439. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76440. /**
  76441. * Gets wether the color grading effect is enabled.
  76442. */
  76443. get: function () {
  76444. return this.imageProcessingConfiguration.colorGradingEnabled;
  76445. },
  76446. /**
  76447. * Gets wether the color grading effect is enabled.
  76448. */
  76449. set: function (value) {
  76450. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76451. },
  76452. enumerable: true,
  76453. configurable: true
  76454. });
  76455. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76456. /**
  76457. * Gets exposure used in the effect.
  76458. */
  76459. get: function () {
  76460. return this.imageProcessingConfiguration.exposure;
  76461. },
  76462. /**
  76463. * Sets exposure used in the effect.
  76464. */
  76465. set: function (value) {
  76466. this.imageProcessingConfiguration.exposure = value;
  76467. },
  76468. enumerable: true,
  76469. configurable: true
  76470. });
  76471. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  76472. /**
  76473. * Gets wether tonemapping is enabled or not.
  76474. */
  76475. get: function () {
  76476. return this._imageProcessingConfiguration.toneMappingEnabled;
  76477. },
  76478. /**
  76479. * Sets wether tonemapping is enabled or not
  76480. */
  76481. set: function (value) {
  76482. this._imageProcessingConfiguration.toneMappingEnabled = value;
  76483. },
  76484. enumerable: true,
  76485. configurable: true
  76486. });
  76487. ;
  76488. ;
  76489. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  76490. /**
  76491. * Gets contrast used in the effect.
  76492. */
  76493. get: function () {
  76494. return this.imageProcessingConfiguration.contrast;
  76495. },
  76496. /**
  76497. * Sets contrast used in the effect.
  76498. */
  76499. set: function (value) {
  76500. this.imageProcessingConfiguration.contrast = value;
  76501. },
  76502. enumerable: true,
  76503. configurable: true
  76504. });
  76505. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  76506. /**
  76507. * Gets Vignette stretch size.
  76508. */
  76509. get: function () {
  76510. return this.imageProcessingConfiguration.vignetteStretch;
  76511. },
  76512. /**
  76513. * Sets Vignette stretch size.
  76514. */
  76515. set: function (value) {
  76516. this.imageProcessingConfiguration.vignetteStretch = value;
  76517. },
  76518. enumerable: true,
  76519. configurable: true
  76520. });
  76521. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  76522. /**
  76523. * Gets Vignette centre X Offset.
  76524. */
  76525. get: function () {
  76526. return this.imageProcessingConfiguration.vignetteCentreX;
  76527. },
  76528. /**
  76529. * Sets Vignette centre X Offset.
  76530. */
  76531. set: function (value) {
  76532. this.imageProcessingConfiguration.vignetteCentreX = value;
  76533. },
  76534. enumerable: true,
  76535. configurable: true
  76536. });
  76537. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  76538. /**
  76539. * Gets Vignette centre Y Offset.
  76540. */
  76541. get: function () {
  76542. return this.imageProcessingConfiguration.vignetteCentreY;
  76543. },
  76544. /**
  76545. * Sets Vignette centre Y Offset.
  76546. */
  76547. set: function (value) {
  76548. this.imageProcessingConfiguration.vignetteCentreY = value;
  76549. },
  76550. enumerable: true,
  76551. configurable: true
  76552. });
  76553. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  76554. /**
  76555. * Gets Vignette weight or intensity of the vignette effect.
  76556. */
  76557. get: function () {
  76558. return this.imageProcessingConfiguration.vignetteWeight;
  76559. },
  76560. /**
  76561. * Sets Vignette weight or intensity of the vignette effect.
  76562. */
  76563. set: function (value) {
  76564. this.imageProcessingConfiguration.vignetteWeight = value;
  76565. },
  76566. enumerable: true,
  76567. configurable: true
  76568. });
  76569. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  76570. /**
  76571. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76572. * if vignetteEnabled is set to true.
  76573. */
  76574. get: function () {
  76575. return this.imageProcessingConfiguration.vignetteColor;
  76576. },
  76577. /**
  76578. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  76579. * if vignetteEnabled is set to true.
  76580. */
  76581. set: function (value) {
  76582. this.imageProcessingConfiguration.vignetteColor = value;
  76583. },
  76584. enumerable: true,
  76585. configurable: true
  76586. });
  76587. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  76588. /**
  76589. * Gets Camera field of view used by the Vignette effect.
  76590. */
  76591. get: function () {
  76592. return this.imageProcessingConfiguration.vignetteCameraFov;
  76593. },
  76594. /**
  76595. * Sets Camera field of view used by the Vignette effect.
  76596. */
  76597. set: function (value) {
  76598. this.imageProcessingConfiguration.vignetteCameraFov = value;
  76599. },
  76600. enumerable: true,
  76601. configurable: true
  76602. });
  76603. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  76604. /**
  76605. * Gets the vignette blend mode allowing different kind of effect.
  76606. */
  76607. get: function () {
  76608. return this.imageProcessingConfiguration.vignetteBlendMode;
  76609. },
  76610. /**
  76611. * Sets the vignette blend mode allowing different kind of effect.
  76612. */
  76613. set: function (value) {
  76614. this.imageProcessingConfiguration.vignetteBlendMode = value;
  76615. },
  76616. enumerable: true,
  76617. configurable: true
  76618. });
  76619. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  76620. /**
  76621. * Gets wether the vignette effect is enabled.
  76622. */
  76623. get: function () {
  76624. return this.imageProcessingConfiguration.vignetteEnabled;
  76625. },
  76626. /**
  76627. * Sets wether the vignette effect is enabled.
  76628. */
  76629. set: function (value) {
  76630. this.imageProcessingConfiguration.vignetteEnabled = value;
  76631. },
  76632. enumerable: true,
  76633. configurable: true
  76634. });
  76635. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  76636. /**
  76637. * Gets wether the input of the processing is in Gamma or Linear Space.
  76638. */
  76639. get: function () {
  76640. return this._fromLinearSpace;
  76641. },
  76642. /**
  76643. * Sets wether the input of the processing is in Gamma or Linear Space.
  76644. */
  76645. set: function (value) {
  76646. if (this._fromLinearSpace === value) {
  76647. return;
  76648. }
  76649. this._fromLinearSpace = value;
  76650. this._updateParameters();
  76651. },
  76652. enumerable: true,
  76653. configurable: true
  76654. });
  76655. ImageProcessingPostProcess.prototype.getClassName = function () {
  76656. return "ImageProcessingPostProcess";
  76657. };
  76658. ImageProcessingPostProcess.prototype._updateParameters = function () {
  76659. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  76660. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  76661. var defines = "";
  76662. for (var define in this._defines) {
  76663. if (this._defines[define]) {
  76664. defines += "#define " + define + ";\r\n";
  76665. }
  76666. }
  76667. var samplers = ["textureSampler"];
  76668. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  76669. var uniforms = ["scale"];
  76670. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  76671. this.updateEffect(defines, uniforms, samplers);
  76672. };
  76673. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  76674. _super.prototype.dispose.call(this, camera);
  76675. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76676. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76677. }
  76678. this.imageProcessingConfiguration.applyByPostProcess = false;
  76679. };
  76680. __decorate([
  76681. BABYLON.serialize()
  76682. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  76683. return ImageProcessingPostProcess;
  76684. }(BABYLON.PostProcess));
  76685. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  76686. })(BABYLON || (BABYLON = {}));
  76687. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  76688. var BABYLON;
  76689. (function (BABYLON) {
  76690. /**
  76691. * Class used to store bone information
  76692. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  76693. */
  76694. var Bone = /** @class */ (function (_super) {
  76695. __extends(Bone, _super);
  76696. /**
  76697. * Create a new bone
  76698. * @param name defines the bone name
  76699. * @param skeleton defines the parent skeleton
  76700. * @param parentBone defines the parent (can be null if the bone is the root)
  76701. * @param localMatrix defines the local matrix
  76702. * @param restPose defines the rest pose matrix
  76703. * @param baseMatrix defines the base matrix
  76704. * @param index defines index of the bone in the hiearchy
  76705. */
  76706. function Bone(
  76707. /**
  76708. * defines the bone name
  76709. */
  76710. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  76711. if (parentBone === void 0) { parentBone = null; }
  76712. if (localMatrix === void 0) { localMatrix = null; }
  76713. if (restPose === void 0) { restPose = null; }
  76714. if (baseMatrix === void 0) { baseMatrix = null; }
  76715. if (index === void 0) { index = null; }
  76716. var _this = _super.call(this, name, skeleton.getScene()) || this;
  76717. _this.name = name;
  76718. /**
  76719. * Gets the list of child bones
  76720. */
  76721. _this.children = new Array();
  76722. /** Gets the animations associated with this bone */
  76723. _this.animations = new Array();
  76724. /**
  76725. * @ignore Internal only
  76726. * Set this value to map this bone to a different index in the transform matrices
  76727. * Set this value to -1 to exclude the bone from the transform matrices
  76728. */
  76729. _this._index = null;
  76730. _this._absoluteTransform = new BABYLON.Matrix();
  76731. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  76732. _this._scalingDeterminant = 1;
  76733. _this._worldTransform = new BABYLON.Matrix();
  76734. _this._needToDecompose = true;
  76735. _this._needToCompose = false;
  76736. _this._skeleton = skeleton;
  76737. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  76738. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  76739. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  76740. _this._index = index;
  76741. skeleton.bones.push(_this);
  76742. _this.setParent(parentBone, false);
  76743. if (baseMatrix || localMatrix) {
  76744. _this._updateDifferenceMatrix();
  76745. }
  76746. return _this;
  76747. }
  76748. Object.defineProperty(Bone.prototype, "_matrix", {
  76749. /** @ignore */
  76750. get: function () {
  76751. this._compose();
  76752. return this._localMatrix;
  76753. },
  76754. /** @ignore */
  76755. set: function (value) {
  76756. this._localMatrix.copyFrom(value);
  76757. this._needToDecompose = true;
  76758. },
  76759. enumerable: true,
  76760. configurable: true
  76761. });
  76762. // Members
  76763. /**
  76764. * Gets the parent skeleton
  76765. * @returns a skeleton
  76766. */
  76767. Bone.prototype.getSkeleton = function () {
  76768. return this._skeleton;
  76769. };
  76770. /**
  76771. * Gets parent bone
  76772. * @returns a bone or null if the bone is the root of the bone hierarchy
  76773. */
  76774. Bone.prototype.getParent = function () {
  76775. return this._parent;
  76776. };
  76777. /**
  76778. * Sets the parent bone
  76779. * @param parent defines the parent (can be null if the bone is the root)
  76780. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76781. */
  76782. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  76783. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76784. if (this._parent === parent) {
  76785. return;
  76786. }
  76787. if (this._parent) {
  76788. var index = this._parent.children.indexOf(this);
  76789. if (index !== -1) {
  76790. this._parent.children.splice(index, 1);
  76791. }
  76792. }
  76793. this._parent = parent;
  76794. if (this._parent) {
  76795. this._parent.children.push(this);
  76796. }
  76797. if (updateDifferenceMatrix) {
  76798. this._updateDifferenceMatrix();
  76799. }
  76800. this.markAsDirty();
  76801. };
  76802. /**
  76803. * Gets the local matrix
  76804. * @returns a matrix
  76805. */
  76806. Bone.prototype.getLocalMatrix = function () {
  76807. this._compose();
  76808. return this._localMatrix;
  76809. };
  76810. /**
  76811. * Gets the base matrix (initial matrix which remains unchanged)
  76812. * @returns a matrix
  76813. */
  76814. Bone.prototype.getBaseMatrix = function () {
  76815. return this._baseMatrix;
  76816. };
  76817. /**
  76818. * Gets the rest pose matrix
  76819. * @returns a matrix
  76820. */
  76821. Bone.prototype.getRestPose = function () {
  76822. return this._restPose;
  76823. };
  76824. /**
  76825. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  76826. */
  76827. Bone.prototype.getWorldMatrix = function () {
  76828. return this._worldTransform;
  76829. };
  76830. /**
  76831. * Sets the local matrix to rest pose matrix
  76832. */
  76833. Bone.prototype.returnToRest = function () {
  76834. this.updateMatrix(this._restPose.clone());
  76835. };
  76836. /**
  76837. * Gets the inverse of the absolute transform matrix.
  76838. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  76839. * @returns a matrix
  76840. */
  76841. Bone.prototype.getInvertedAbsoluteTransform = function () {
  76842. return this._invertedAbsoluteTransform;
  76843. };
  76844. /**
  76845. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  76846. * @returns a matrix
  76847. */
  76848. Bone.prototype.getAbsoluteTransform = function () {
  76849. return this._absoluteTransform;
  76850. };
  76851. Object.defineProperty(Bone.prototype, "position", {
  76852. // Properties (matches AbstractMesh properties)
  76853. /** Gets or sets current position (in local space) */
  76854. get: function () {
  76855. this._decompose();
  76856. return this._localPosition;
  76857. },
  76858. set: function (newPosition) {
  76859. this._decompose();
  76860. this._localPosition.copyFrom(newPosition);
  76861. this._markAsDirtyAndCompose();
  76862. },
  76863. enumerable: true,
  76864. configurable: true
  76865. });
  76866. Object.defineProperty(Bone.prototype, "rotation", {
  76867. /** Gets or sets current rotation (in local space) */
  76868. get: function () {
  76869. return this.getRotation();
  76870. },
  76871. set: function (newRotation) {
  76872. this.setRotation(newRotation);
  76873. },
  76874. enumerable: true,
  76875. configurable: true
  76876. });
  76877. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  76878. /** Gets or sets current rotation quaternion (in local space) */
  76879. get: function () {
  76880. this._decompose();
  76881. return this._localRotation;
  76882. },
  76883. set: function (newRotation) {
  76884. this.setRotationQuaternion(newRotation);
  76885. },
  76886. enumerable: true,
  76887. configurable: true
  76888. });
  76889. Object.defineProperty(Bone.prototype, "scaling", {
  76890. /** Gets or sets current scaling (in local space) */
  76891. get: function () {
  76892. return this.getScale();
  76893. },
  76894. set: function (newScaling) {
  76895. this.setScale(newScaling);
  76896. },
  76897. enumerable: true,
  76898. configurable: true
  76899. });
  76900. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  76901. /**
  76902. * Gets the animation properties override
  76903. */
  76904. get: function () {
  76905. return this._skeleton.animationPropertiesOverride;
  76906. },
  76907. enumerable: true,
  76908. configurable: true
  76909. });
  76910. // Methods
  76911. Bone.prototype._decompose = function () {
  76912. if (!this._needToDecompose) {
  76913. return;
  76914. }
  76915. this._needToDecompose = false;
  76916. if (!this._localScaling) {
  76917. this._localScaling = BABYLON.Vector3.Zero();
  76918. this._localRotation = BABYLON.Quaternion.Zero();
  76919. this._localPosition = BABYLON.Vector3.Zero();
  76920. }
  76921. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  76922. };
  76923. Bone.prototype._compose = function () {
  76924. if (!this._needToCompose) {
  76925. return;
  76926. }
  76927. this._needToCompose = false;
  76928. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  76929. };
  76930. /**
  76931. * Update the base and local matrices
  76932. * @param matrix defines the new base or local matrix
  76933. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  76934. * @param updateLocalMatrix defines if the local matrix should be updated
  76935. */
  76936. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  76937. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  76938. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  76939. this._baseMatrix.copyFrom(matrix);
  76940. if (updateDifferenceMatrix) {
  76941. this._updateDifferenceMatrix();
  76942. }
  76943. if (updateLocalMatrix) {
  76944. this._localMatrix.copyFrom(matrix);
  76945. this._markAsDirtyAndDecompose();
  76946. }
  76947. else {
  76948. this.markAsDirty();
  76949. }
  76950. };
  76951. /** @ignore */
  76952. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  76953. if (updateChildren === void 0) { updateChildren = true; }
  76954. if (!rootMatrix) {
  76955. rootMatrix = this._baseMatrix;
  76956. }
  76957. if (this._parent) {
  76958. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  76959. }
  76960. else {
  76961. this._absoluteTransform.copyFrom(rootMatrix);
  76962. }
  76963. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  76964. if (updateChildren) {
  76965. for (var index = 0; index < this.children.length; index++) {
  76966. this.children[index]._updateDifferenceMatrix();
  76967. }
  76968. }
  76969. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  76970. };
  76971. /**
  76972. * Flag the bone as dirty (Forcing it to update everything)
  76973. */
  76974. Bone.prototype.markAsDirty = function () {
  76975. this._currentRenderId++;
  76976. this._childRenderId++;
  76977. this._skeleton._markAsDirty();
  76978. };
  76979. Bone.prototype._markAsDirtyAndCompose = function () {
  76980. this.markAsDirty();
  76981. this._needToCompose = true;
  76982. };
  76983. Bone.prototype._markAsDirtyAndDecompose = function () {
  76984. this.markAsDirty();
  76985. this._needToDecompose = true;
  76986. };
  76987. /**
  76988. * Copy an animation range from another bone
  76989. * @param source defines the source bone
  76990. * @param rangeName defines the range name to copy
  76991. * @param frameOffset defines the frame offset
  76992. * @param rescaleAsRequired defines if rescaling must be applied if required
  76993. * @param skelDimensionsRatio defines the scaling ratio
  76994. * @returns true if operation was successful
  76995. */
  76996. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  76997. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  76998. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  76999. // all animation may be coming from a library skeleton, so may need to create animation
  77000. if (this.animations.length === 0) {
  77001. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77002. this.animations[0].setKeys([]);
  77003. }
  77004. // get animation info / verify there is such a range from the source bone
  77005. var sourceRange = source.animations[0].getRange(rangeName);
  77006. if (!sourceRange) {
  77007. return false;
  77008. }
  77009. var from = sourceRange.from;
  77010. var to = sourceRange.to;
  77011. var sourceKeys = source.animations[0].getKeys();
  77012. // rescaling prep
  77013. var sourceBoneLength = source.length;
  77014. var sourceParent = source.getParent();
  77015. var parent = this.getParent();
  77016. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77017. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77018. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77019. var destKeys = this.animations[0].getKeys();
  77020. // loop vars declaration
  77021. var orig;
  77022. var origTranslation;
  77023. var mat;
  77024. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77025. orig = sourceKeys[key];
  77026. if (orig.frame >= from && orig.frame <= to) {
  77027. if (rescaleAsRequired) {
  77028. mat = orig.value.clone();
  77029. // scale based on parent ratio, when bone has parent
  77030. if (parentScalingReqd) {
  77031. origTranslation = mat.getTranslation();
  77032. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77033. // scale based on skeleton dimension ratio when root bone, and value is passed
  77034. }
  77035. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77036. origTranslation = mat.getTranslation();
  77037. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77038. // use original when root bone, and no data for skelDimensionsRatio
  77039. }
  77040. else {
  77041. mat = orig.value;
  77042. }
  77043. }
  77044. else {
  77045. mat = orig.value;
  77046. }
  77047. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77048. }
  77049. }
  77050. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77051. return true;
  77052. };
  77053. /**
  77054. * Translate the bone in local or world space
  77055. * @param vec The amount to translate the bone
  77056. * @param space The space that the translation is in
  77057. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77058. */
  77059. Bone.prototype.translate = function (vec, space, mesh) {
  77060. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77061. var lm = this.getLocalMatrix();
  77062. if (space == BABYLON.Space.LOCAL) {
  77063. lm.m[12] += vec.x;
  77064. lm.m[13] += vec.y;
  77065. lm.m[14] += vec.z;
  77066. }
  77067. else {
  77068. var wm = null;
  77069. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77070. if (mesh) {
  77071. wm = mesh.getWorldMatrix();
  77072. }
  77073. this._skeleton.computeAbsoluteTransforms();
  77074. var tmat = Bone._tmpMats[0];
  77075. var tvec = Bone._tmpVecs[0];
  77076. if (this._parent) {
  77077. if (mesh && wm) {
  77078. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77079. tmat.multiplyToRef(wm, tmat);
  77080. }
  77081. else {
  77082. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77083. }
  77084. }
  77085. tmat.m[12] = 0;
  77086. tmat.m[13] = 0;
  77087. tmat.m[14] = 0;
  77088. tmat.invert();
  77089. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77090. lm.m[12] += tvec.x;
  77091. lm.m[13] += tvec.y;
  77092. lm.m[14] += tvec.z;
  77093. }
  77094. this._markAsDirtyAndDecompose();
  77095. };
  77096. /**
  77097. * Set the postion of the bone in local or world space
  77098. * @param position The position to set the bone
  77099. * @param space The space that the position is in
  77100. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77101. */
  77102. Bone.prototype.setPosition = function (position, space, mesh) {
  77103. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77104. var lm = this.getLocalMatrix();
  77105. if (space == BABYLON.Space.LOCAL) {
  77106. lm.m[12] = position.x;
  77107. lm.m[13] = position.y;
  77108. lm.m[14] = position.z;
  77109. }
  77110. else {
  77111. var wm = null;
  77112. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77113. if (mesh) {
  77114. wm = mesh.getWorldMatrix();
  77115. }
  77116. this._skeleton.computeAbsoluteTransforms();
  77117. var tmat = Bone._tmpMats[0];
  77118. var vec = Bone._tmpVecs[0];
  77119. if (this._parent) {
  77120. if (mesh && wm) {
  77121. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77122. tmat.multiplyToRef(wm, tmat);
  77123. }
  77124. else {
  77125. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77126. }
  77127. }
  77128. tmat.invert();
  77129. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77130. lm.m[12] = vec.x;
  77131. lm.m[13] = vec.y;
  77132. lm.m[14] = vec.z;
  77133. }
  77134. this._markAsDirtyAndDecompose();
  77135. };
  77136. /**
  77137. * Set the absolute position of the bone (world space)
  77138. * @param position The position to set the bone
  77139. * @param mesh The mesh that this bone is attached to
  77140. */
  77141. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77142. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77143. };
  77144. /**
  77145. * Scale the bone on the x, y and z axes (in local space)
  77146. * @param x The amount to scale the bone on the x axis
  77147. * @param y The amount to scale the bone on the y axis
  77148. * @param z The amount to scale the bone on the z axis
  77149. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77150. */
  77151. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77152. if (scaleChildren === void 0) { scaleChildren = false; }
  77153. var locMat = this.getLocalMatrix();
  77154. // Apply new scaling on top of current local matrix
  77155. var scaleMat = Bone._tmpMats[0];
  77156. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77157. scaleMat.multiplyToRef(locMat, locMat);
  77158. // Invert scaling matrix and apply the inverse to all children
  77159. scaleMat.invert();
  77160. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77161. var child = _a[_i];
  77162. var cm = child.getLocalMatrix();
  77163. cm.multiplyToRef(scaleMat, cm);
  77164. cm.m[12] *= x;
  77165. cm.m[13] *= y;
  77166. cm.m[14] *= z;
  77167. child._markAsDirtyAndDecompose();
  77168. }
  77169. this._markAsDirtyAndDecompose();
  77170. if (scaleChildren) {
  77171. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77172. var child = _c[_b];
  77173. child.scale(x, y, z, scaleChildren);
  77174. }
  77175. }
  77176. };
  77177. /**
  77178. * Set the bone scaling in local space
  77179. * @param scale defines the scaling vector
  77180. */
  77181. Bone.prototype.setScale = function (scale) {
  77182. this._decompose();
  77183. this._localScaling.copyFrom(scale);
  77184. this._markAsDirtyAndCompose();
  77185. };
  77186. /**
  77187. * Gets the current scaling in local space
  77188. * @returns the current scaling vector
  77189. */
  77190. Bone.prototype.getScale = function () {
  77191. this._decompose();
  77192. return this._localScaling;
  77193. };
  77194. /**
  77195. * Gets the current scaling in local space and stores it in a target vector
  77196. * @param result defines the target vector
  77197. */
  77198. Bone.prototype.getScaleToRef = function (result) {
  77199. this._decompose();
  77200. result.copyFrom(this._localScaling);
  77201. };
  77202. /**
  77203. * Set the yaw, pitch, and roll of the bone in local or world space
  77204. * @param yaw The rotation of the bone on the y axis
  77205. * @param pitch The rotation of the bone on the x axis
  77206. * @param roll The rotation of the bone on the z axis
  77207. * @param space The space that the axes of rotation are in
  77208. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77209. */
  77210. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77211. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77212. if (space === BABYLON.Space.LOCAL) {
  77213. var quat = Bone._tmpQuat;
  77214. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77215. this.setRotationQuaternion(quat, space, mesh);
  77216. return;
  77217. }
  77218. var rotMatInv = Bone._tmpMats[0];
  77219. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77220. return;
  77221. }
  77222. var rotMat = Bone._tmpMats[1];
  77223. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77224. rotMatInv.multiplyToRef(rotMat, rotMat);
  77225. this._rotateWithMatrix(rotMat, space, mesh);
  77226. };
  77227. /**
  77228. * Add a rotation to the bone on an axis in local or world space
  77229. * @param axis The axis to rotate the bone on
  77230. * @param amount The amount to rotate the bone
  77231. * @param space The space that the axis is in
  77232. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77233. */
  77234. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77235. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77236. var rmat = Bone._tmpMats[0];
  77237. rmat.m[12] = 0;
  77238. rmat.m[13] = 0;
  77239. rmat.m[14] = 0;
  77240. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77241. this._rotateWithMatrix(rmat, space, mesh);
  77242. };
  77243. /**
  77244. * Set the rotation of the bone to a particular axis angle in local or world space
  77245. * @param axis The axis to rotate the bone on
  77246. * @param angle The angle that the bone should be rotated to
  77247. * @param space The space that the axis is in
  77248. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77249. */
  77250. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77251. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77252. if (space === BABYLON.Space.LOCAL) {
  77253. var quat = Bone._tmpQuat;
  77254. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77255. this.setRotationQuaternion(quat, space, mesh);
  77256. return;
  77257. }
  77258. var rotMatInv = Bone._tmpMats[0];
  77259. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77260. return;
  77261. }
  77262. var rotMat = Bone._tmpMats[1];
  77263. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77264. rotMatInv.multiplyToRef(rotMat, rotMat);
  77265. this._rotateWithMatrix(rotMat, space, mesh);
  77266. };
  77267. /**
  77268. * Set the euler rotation of the bone in local of world space
  77269. * @param rotation The euler rotation that the bone should be set to
  77270. * @param space The space that the rotation is in
  77271. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77272. */
  77273. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77274. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77275. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77276. };
  77277. /**
  77278. * Set the quaternion rotation of the bone in local of world space
  77279. * @param quat The quaternion rotation that the bone should be set to
  77280. * @param space The space that the rotation is in
  77281. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77282. */
  77283. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77284. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77285. if (space === BABYLON.Space.LOCAL) {
  77286. this._decompose();
  77287. this._localRotation.copyFrom(quat);
  77288. this._markAsDirtyAndCompose();
  77289. return;
  77290. }
  77291. var rotMatInv = Bone._tmpMats[0];
  77292. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77293. return;
  77294. }
  77295. var rotMat = Bone._tmpMats[1];
  77296. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77297. rotMatInv.multiplyToRef(rotMat, rotMat);
  77298. this._rotateWithMatrix(rotMat, space, mesh);
  77299. };
  77300. /**
  77301. * Set the rotation matrix of the bone in local of world space
  77302. * @param rotMat The rotation matrix that the bone should be set to
  77303. * @param space The space that the rotation is in
  77304. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77305. */
  77306. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77307. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77308. if (space === BABYLON.Space.LOCAL) {
  77309. var quat = Bone._tmpQuat;
  77310. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77311. this.setRotationQuaternion(quat, space, mesh);
  77312. return;
  77313. }
  77314. var rotMatInv = Bone._tmpMats[0];
  77315. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77316. return;
  77317. }
  77318. var rotMat2 = Bone._tmpMats[1];
  77319. rotMat2.copyFrom(rotMat);
  77320. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77321. this._rotateWithMatrix(rotMat2, space, mesh);
  77322. };
  77323. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77324. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77325. var lmat = this.getLocalMatrix();
  77326. var lx = lmat.m[12];
  77327. var ly = lmat.m[13];
  77328. var lz = lmat.m[14];
  77329. var parent = this.getParent();
  77330. var parentScale = Bone._tmpMats[3];
  77331. var parentScaleInv = Bone._tmpMats[4];
  77332. if (parent && space == BABYLON.Space.WORLD) {
  77333. if (mesh) {
  77334. parentScale.copyFrom(mesh.getWorldMatrix());
  77335. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77336. }
  77337. else {
  77338. parentScale.copyFrom(parent.getAbsoluteTransform());
  77339. }
  77340. parentScaleInv.copyFrom(parentScale);
  77341. parentScaleInv.invert();
  77342. lmat.multiplyToRef(parentScale, lmat);
  77343. lmat.multiplyToRef(rmat, lmat);
  77344. lmat.multiplyToRef(parentScaleInv, lmat);
  77345. }
  77346. else {
  77347. if (space == BABYLON.Space.WORLD && mesh) {
  77348. parentScale.copyFrom(mesh.getWorldMatrix());
  77349. parentScaleInv.copyFrom(parentScale);
  77350. parentScaleInv.invert();
  77351. lmat.multiplyToRef(parentScale, lmat);
  77352. lmat.multiplyToRef(rmat, lmat);
  77353. lmat.multiplyToRef(parentScaleInv, lmat);
  77354. }
  77355. else {
  77356. lmat.multiplyToRef(rmat, lmat);
  77357. }
  77358. }
  77359. lmat.m[12] = lx;
  77360. lmat.m[13] = ly;
  77361. lmat.m[14] = lz;
  77362. this.computeAbsoluteTransforms();
  77363. this._markAsDirtyAndDecompose();
  77364. };
  77365. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77366. var scaleMatrix = Bone._tmpMats[2];
  77367. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77368. if (mesh) {
  77369. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77370. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77371. }
  77372. rotMatInv.invert();
  77373. if (isNaN(rotMatInv.m[0])) {
  77374. // Matrix failed to invert.
  77375. // This can happen if scale is zero for example.
  77376. return false;
  77377. }
  77378. scaleMatrix.m[0] *= this._scalingDeterminant;
  77379. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77380. return true;
  77381. };
  77382. /**
  77383. * Get the position of the bone in local or world space
  77384. * @param space The space that the returned position is in
  77385. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77386. * @returns The position of the bone
  77387. */
  77388. Bone.prototype.getPosition = function (space, mesh) {
  77389. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77390. if (mesh === void 0) { mesh = null; }
  77391. var pos = BABYLON.Vector3.Zero();
  77392. this.getPositionToRef(space, mesh, pos);
  77393. return pos;
  77394. };
  77395. /**
  77396. * Copy the position of the bone to a vector3 in local or world space
  77397. * @param space The space that the returned position is in
  77398. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77399. * @param result The vector3 to copy the position to
  77400. */
  77401. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77402. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77403. if (space == BABYLON.Space.LOCAL) {
  77404. var lm = this.getLocalMatrix();
  77405. result.x = lm.m[12];
  77406. result.y = lm.m[13];
  77407. result.z = lm.m[14];
  77408. }
  77409. else {
  77410. var wm = null;
  77411. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77412. if (mesh) {
  77413. wm = mesh.getWorldMatrix();
  77414. }
  77415. this._skeleton.computeAbsoluteTransforms();
  77416. var tmat = Bone._tmpMats[0];
  77417. if (mesh && wm) {
  77418. tmat.copyFrom(this.getAbsoluteTransform());
  77419. tmat.multiplyToRef(wm, tmat);
  77420. }
  77421. else {
  77422. tmat = this.getAbsoluteTransform();
  77423. }
  77424. result.x = tmat.m[12];
  77425. result.y = tmat.m[13];
  77426. result.z = tmat.m[14];
  77427. }
  77428. };
  77429. /**
  77430. * Get the absolute position of the bone (world space)
  77431. * @param mesh The mesh that this bone is attached to
  77432. * @returns The absolute position of the bone
  77433. */
  77434. Bone.prototype.getAbsolutePosition = function (mesh) {
  77435. if (mesh === void 0) { mesh = null; }
  77436. var pos = BABYLON.Vector3.Zero();
  77437. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77438. return pos;
  77439. };
  77440. /**
  77441. * Copy the absolute position of the bone (world space) to the result param
  77442. * @param mesh The mesh that this bone is attached to
  77443. * @param result The vector3 to copy the absolute position to
  77444. */
  77445. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77446. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77447. };
  77448. /**
  77449. * Compute the absolute transforms of this bone and its children
  77450. */
  77451. Bone.prototype.computeAbsoluteTransforms = function () {
  77452. this._compose();
  77453. if (this._parent) {
  77454. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77455. }
  77456. else {
  77457. this._absoluteTransform.copyFrom(this._localMatrix);
  77458. var poseMatrix = this._skeleton.getPoseMatrix();
  77459. if (poseMatrix) {
  77460. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77461. }
  77462. }
  77463. var children = this.children;
  77464. var len = children.length;
  77465. for (var i = 0; i < len; i++) {
  77466. children[i].computeAbsoluteTransforms();
  77467. }
  77468. };
  77469. /**
  77470. * Get the world direction from an axis that is in the local space of the bone
  77471. * @param localAxis The local direction that is used to compute the world direction
  77472. * @param mesh The mesh that this bone is attached to
  77473. * @returns The world direction
  77474. */
  77475. Bone.prototype.getDirection = function (localAxis, mesh) {
  77476. if (mesh === void 0) { mesh = null; }
  77477. var result = BABYLON.Vector3.Zero();
  77478. this.getDirectionToRef(localAxis, mesh, result);
  77479. return result;
  77480. };
  77481. /**
  77482. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  77483. * @param localAxis The local direction that is used to compute the world direction
  77484. * @param mesh The mesh that this bone is attached to
  77485. * @param result The vector3 that the world direction will be copied to
  77486. */
  77487. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  77488. if (mesh === void 0) { mesh = null; }
  77489. var wm = null;
  77490. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77491. if (mesh) {
  77492. wm = mesh.getWorldMatrix();
  77493. }
  77494. this._skeleton.computeAbsoluteTransforms();
  77495. var mat = Bone._tmpMats[0];
  77496. mat.copyFrom(this.getAbsoluteTransform());
  77497. if (mesh && wm) {
  77498. mat.multiplyToRef(wm, mat);
  77499. }
  77500. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  77501. result.normalize();
  77502. };
  77503. /**
  77504. * Get the euler rotation of the bone in local or world space
  77505. * @param space The space that the rotation should be in
  77506. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77507. * @returns The euler rotation
  77508. */
  77509. Bone.prototype.getRotation = function (space, mesh) {
  77510. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77511. if (mesh === void 0) { mesh = null; }
  77512. var result = BABYLON.Vector3.Zero();
  77513. this.getRotationToRef(space, mesh, result);
  77514. return result;
  77515. };
  77516. /**
  77517. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  77518. * @param space The space that the rotation should be in
  77519. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77520. * @param result The vector3 that the rotation should be copied to
  77521. */
  77522. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  77523. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77524. if (mesh === void 0) { mesh = null; }
  77525. var quat = Bone._tmpQuat;
  77526. this.getRotationQuaternionToRef(space, mesh, quat);
  77527. quat.toEulerAnglesToRef(result);
  77528. };
  77529. /**
  77530. * Get the quaternion rotation of the bone in either local or world space
  77531. * @param space The space that the rotation should be in
  77532. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77533. * @returns The quaternion rotation
  77534. */
  77535. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  77536. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77537. if (mesh === void 0) { mesh = null; }
  77538. var result = BABYLON.Quaternion.Identity();
  77539. this.getRotationQuaternionToRef(space, mesh, result);
  77540. return result;
  77541. };
  77542. /**
  77543. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  77544. * @param space The space that the rotation should be in
  77545. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77546. * @param result The quaternion that the rotation should be copied to
  77547. */
  77548. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  77549. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77550. if (mesh === void 0) { mesh = null; }
  77551. if (space == BABYLON.Space.LOCAL) {
  77552. this._decompose();
  77553. result.copyFrom(this._localRotation);
  77554. }
  77555. else {
  77556. var mat = Bone._tmpMats[0];
  77557. var amat = this.getAbsoluteTransform();
  77558. if (mesh) {
  77559. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77560. }
  77561. else {
  77562. mat.copyFrom(amat);
  77563. }
  77564. mat.m[0] *= this._scalingDeterminant;
  77565. mat.m[1] *= this._scalingDeterminant;
  77566. mat.m[2] *= this._scalingDeterminant;
  77567. mat.decompose(undefined, result, undefined);
  77568. }
  77569. };
  77570. /**
  77571. * Get the rotation matrix of the bone in local or world space
  77572. * @param space The space that the rotation should be in
  77573. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77574. * @returns The rotation matrix
  77575. */
  77576. Bone.prototype.getRotationMatrix = function (space, mesh) {
  77577. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77578. var result = BABYLON.Matrix.Identity();
  77579. this.getRotationMatrixToRef(space, mesh, result);
  77580. return result;
  77581. };
  77582. /**
  77583. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  77584. * @param space The space that the rotation should be in
  77585. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77586. * @param result The quaternion that the rotation should be copied to
  77587. */
  77588. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  77589. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77590. if (space == BABYLON.Space.LOCAL) {
  77591. this.getLocalMatrix().getRotationMatrixToRef(result);
  77592. }
  77593. else {
  77594. var mat = Bone._tmpMats[0];
  77595. var amat = this.getAbsoluteTransform();
  77596. if (mesh) {
  77597. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  77598. }
  77599. else {
  77600. mat.copyFrom(amat);
  77601. }
  77602. mat.m[0] *= this._scalingDeterminant;
  77603. mat.m[1] *= this._scalingDeterminant;
  77604. mat.m[2] *= this._scalingDeterminant;
  77605. mat.getRotationMatrixToRef(result);
  77606. }
  77607. };
  77608. /**
  77609. * Get the world position of a point that is in the local space of the bone
  77610. * @param position The local position
  77611. * @param mesh The mesh that this bone is attached to
  77612. * @returns The world position
  77613. */
  77614. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  77615. if (mesh === void 0) { mesh = null; }
  77616. var result = BABYLON.Vector3.Zero();
  77617. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  77618. return result;
  77619. };
  77620. /**
  77621. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  77622. * @param position The local position
  77623. * @param mesh The mesh that this bone is attached to
  77624. * @param result The vector3 that the world position should be copied to
  77625. */
  77626. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  77627. if (mesh === void 0) { mesh = null; }
  77628. var wm = null;
  77629. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77630. if (mesh) {
  77631. wm = mesh.getWorldMatrix();
  77632. }
  77633. this._skeleton.computeAbsoluteTransforms();
  77634. var tmat = Bone._tmpMats[0];
  77635. if (mesh && wm) {
  77636. tmat.copyFrom(this.getAbsoluteTransform());
  77637. tmat.multiplyToRef(wm, tmat);
  77638. }
  77639. else {
  77640. tmat = this.getAbsoluteTransform();
  77641. }
  77642. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77643. };
  77644. /**
  77645. * Get the local position of a point that is in world space
  77646. * @param position The world position
  77647. * @param mesh The mesh that this bone is attached to
  77648. * @returns The local position
  77649. */
  77650. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  77651. if (mesh === void 0) { mesh = null; }
  77652. var result = BABYLON.Vector3.Zero();
  77653. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  77654. return result;
  77655. };
  77656. /**
  77657. * Get the local position of a point that is in world space and copy it to the result param
  77658. * @param position The world position
  77659. * @param mesh The mesh that this bone is attached to
  77660. * @param result The vector3 that the local position should be copied to
  77661. */
  77662. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  77663. if (mesh === void 0) { mesh = null; }
  77664. var wm = null;
  77665. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77666. if (mesh) {
  77667. wm = mesh.getWorldMatrix();
  77668. }
  77669. this._skeleton.computeAbsoluteTransforms();
  77670. var tmat = Bone._tmpMats[0];
  77671. tmat.copyFrom(this.getAbsoluteTransform());
  77672. if (mesh && wm) {
  77673. tmat.multiplyToRef(wm, tmat);
  77674. }
  77675. tmat.invert();
  77676. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  77677. };
  77678. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77679. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  77680. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77681. return Bone;
  77682. }(BABYLON.Node));
  77683. BABYLON.Bone = Bone;
  77684. })(BABYLON || (BABYLON = {}));
  77685. //# sourceMappingURL=babylon.bone.js.map
  77686. var BABYLON;
  77687. (function (BABYLON) {
  77688. /**
  77689. * Class used to apply inverse kinematics to bones
  77690. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  77691. */
  77692. var BoneIKController = /** @class */ (function () {
  77693. /**
  77694. * Creates a new BoneIKController
  77695. * @param mesh defines the mesh to control
  77696. * @param bone defines the bone to control
  77697. * @param options defines options to set up the controller
  77698. */
  77699. function BoneIKController(mesh, bone, options) {
  77700. /**
  77701. * Gets or sets the target position
  77702. */
  77703. this.targetPosition = BABYLON.Vector3.Zero();
  77704. /**
  77705. * Gets or sets the pole target position
  77706. */
  77707. this.poleTargetPosition = BABYLON.Vector3.Zero();
  77708. /**
  77709. * Gets or sets the pole target local offset
  77710. */
  77711. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  77712. /**
  77713. * Gets or sets the pole angle
  77714. */
  77715. this.poleAngle = 0;
  77716. /**
  77717. * 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)
  77718. */
  77719. this.slerpAmount = 1;
  77720. this._bone1Quat = BABYLON.Quaternion.Identity();
  77721. this._bone1Mat = BABYLON.Matrix.Identity();
  77722. this._bone2Ang = Math.PI;
  77723. this._maxAngle = Math.PI;
  77724. this._rightHandedSystem = false;
  77725. this._bendAxis = BABYLON.Vector3.Right();
  77726. this._slerping = false;
  77727. this._adjustRoll = 0;
  77728. this._bone2 = bone;
  77729. this._bone1 = bone.getParent();
  77730. if (!this._bone1) {
  77731. return;
  77732. }
  77733. this.mesh = mesh;
  77734. var bonePos = bone.getPosition();
  77735. if (bone.getAbsoluteTransform().determinant() > 0) {
  77736. this._rightHandedSystem = true;
  77737. this._bendAxis.x = 0;
  77738. this._bendAxis.y = 0;
  77739. this._bendAxis.z = -1;
  77740. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  77741. this._adjustRoll = Math.PI * .5;
  77742. this._bendAxis.z = 1;
  77743. }
  77744. }
  77745. if (this._bone1.length) {
  77746. var boneScale1 = this._bone1.getScale();
  77747. var boneScale2 = this._bone2.getScale();
  77748. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  77749. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  77750. }
  77751. else if (this._bone1.children[0]) {
  77752. mesh.computeWorldMatrix(true);
  77753. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  77754. var pos2 = this._bone2.getAbsolutePosition(mesh);
  77755. var pos3 = this._bone1.getAbsolutePosition(mesh);
  77756. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  77757. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  77758. }
  77759. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  77760. this.maxAngle = Math.PI;
  77761. if (options) {
  77762. if (options.targetMesh) {
  77763. this.targetMesh = options.targetMesh;
  77764. this.targetMesh.computeWorldMatrix(true);
  77765. }
  77766. if (options.poleTargetMesh) {
  77767. this.poleTargetMesh = options.poleTargetMesh;
  77768. this.poleTargetMesh.computeWorldMatrix(true);
  77769. }
  77770. else if (options.poleTargetBone) {
  77771. this.poleTargetBone = options.poleTargetBone;
  77772. }
  77773. else if (this._bone1.getParent()) {
  77774. this.poleTargetBone = this._bone1.getParent();
  77775. }
  77776. if (options.poleTargetLocalOffset) {
  77777. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  77778. }
  77779. if (options.poleAngle) {
  77780. this.poleAngle = options.poleAngle;
  77781. }
  77782. if (options.bendAxis) {
  77783. this._bendAxis.copyFrom(options.bendAxis);
  77784. }
  77785. if (options.maxAngle) {
  77786. this.maxAngle = options.maxAngle;
  77787. }
  77788. if (options.slerpAmount) {
  77789. this.slerpAmount = options.slerpAmount;
  77790. }
  77791. }
  77792. }
  77793. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  77794. /**
  77795. * Gets or sets maximum allowed angle
  77796. */
  77797. get: function () {
  77798. return this._maxAngle;
  77799. },
  77800. set: function (value) {
  77801. this._setMaxAngle(value);
  77802. },
  77803. enumerable: true,
  77804. configurable: true
  77805. });
  77806. BoneIKController.prototype._setMaxAngle = function (ang) {
  77807. if (ang < 0) {
  77808. ang = 0;
  77809. }
  77810. if (ang > Math.PI || ang == undefined) {
  77811. ang = Math.PI;
  77812. }
  77813. this._maxAngle = ang;
  77814. var a = this._bone1Length;
  77815. var b = this._bone2Length;
  77816. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  77817. };
  77818. /**
  77819. * Force the controller to update the bones
  77820. */
  77821. BoneIKController.prototype.update = function () {
  77822. var bone1 = this._bone1;
  77823. if (!bone1) {
  77824. return;
  77825. }
  77826. var target = this.targetPosition;
  77827. var poleTarget = this.poleTargetPosition;
  77828. var mat1 = BoneIKController._tmpMats[0];
  77829. var mat2 = BoneIKController._tmpMats[1];
  77830. if (this.targetMesh) {
  77831. target.copyFrom(this.targetMesh.getAbsolutePosition());
  77832. }
  77833. if (this.poleTargetBone) {
  77834. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  77835. }
  77836. else if (this.poleTargetMesh) {
  77837. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  77838. }
  77839. var bonePos = BoneIKController._tmpVecs[0];
  77840. var zaxis = BoneIKController._tmpVecs[1];
  77841. var xaxis = BoneIKController._tmpVecs[2];
  77842. var yaxis = BoneIKController._tmpVecs[3];
  77843. var upAxis = BoneIKController._tmpVecs[4];
  77844. var _tmpQuat = BoneIKController._tmpQuat;
  77845. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  77846. poleTarget.subtractToRef(bonePos, upAxis);
  77847. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  77848. upAxis.y = 1;
  77849. }
  77850. else {
  77851. upAxis.normalize();
  77852. }
  77853. target.subtractToRef(bonePos, yaxis);
  77854. yaxis.normalize();
  77855. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  77856. zaxis.normalize();
  77857. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  77858. xaxis.normalize();
  77859. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  77860. var a = this._bone1Length;
  77861. var b = this._bone2Length;
  77862. var c = BABYLON.Vector3.Distance(bonePos, target);
  77863. if (this._maxReach > 0) {
  77864. c = Math.min(this._maxReach, c);
  77865. }
  77866. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  77867. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  77868. if (acosa > 1) {
  77869. acosa = 1;
  77870. }
  77871. if (acosb > 1) {
  77872. acosb = 1;
  77873. }
  77874. if (acosa < -1) {
  77875. acosa = -1;
  77876. }
  77877. if (acosb < -1) {
  77878. acosb = -1;
  77879. }
  77880. var angA = Math.acos(acosa);
  77881. var angB = Math.acos(acosb);
  77882. var angC = -angA - angB;
  77883. if (this._rightHandedSystem) {
  77884. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  77885. mat2.multiplyToRef(mat1, mat1);
  77886. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  77887. mat2.multiplyToRef(mat1, mat1);
  77888. }
  77889. else {
  77890. var _tmpVec = BoneIKController._tmpVecs[5];
  77891. _tmpVec.copyFrom(this._bendAxis);
  77892. _tmpVec.x *= -1;
  77893. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  77894. mat2.multiplyToRef(mat1, mat1);
  77895. }
  77896. if (this.poleAngle) {
  77897. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  77898. mat1.multiplyToRef(mat2, mat1);
  77899. }
  77900. if (this._bone1) {
  77901. if (this.slerpAmount < 1) {
  77902. if (!this._slerping) {
  77903. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  77904. }
  77905. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  77906. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  77907. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  77908. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  77909. this._slerping = true;
  77910. }
  77911. else {
  77912. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  77913. this._bone1Mat.copyFrom(mat1);
  77914. this._slerping = false;
  77915. }
  77916. }
  77917. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  77918. this._bone2Ang = angC;
  77919. };
  77920. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77921. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  77922. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  77923. return BoneIKController;
  77924. }());
  77925. BABYLON.BoneIKController = BoneIKController;
  77926. })(BABYLON || (BABYLON = {}));
  77927. //# sourceMappingURL=babylon.boneIKController.js.map
  77928. var BABYLON;
  77929. (function (BABYLON) {
  77930. /**
  77931. * Class used to make a bone look toward a point in space
  77932. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  77933. */
  77934. var BoneLookController = /** @class */ (function () {
  77935. /**
  77936. * Create a BoneLookController
  77937. * @param mesh the mesh that the bone belongs to
  77938. * @param bone the bone that will be looking to the target
  77939. * @param target the target Vector3 to look at
  77940. * @param settings optional settings:
  77941. * * maxYaw: the maximum angle the bone will yaw to
  77942. * * minYaw: the minimum angle the bone will yaw to
  77943. * * maxPitch: the maximum angle the bone will pitch to
  77944. * * minPitch: the minimum angle the bone will yaw to
  77945. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  77946. * * upAxis: the up axis of the coordinate system
  77947. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  77948. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  77949. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  77950. * * adjustYaw: used to make an adjustment to the yaw of the bone
  77951. * * adjustPitch: used to make an adjustment to the pitch of the bone
  77952. * * adjustRoll: used to make an adjustment to the roll of the bone
  77953. **/
  77954. function BoneLookController(mesh, bone, target, options) {
  77955. /**
  77956. * The up axis of the coordinate system that is used when the bone is rotated
  77957. */
  77958. this.upAxis = BABYLON.Vector3.Up();
  77959. /**
  77960. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  77961. */
  77962. this.upAxisSpace = BABYLON.Space.LOCAL;
  77963. /**
  77964. * Used to make an adjustment to the yaw of the bone
  77965. */
  77966. this.adjustYaw = 0;
  77967. /**
  77968. * Used to make an adjustment to the pitch of the bone
  77969. */
  77970. this.adjustPitch = 0;
  77971. /**
  77972. * Used to make an adjustment to the roll of the bone
  77973. */
  77974. this.adjustRoll = 0;
  77975. /**
  77976. * 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)
  77977. */
  77978. this.slerpAmount = 1;
  77979. this._boneQuat = BABYLON.Quaternion.Identity();
  77980. this._slerping = false;
  77981. this._firstFrameSkipped = false;
  77982. this._fowardAxis = BABYLON.Vector3.Forward();
  77983. this.mesh = mesh;
  77984. this.bone = bone;
  77985. this.target = target;
  77986. if (options) {
  77987. if (options.adjustYaw) {
  77988. this.adjustYaw = options.adjustYaw;
  77989. }
  77990. if (options.adjustPitch) {
  77991. this.adjustPitch = options.adjustPitch;
  77992. }
  77993. if (options.adjustRoll) {
  77994. this.adjustRoll = options.adjustRoll;
  77995. }
  77996. if (options.maxYaw != null) {
  77997. this.maxYaw = options.maxYaw;
  77998. }
  77999. else {
  78000. this.maxYaw = Math.PI;
  78001. }
  78002. if (options.minYaw != null) {
  78003. this.minYaw = options.minYaw;
  78004. }
  78005. else {
  78006. this.minYaw = -Math.PI;
  78007. }
  78008. if (options.maxPitch != null) {
  78009. this.maxPitch = options.maxPitch;
  78010. }
  78011. else {
  78012. this.maxPitch = Math.PI;
  78013. }
  78014. if (options.minPitch != null) {
  78015. this.minPitch = options.minPitch;
  78016. }
  78017. else {
  78018. this.minPitch = -Math.PI;
  78019. }
  78020. if (options.slerpAmount != null) {
  78021. this.slerpAmount = options.slerpAmount;
  78022. }
  78023. if (options.upAxis != null) {
  78024. this.upAxis = options.upAxis;
  78025. }
  78026. if (options.upAxisSpace != null) {
  78027. this.upAxisSpace = options.upAxisSpace;
  78028. }
  78029. if (options.yawAxis != null || options.pitchAxis != null) {
  78030. var newYawAxis = BABYLON.Axis.Y;
  78031. var newPitchAxis = BABYLON.Axis.X;
  78032. if (options.yawAxis != null) {
  78033. newYawAxis = options.yawAxis.clone();
  78034. newYawAxis.normalize();
  78035. }
  78036. if (options.pitchAxis != null) {
  78037. newPitchAxis = options.pitchAxis.clone();
  78038. newPitchAxis.normalize();
  78039. }
  78040. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78041. this._transformYawPitch = BABYLON.Matrix.Identity();
  78042. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78043. this._transformYawPitchInv = this._transformYawPitch.clone();
  78044. this._transformYawPitch.invert();
  78045. }
  78046. }
  78047. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78048. this.upAxisSpace = BABYLON.Space.LOCAL;
  78049. }
  78050. }
  78051. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78052. /**
  78053. * Gets or sets the minimum yaw angle that the bone can look to
  78054. */
  78055. get: function () {
  78056. return this._minYaw;
  78057. },
  78058. set: function (value) {
  78059. this._minYaw = value;
  78060. this._minYawSin = Math.sin(value);
  78061. this._minYawCos = Math.cos(value);
  78062. if (this._maxYaw != null) {
  78063. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78064. this._yawRange = this._maxYaw - this._minYaw;
  78065. }
  78066. },
  78067. enumerable: true,
  78068. configurable: true
  78069. });
  78070. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78071. /**
  78072. * Gets or sets the maximum yaw angle that the bone can look to
  78073. */
  78074. get: function () {
  78075. return this._maxYaw;
  78076. },
  78077. set: function (value) {
  78078. this._maxYaw = value;
  78079. this._maxYawSin = Math.sin(value);
  78080. this._maxYawCos = Math.cos(value);
  78081. if (this._minYaw != null) {
  78082. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78083. this._yawRange = this._maxYaw - this._minYaw;
  78084. }
  78085. },
  78086. enumerable: true,
  78087. configurable: true
  78088. });
  78089. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78090. /**
  78091. * Gets or sets the minimum pitch angle that the bone can look to
  78092. */
  78093. get: function () {
  78094. return this._minPitch;
  78095. },
  78096. set: function (value) {
  78097. this._minPitch = value;
  78098. this._minPitchTan = Math.tan(value);
  78099. },
  78100. enumerable: true,
  78101. configurable: true
  78102. });
  78103. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78104. /**
  78105. * Gets or sets the maximum pitch angle that the bone can look to
  78106. */
  78107. get: function () {
  78108. return this._maxPitch;
  78109. },
  78110. set: function (value) {
  78111. this._maxPitch = value;
  78112. this._maxPitchTan = Math.tan(value);
  78113. },
  78114. enumerable: true,
  78115. configurable: true
  78116. });
  78117. /**
  78118. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78119. */
  78120. BoneLookController.prototype.update = function () {
  78121. //skip the first frame when slerping so that the mesh rotation is correct
  78122. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78123. this._firstFrameSkipped = true;
  78124. return;
  78125. }
  78126. var bone = this.bone;
  78127. var bonePos = BoneLookController._tmpVecs[0];
  78128. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78129. var target = this.target;
  78130. var _tmpMat1 = BoneLookController._tmpMats[0];
  78131. var _tmpMat2 = BoneLookController._tmpMats[1];
  78132. var mesh = this.mesh;
  78133. var parentBone = bone.getParent();
  78134. var upAxis = BoneLookController._tmpVecs[1];
  78135. upAxis.copyFrom(this.upAxis);
  78136. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78137. if (this._transformYawPitch) {
  78138. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78139. }
  78140. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78141. }
  78142. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78143. mesh.getDirectionToRef(upAxis, upAxis);
  78144. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78145. upAxis.normalize();
  78146. }
  78147. }
  78148. var checkYaw = false;
  78149. var checkPitch = false;
  78150. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78151. checkYaw = true;
  78152. }
  78153. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78154. checkPitch = true;
  78155. }
  78156. if (checkYaw || checkPitch) {
  78157. var spaceMat = BoneLookController._tmpMats[2];
  78158. var spaceMatInv = BoneLookController._tmpMats[3];
  78159. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78160. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78161. }
  78162. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78163. spaceMat.copyFrom(mesh.getWorldMatrix());
  78164. }
  78165. else {
  78166. var forwardAxis = BoneLookController._tmpVecs[2];
  78167. forwardAxis.copyFrom(this._fowardAxis);
  78168. if (this._transformYawPitch) {
  78169. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78170. }
  78171. if (parentBone) {
  78172. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78173. }
  78174. else {
  78175. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78176. }
  78177. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78178. rightAxis.normalize();
  78179. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78180. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78181. }
  78182. spaceMat.invertToRef(spaceMatInv);
  78183. var xzlen = null;
  78184. if (checkPitch) {
  78185. var localTarget = BoneLookController._tmpVecs[3];
  78186. target.subtractToRef(bonePos, localTarget);
  78187. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78188. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78189. var pitch = Math.atan2(localTarget.y, xzlen);
  78190. var newPitch = pitch;
  78191. if (pitch > this._maxPitch) {
  78192. localTarget.y = this._maxPitchTan * xzlen;
  78193. newPitch = this._maxPitch;
  78194. }
  78195. else if (pitch < this._minPitch) {
  78196. localTarget.y = this._minPitchTan * xzlen;
  78197. newPitch = this._minPitch;
  78198. }
  78199. if (pitch != newPitch) {
  78200. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78201. localTarget.addInPlace(bonePos);
  78202. target = localTarget;
  78203. }
  78204. }
  78205. if (checkYaw) {
  78206. var localTarget = BoneLookController._tmpVecs[4];
  78207. target.subtractToRef(bonePos, localTarget);
  78208. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78209. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78210. var newYaw = yaw;
  78211. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78212. if (xzlen == null) {
  78213. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78214. }
  78215. if (this._yawRange > Math.PI) {
  78216. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78217. localTarget.z = this._maxYawCos * xzlen;
  78218. localTarget.x = this._maxYawSin * xzlen;
  78219. newYaw = this._maxYaw;
  78220. }
  78221. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78222. localTarget.z = this._minYawCos * xzlen;
  78223. localTarget.x = this._minYawSin * xzlen;
  78224. newYaw = this._minYaw;
  78225. }
  78226. }
  78227. else {
  78228. if (yaw > this._maxYaw) {
  78229. localTarget.z = this._maxYawCos * xzlen;
  78230. localTarget.x = this._maxYawSin * xzlen;
  78231. newYaw = this._maxYaw;
  78232. }
  78233. else if (yaw < this._minYaw) {
  78234. localTarget.z = this._minYawCos * xzlen;
  78235. localTarget.x = this._minYawSin * xzlen;
  78236. newYaw = this._minYaw;
  78237. }
  78238. }
  78239. }
  78240. if (this._slerping && this._yawRange > Math.PI) {
  78241. //are we going to be crossing into the min/max region?
  78242. var boneFwd = BoneLookController._tmpVecs[8];
  78243. boneFwd.copyFrom(BABYLON.Axis.Z);
  78244. if (this._transformYawPitch) {
  78245. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78246. }
  78247. var boneRotMat = BoneLookController._tmpMats[4];
  78248. this._boneQuat.toRotationMatrix(boneRotMat);
  78249. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78250. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78251. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78252. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78253. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78254. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78255. if (angBtwTar > angBtwMidYaw) {
  78256. if (xzlen == null) {
  78257. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78258. }
  78259. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78260. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78261. if (angBtwMin < angBtwMax) {
  78262. newYaw = boneYaw + Math.PI * .75;
  78263. localTarget.z = Math.cos(newYaw) * xzlen;
  78264. localTarget.x = Math.sin(newYaw) * xzlen;
  78265. }
  78266. else {
  78267. newYaw = boneYaw - Math.PI * .75;
  78268. localTarget.z = Math.cos(newYaw) * xzlen;
  78269. localTarget.x = Math.sin(newYaw) * xzlen;
  78270. }
  78271. }
  78272. }
  78273. if (yaw != newYaw) {
  78274. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78275. localTarget.addInPlace(bonePos);
  78276. target = localTarget;
  78277. }
  78278. }
  78279. }
  78280. var zaxis = BoneLookController._tmpVecs[5];
  78281. var xaxis = BoneLookController._tmpVecs[6];
  78282. var yaxis = BoneLookController._tmpVecs[7];
  78283. var _tmpQuat = BoneLookController._tmpQuat;
  78284. target.subtractToRef(bonePos, zaxis);
  78285. zaxis.normalize();
  78286. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78287. xaxis.normalize();
  78288. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78289. yaxis.normalize();
  78290. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78291. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78292. return;
  78293. }
  78294. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78295. return;
  78296. }
  78297. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78298. return;
  78299. }
  78300. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78301. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78302. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78303. }
  78304. if (this.slerpAmount < 1) {
  78305. if (!this._slerping) {
  78306. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78307. }
  78308. if (this._transformYawPitch) {
  78309. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78310. }
  78311. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78312. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78313. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78314. this._slerping = true;
  78315. }
  78316. else {
  78317. if (this._transformYawPitch) {
  78318. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78319. }
  78320. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78321. this._slerping = false;
  78322. }
  78323. };
  78324. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78325. var angDiff = ang2 - ang1;
  78326. angDiff %= Math.PI * 2;
  78327. if (angDiff > Math.PI) {
  78328. angDiff -= Math.PI * 2;
  78329. }
  78330. else if (angDiff < -Math.PI) {
  78331. angDiff += Math.PI * 2;
  78332. }
  78333. return angDiff;
  78334. };
  78335. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78336. ang1 %= (2 * Math.PI);
  78337. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78338. ang2 %= (2 * Math.PI);
  78339. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78340. var ab = 0;
  78341. if (ang1 < ang2) {
  78342. ab = ang2 - ang1;
  78343. }
  78344. else {
  78345. ab = ang1 - ang2;
  78346. }
  78347. if (ab > Math.PI) {
  78348. ab = Math.PI * 2 - ab;
  78349. }
  78350. return ab;
  78351. };
  78352. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78353. ang %= (2 * Math.PI);
  78354. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78355. ang1 %= (2 * Math.PI);
  78356. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78357. ang2 %= (2 * Math.PI);
  78358. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78359. if (ang1 < ang2) {
  78360. if (ang > ang1 && ang < ang2) {
  78361. return true;
  78362. }
  78363. }
  78364. else {
  78365. if (ang > ang2 && ang < ang1) {
  78366. return true;
  78367. }
  78368. }
  78369. return false;
  78370. };
  78371. 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()];
  78372. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78373. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78374. return BoneLookController;
  78375. }());
  78376. BABYLON.BoneLookController = BoneLookController;
  78377. })(BABYLON || (BABYLON = {}));
  78378. //# sourceMappingURL=babylon.boneLookController.js.map
  78379. var BABYLON;
  78380. (function (BABYLON) {
  78381. /**
  78382. * Class used to handle skinning animations
  78383. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78384. */
  78385. var Skeleton = /** @class */ (function () {
  78386. /**
  78387. * Creates a new skeleton
  78388. * @param name defines the skeleton name
  78389. * @param id defines the skeleton Id
  78390. * @param scene defines the hosting scene
  78391. */
  78392. function Skeleton(
  78393. /** defines the skeleton name */
  78394. name,
  78395. /** defines the skeleton Id */
  78396. id, scene) {
  78397. this.name = name;
  78398. this.id = id;
  78399. /**
  78400. * Gets the list of child bones
  78401. */
  78402. this.bones = new Array();
  78403. /**
  78404. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78405. */
  78406. this.needInitialSkinMatrix = false;
  78407. this._isDirty = true;
  78408. this._meshesWithPoseMatrix = new Array();
  78409. this._identity = BABYLON.Matrix.Identity();
  78410. this._ranges = {};
  78411. this._lastAbsoluteTransformsUpdateId = -1;
  78412. /**
  78413. * Specifies if the skeleton should be serialized
  78414. */
  78415. this.doNotSerialize = false;
  78416. this._animationPropertiesOverride = null;
  78417. // Events
  78418. /**
  78419. * An observable triggered before computing the skeleton's matrices
  78420. */
  78421. this.onBeforeComputeObservable = new BABYLON.Observable();
  78422. this.bones = [];
  78423. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78424. scene.skeletons.push(this);
  78425. //make sure it will recalculate the matrix next time prepare is called.
  78426. this._isDirty = true;
  78427. }
  78428. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78429. /**
  78430. * Gets or sets the animation properties override
  78431. */
  78432. get: function () {
  78433. if (!this._animationPropertiesOverride) {
  78434. return this._scene.animationPropertiesOverride;
  78435. }
  78436. return this._animationPropertiesOverride;
  78437. },
  78438. set: function (value) {
  78439. this._animationPropertiesOverride = value;
  78440. },
  78441. enumerable: true,
  78442. configurable: true
  78443. });
  78444. // Members
  78445. /**
  78446. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78447. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78448. * @returns a Float32Array containing matrices data
  78449. */
  78450. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78451. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78452. return mesh._bonesTransformMatrices;
  78453. }
  78454. if (!this._transformMatrices) {
  78455. this.prepare();
  78456. }
  78457. return this._transformMatrices;
  78458. };
  78459. /**
  78460. * Gets the current hosting scene
  78461. * @returns a scene object
  78462. */
  78463. Skeleton.prototype.getScene = function () {
  78464. return this._scene;
  78465. };
  78466. // Methods
  78467. /**
  78468. * Gets a string representing the current skeleton data
  78469. * @param fullDetails defines a boolean indicating if we want a verbose version
  78470. * @returns a string representing the current skeleton data
  78471. */
  78472. Skeleton.prototype.toString = function (fullDetails) {
  78473. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  78474. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  78475. if (fullDetails) {
  78476. ret += ", Ranges: {";
  78477. var first = true;
  78478. for (var name_1 in this._ranges) {
  78479. if (first) {
  78480. ret += ", ";
  78481. first = false;
  78482. }
  78483. ret += name_1;
  78484. }
  78485. ret += "}";
  78486. }
  78487. return ret;
  78488. };
  78489. /**
  78490. * Get bone's index searching by name
  78491. * @param name defines bone's name to search for
  78492. * @return the indice of the bone. Returns -1 if not found
  78493. */
  78494. Skeleton.prototype.getBoneIndexByName = function (name) {
  78495. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  78496. if (this.bones[boneIndex].name === name) {
  78497. return boneIndex;
  78498. }
  78499. }
  78500. return -1;
  78501. };
  78502. /**
  78503. * Creater a new animation range
  78504. * @param name defines the name of the range
  78505. * @param from defines the start key
  78506. * @param to defines the end key
  78507. */
  78508. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  78509. // check name not already in use
  78510. if (!this._ranges[name]) {
  78511. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  78512. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78513. if (this.bones[i].animations[0]) {
  78514. this.bones[i].animations[0].createRange(name, from, to);
  78515. }
  78516. }
  78517. }
  78518. };
  78519. /**
  78520. * Delete a specific animation range
  78521. * @param name defines the name of the range
  78522. * @param deleteFrames defines if frames must be removed as well
  78523. */
  78524. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  78525. if (deleteFrames === void 0) { deleteFrames = true; }
  78526. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78527. if (this.bones[i].animations[0]) {
  78528. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  78529. }
  78530. }
  78531. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  78532. };
  78533. /**
  78534. * Gets a specific animation range
  78535. * @param name defines the name of the range to look for
  78536. * @returns the requested animation range or null if not found
  78537. */
  78538. Skeleton.prototype.getAnimationRange = function (name) {
  78539. return this._ranges[name];
  78540. };
  78541. /**
  78542. * Gets the list of all animation ranges defined on this skeleton
  78543. * @returns an array
  78544. */
  78545. Skeleton.prototype.getAnimationRanges = function () {
  78546. var animationRanges = [];
  78547. var name;
  78548. var i = 0;
  78549. for (name in this._ranges) {
  78550. animationRanges[i] = this._ranges[name];
  78551. i++;
  78552. }
  78553. return animationRanges;
  78554. };
  78555. /**
  78556. * Copy animation range from a source skeleton.
  78557. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  78558. * @param source defines the source skeleton
  78559. * @param name defines the name of the range to copy
  78560. * @param rescaleAsRequired defines if rescaling must be applied if required
  78561. * @returns true if operation was successful
  78562. */
  78563. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  78564. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  78565. if (this._ranges[name] || !source.getAnimationRange(name)) {
  78566. return false;
  78567. }
  78568. var ret = true;
  78569. var frameOffset = this._getHighestAnimationFrame() + 1;
  78570. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  78571. var boneDict = {};
  78572. var sourceBones = source.bones;
  78573. var nBones;
  78574. var i;
  78575. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  78576. boneDict[sourceBones[i].name] = sourceBones[i];
  78577. }
  78578. if (this.bones.length !== sourceBones.length) {
  78579. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  78580. ret = false;
  78581. }
  78582. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  78583. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  78584. var boneName = this.bones[i].name;
  78585. var sourceBone = boneDict[boneName];
  78586. if (sourceBone) {
  78587. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  78588. }
  78589. else {
  78590. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  78591. ret = false;
  78592. }
  78593. }
  78594. // do not call createAnimationRange(), since it also is done to bones, which was already done
  78595. var range = source.getAnimationRange(name);
  78596. if (range) {
  78597. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  78598. }
  78599. return ret;
  78600. };
  78601. /**
  78602. * Forces the skeleton to go to rest pose
  78603. */
  78604. Skeleton.prototype.returnToRest = function () {
  78605. for (var index = 0; index < this.bones.length; index++) {
  78606. this.bones[index].returnToRest();
  78607. }
  78608. };
  78609. Skeleton.prototype._getHighestAnimationFrame = function () {
  78610. var ret = 0;
  78611. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  78612. if (this.bones[i].animations[0]) {
  78613. var highest = this.bones[i].animations[0].getHighestFrame();
  78614. if (ret < highest) {
  78615. ret = highest;
  78616. }
  78617. }
  78618. }
  78619. return ret;
  78620. };
  78621. /**
  78622. * Begin a specific animation range
  78623. * @param name defines the name of the range to start
  78624. * @param loop defines if looping must be turned on (false by default)
  78625. * @param speedRatio defines the speed ratio to apply (1 by default)
  78626. * @param onAnimationEnd defines a callback which will be called when animation will end
  78627. * @returns a new animatable
  78628. */
  78629. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  78630. var range = this.getAnimationRange(name);
  78631. if (!range) {
  78632. return null;
  78633. }
  78634. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  78635. };
  78636. /** @ignore */
  78637. Skeleton.prototype._markAsDirty = function () {
  78638. this._isDirty = true;
  78639. };
  78640. /** @ignore */
  78641. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  78642. this._meshesWithPoseMatrix.push(mesh);
  78643. };
  78644. /** @ignore */
  78645. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  78646. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  78647. if (index > -1) {
  78648. this._meshesWithPoseMatrix.splice(index, 1);
  78649. }
  78650. };
  78651. /** @ignore */
  78652. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  78653. this.onBeforeComputeObservable.notifyObservers(this);
  78654. for (var index = 0; index < this.bones.length; index++) {
  78655. var bone = this.bones[index];
  78656. var parentBone = bone.getParent();
  78657. if (parentBone) {
  78658. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  78659. }
  78660. else {
  78661. if (initialSkinMatrix) {
  78662. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  78663. }
  78664. else {
  78665. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  78666. }
  78667. }
  78668. if (bone._index !== -1) {
  78669. var mappedIndex = bone._index === null ? index : bone._index;
  78670. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  78671. }
  78672. }
  78673. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  78674. };
  78675. /**
  78676. * Build all resources required to render a skeleton
  78677. */
  78678. Skeleton.prototype.prepare = function () {
  78679. if (!this._isDirty) {
  78680. return;
  78681. }
  78682. if (this.needInitialSkinMatrix) {
  78683. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  78684. var mesh = this._meshesWithPoseMatrix[index];
  78685. var poseMatrix = mesh.getPoseMatrix();
  78686. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  78687. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78688. }
  78689. if (this._synchronizedWithMesh !== mesh) {
  78690. this._synchronizedWithMesh = mesh;
  78691. // Prepare bones
  78692. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  78693. var bone = this.bones[boneIndex];
  78694. if (!bone.getParent()) {
  78695. var matrix = bone.getBaseMatrix();
  78696. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  78697. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  78698. }
  78699. }
  78700. }
  78701. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  78702. }
  78703. }
  78704. else {
  78705. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  78706. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  78707. }
  78708. this._computeTransformMatrices(this._transformMatrices, null);
  78709. }
  78710. this._isDirty = false;
  78711. this._scene._activeBones.addCount(this.bones.length, false);
  78712. };
  78713. /**
  78714. * Gets the list of animatables currently running for this skeleton
  78715. * @returns an array of animatables
  78716. */
  78717. Skeleton.prototype.getAnimatables = function () {
  78718. if (!this._animatables || this._animatables.length !== this.bones.length) {
  78719. this._animatables = [];
  78720. for (var index = 0; index < this.bones.length; index++) {
  78721. this._animatables.push(this.bones[index]);
  78722. }
  78723. }
  78724. return this._animatables;
  78725. };
  78726. /**
  78727. * Clone the current skeleton
  78728. * @param name defines the name of the new skeleton
  78729. * @param id defines the id of the enw skeleton
  78730. * @returns the new skeleton
  78731. */
  78732. Skeleton.prototype.clone = function (name, id) {
  78733. var result = new Skeleton(name, id || name, this._scene);
  78734. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78735. for (var index = 0; index < this.bones.length; index++) {
  78736. var source = this.bones[index];
  78737. var parentBone = null;
  78738. var parent_1 = source.getParent();
  78739. if (parent_1) {
  78740. var parentIndex = this.bones.indexOf(parent_1);
  78741. parentBone = result.bones[parentIndex];
  78742. }
  78743. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  78744. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  78745. }
  78746. if (this._ranges) {
  78747. result._ranges = {};
  78748. for (var rangeName in this._ranges) {
  78749. var range = this._ranges[rangeName];
  78750. if (range) {
  78751. result._ranges[rangeName] = range.clone();
  78752. }
  78753. }
  78754. }
  78755. this._isDirty = true;
  78756. return result;
  78757. };
  78758. /**
  78759. * Enable animation blending for this skeleton
  78760. * @param blendingSpeed defines the blending speed to apply
  78761. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  78762. */
  78763. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  78764. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  78765. this.bones.forEach(function (bone) {
  78766. bone.animations.forEach(function (animation) {
  78767. animation.enableBlending = true;
  78768. animation.blendingSpeed = blendingSpeed;
  78769. });
  78770. });
  78771. };
  78772. /**
  78773. * Releases all resources associated with the current skeleton
  78774. */
  78775. Skeleton.prototype.dispose = function () {
  78776. this._meshesWithPoseMatrix = [];
  78777. // Animations
  78778. this.getScene().stopAnimation(this);
  78779. // Remove from scene
  78780. this.getScene().removeSkeleton(this);
  78781. };
  78782. /**
  78783. * Serialize the skeleton in a JSON object
  78784. * @returns a JSON object
  78785. */
  78786. Skeleton.prototype.serialize = function () {
  78787. var serializationObject = {};
  78788. serializationObject.name = this.name;
  78789. serializationObject.id = this.id;
  78790. if (this.dimensionsAtRest) {
  78791. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  78792. }
  78793. serializationObject.bones = [];
  78794. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  78795. for (var index = 0; index < this.bones.length; index++) {
  78796. var bone = this.bones[index];
  78797. var parent_2 = bone.getParent();
  78798. var serializedBone = {
  78799. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  78800. name: bone.name,
  78801. matrix: bone.getBaseMatrix().toArray(),
  78802. rest: bone.getRestPose().toArray()
  78803. };
  78804. serializationObject.bones.push(serializedBone);
  78805. if (bone.length) {
  78806. serializedBone.length = bone.length;
  78807. }
  78808. if (bone.animations && bone.animations.length > 0) {
  78809. serializedBone.animation = bone.animations[0].serialize();
  78810. }
  78811. serializationObject.ranges = [];
  78812. for (var name in this._ranges) {
  78813. var source = this._ranges[name];
  78814. if (!source) {
  78815. continue;
  78816. }
  78817. var range = {};
  78818. range.name = name;
  78819. range.from = source.from;
  78820. range.to = source.to;
  78821. serializationObject.ranges.push(range);
  78822. }
  78823. }
  78824. return serializationObject;
  78825. };
  78826. /**
  78827. * Creates a new skeleton from serialized data
  78828. * @param parsedSkeleton defines the serialized data
  78829. * @param scene defines the hosting scene
  78830. * @returns a new skeleton
  78831. */
  78832. Skeleton.Parse = function (parsedSkeleton, scene) {
  78833. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  78834. if (parsedSkeleton.dimensionsAtRest) {
  78835. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  78836. }
  78837. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  78838. var index;
  78839. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  78840. var parsedBone = parsedSkeleton.bones[index];
  78841. var parentBone = null;
  78842. if (parsedBone.parentBoneIndex > -1) {
  78843. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  78844. }
  78845. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  78846. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  78847. if (parsedBone.length) {
  78848. bone.length = parsedBone.length;
  78849. }
  78850. if (parsedBone.animation) {
  78851. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  78852. }
  78853. }
  78854. // placed after bones, so createAnimationRange can cascade down
  78855. if (parsedSkeleton.ranges) {
  78856. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  78857. var data = parsedSkeleton.ranges[index];
  78858. skeleton.createAnimationRange(data.name, data.from, data.to);
  78859. }
  78860. }
  78861. return skeleton;
  78862. };
  78863. /**
  78864. * Compute all node absolute transforms
  78865. * @param forceUpdate defines if computation must be done even if cache is up to date
  78866. */
  78867. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  78868. if (forceUpdate === void 0) { forceUpdate = false; }
  78869. var renderId = this._scene.getRenderId();
  78870. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  78871. this.bones[0].computeAbsoluteTransforms();
  78872. this._lastAbsoluteTransformsUpdateId = renderId;
  78873. }
  78874. };
  78875. /**
  78876. * Gets the root pose matrix
  78877. * @returns a matrix
  78878. */
  78879. Skeleton.prototype.getPoseMatrix = function () {
  78880. var poseMatrix = null;
  78881. if (this._meshesWithPoseMatrix.length > 0) {
  78882. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  78883. }
  78884. return poseMatrix;
  78885. };
  78886. /**
  78887. * Sorts bones per internal index
  78888. */
  78889. Skeleton.prototype.sortBones = function () {
  78890. var bones = new Array();
  78891. var visited = new Array(this.bones.length);
  78892. for (var index = 0; index < this.bones.length; index++) {
  78893. this._sortBones(index, bones, visited);
  78894. }
  78895. this.bones = bones;
  78896. };
  78897. Skeleton.prototype._sortBones = function (index, bones, visited) {
  78898. if (visited[index]) {
  78899. return;
  78900. }
  78901. visited[index] = true;
  78902. var bone = this.bones[index];
  78903. if (bone._index === undefined) {
  78904. bone._index = index;
  78905. }
  78906. var parentBone = bone.getParent();
  78907. if (parentBone) {
  78908. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  78909. }
  78910. bones.push(bone);
  78911. };
  78912. return Skeleton;
  78913. }());
  78914. BABYLON.Skeleton = Skeleton;
  78915. })(BABYLON || (BABYLON = {}));
  78916. //# sourceMappingURL=babylon.skeleton.js.map
  78917. var BABYLON;
  78918. (function (BABYLON) {
  78919. var SphericalPolynomial = /** @class */ (function () {
  78920. function SphericalPolynomial() {
  78921. this.x = BABYLON.Vector3.Zero();
  78922. this.y = BABYLON.Vector3.Zero();
  78923. this.z = BABYLON.Vector3.Zero();
  78924. this.xx = BABYLON.Vector3.Zero();
  78925. this.yy = BABYLON.Vector3.Zero();
  78926. this.zz = BABYLON.Vector3.Zero();
  78927. this.xy = BABYLON.Vector3.Zero();
  78928. this.yz = BABYLON.Vector3.Zero();
  78929. this.zx = BABYLON.Vector3.Zero();
  78930. }
  78931. SphericalPolynomial.prototype.addAmbient = function (color) {
  78932. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78933. this.xx = this.xx.add(colorVector);
  78934. this.yy = this.yy.add(colorVector);
  78935. this.zz = this.zz.add(colorVector);
  78936. };
  78937. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  78938. var result = new SphericalPolynomial();
  78939. result.x = harmonics.L11.scale(1.02333);
  78940. result.y = harmonics.L1_1.scale(1.02333);
  78941. result.z = harmonics.L10.scale(1.02333);
  78942. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  78943. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  78944. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  78945. result.yz = harmonics.L2_1.scale(0.858086);
  78946. result.zx = harmonics.L21.scale(0.858086);
  78947. result.xy = harmonics.L2_2.scale(0.858086);
  78948. result.scale(1.0 / Math.PI);
  78949. return result;
  78950. };
  78951. SphericalPolynomial.prototype.scale = function (scale) {
  78952. this.x = this.x.scale(scale);
  78953. this.y = this.y.scale(scale);
  78954. this.z = this.z.scale(scale);
  78955. this.xx = this.xx.scale(scale);
  78956. this.yy = this.yy.scale(scale);
  78957. this.zz = this.zz.scale(scale);
  78958. this.yz = this.yz.scale(scale);
  78959. this.zx = this.zx.scale(scale);
  78960. this.xy = this.xy.scale(scale);
  78961. };
  78962. return SphericalPolynomial;
  78963. }());
  78964. BABYLON.SphericalPolynomial = SphericalPolynomial;
  78965. var SphericalHarmonics = /** @class */ (function () {
  78966. function SphericalHarmonics() {
  78967. this.L00 = BABYLON.Vector3.Zero();
  78968. this.L1_1 = BABYLON.Vector3.Zero();
  78969. this.L10 = BABYLON.Vector3.Zero();
  78970. this.L11 = BABYLON.Vector3.Zero();
  78971. this.L2_2 = BABYLON.Vector3.Zero();
  78972. this.L2_1 = BABYLON.Vector3.Zero();
  78973. this.L20 = BABYLON.Vector3.Zero();
  78974. this.L21 = BABYLON.Vector3.Zero();
  78975. this.L22 = BABYLON.Vector3.Zero();
  78976. }
  78977. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  78978. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  78979. var c = colorVector.scale(deltaSolidAngle);
  78980. this.L00 = this.L00.add(c.scale(0.282095));
  78981. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  78982. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  78983. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  78984. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  78985. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  78986. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  78987. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  78988. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  78989. };
  78990. SphericalHarmonics.prototype.scale = function (scale) {
  78991. this.L00 = this.L00.scale(scale);
  78992. this.L1_1 = this.L1_1.scale(scale);
  78993. this.L10 = this.L10.scale(scale);
  78994. this.L11 = this.L11.scale(scale);
  78995. this.L2_2 = this.L2_2.scale(scale);
  78996. this.L2_1 = this.L2_1.scale(scale);
  78997. this.L20 = this.L20.scale(scale);
  78998. this.L21 = this.L21.scale(scale);
  78999. this.L22 = this.L22.scale(scale);
  79000. };
  79001. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79002. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79003. //
  79004. // E_lm = A_l * L_lm
  79005. //
  79006. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79007. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79008. // the scaling factors are given in equation 9.
  79009. // Constant (Band 0)
  79010. this.L00 = this.L00.scale(3.141593);
  79011. // Linear (Band 1)
  79012. this.L1_1 = this.L1_1.scale(2.094395);
  79013. this.L10 = this.L10.scale(2.094395);
  79014. this.L11 = this.L11.scale(2.094395);
  79015. // Quadratic (Band 2)
  79016. this.L2_2 = this.L2_2.scale(0.785398);
  79017. this.L2_1 = this.L2_1.scale(0.785398);
  79018. this.L20 = this.L20.scale(0.785398);
  79019. this.L21 = this.L21.scale(0.785398);
  79020. this.L22 = this.L22.scale(0.785398);
  79021. };
  79022. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79023. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79024. // L = (1/pi) * E * rho
  79025. //
  79026. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79027. this.scale(1.0 / Math.PI);
  79028. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79029. // (The pixel shader must apply albedo after texture fetches, etc).
  79030. };
  79031. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79032. var result = new SphericalHarmonics();
  79033. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79034. result.L1_1 = polynomial.y.scale(0.977204);
  79035. result.L10 = polynomial.z.scale(0.977204);
  79036. result.L11 = polynomial.x.scale(0.977204);
  79037. result.L2_2 = polynomial.xy.scale(1.16538);
  79038. result.L2_1 = polynomial.yz.scale(1.16538);
  79039. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79040. result.L21 = polynomial.zx.scale(1.16538);
  79041. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79042. result.scale(Math.PI);
  79043. return result;
  79044. };
  79045. return SphericalHarmonics;
  79046. }());
  79047. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79048. })(BABYLON || (BABYLON = {}));
  79049. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79050. var BABYLON;
  79051. (function (BABYLON) {
  79052. var FileFaceOrientation = /** @class */ (function () {
  79053. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79054. this.name = name;
  79055. this.worldAxisForNormal = worldAxisForNormal;
  79056. this.worldAxisForFileX = worldAxisForFileX;
  79057. this.worldAxisForFileY = worldAxisForFileY;
  79058. }
  79059. return FileFaceOrientation;
  79060. }());
  79061. ;
  79062. /**
  79063. * Helper class dealing with the extraction of spherical polynomial dataArray
  79064. * from a cube map.
  79065. */
  79066. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79067. function CubeMapToSphericalPolynomialTools() {
  79068. }
  79069. /**
  79070. * Converts a texture to the according Spherical Polynomial data.
  79071. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79072. *
  79073. * @param texture The texture to extract the information from.
  79074. * @return The Spherical Polynomial data.
  79075. */
  79076. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79077. if (!texture.isCube) {
  79078. // Only supports cube Textures currently.
  79079. return null;
  79080. }
  79081. var size = texture.getSize().width;
  79082. var right = texture.readPixels(0);
  79083. var left = texture.readPixels(1);
  79084. var up;
  79085. var down;
  79086. if (texture.isRenderTarget) {
  79087. up = texture.readPixels(3);
  79088. down = texture.readPixels(2);
  79089. }
  79090. else {
  79091. up = texture.readPixels(2);
  79092. down = texture.readPixels(3);
  79093. }
  79094. var front = texture.readPixels(4);
  79095. var back = texture.readPixels(5);
  79096. var gammaSpace = texture.gammaSpace;
  79097. // Always read as RGBA.
  79098. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79099. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79100. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79101. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79102. }
  79103. var cubeInfo = {
  79104. size: size,
  79105. right: right,
  79106. left: left,
  79107. up: up,
  79108. down: down,
  79109. front: front,
  79110. back: back,
  79111. format: format,
  79112. type: type,
  79113. gammaSpace: gammaSpace,
  79114. };
  79115. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79116. };
  79117. /**
  79118. * Converts a cubemap to the according Spherical Polynomial data.
  79119. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79120. *
  79121. * @param cubeInfo The Cube map to extract the information from.
  79122. * @return The Spherical Polynomial data.
  79123. */
  79124. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79125. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79126. var totalSolidAngle = 0.0;
  79127. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79128. var du = 2.0 / cubeInfo.size;
  79129. var dv = du;
  79130. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79131. var minUV = du * 0.5 - 1.0;
  79132. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79133. var fileFace = this.FileFaces[faceIndex];
  79134. var dataArray = cubeInfo[fileFace.name];
  79135. var v = minUV;
  79136. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79137. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79138. // Because SP is still linear, so summation is fine in that basis.
  79139. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79140. for (var y = 0; y < cubeInfo.size; y++) {
  79141. var u = minUV;
  79142. for (var x = 0; x < cubeInfo.size; x++) {
  79143. // World direction (not normalised)
  79144. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79145. worldDirection.normalize();
  79146. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79147. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79148. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79149. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79150. // Handle Integer types.
  79151. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79152. r /= 255;
  79153. g /= 255;
  79154. b /= 255;
  79155. }
  79156. // Handle Gamma space textures.
  79157. if (cubeInfo.gammaSpace) {
  79158. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79159. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79160. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79161. }
  79162. var color = new BABYLON.Color3(r, g, b);
  79163. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79164. totalSolidAngle += deltaSolidAngle;
  79165. u += du;
  79166. }
  79167. v += dv;
  79168. }
  79169. }
  79170. // Solid angle for entire sphere is 4*pi
  79171. var sphereSolidAngle = 4.0 * Math.PI;
  79172. // Adjust the solid angle to allow for how many faces we processed.
  79173. var facesProcessed = 6.0;
  79174. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79175. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79176. // This is needed because the numerical integration over the cube uses a
  79177. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79178. // and also to compensate for accumulative error due to float precision in the summation.
  79179. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79180. sphericalHarmonics.scale(correctionFactor);
  79181. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79182. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79183. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79184. };
  79185. CubeMapToSphericalPolynomialTools.FileFaces = [
  79186. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79187. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79188. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79189. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79190. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79191. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79192. ];
  79193. return CubeMapToSphericalPolynomialTools;
  79194. }());
  79195. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79196. })(BABYLON || (BABYLON = {}));
  79197. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79198. var BABYLON;
  79199. (function (BABYLON) {
  79200. /**
  79201. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79202. */
  79203. var PanoramaToCubeMapTools = /** @class */ (function () {
  79204. function PanoramaToCubeMapTools() {
  79205. }
  79206. /**
  79207. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79208. *
  79209. * @param float32Array The source data.
  79210. * @param inputWidth The width of the input panorama.
  79211. * @param inputhHeight The height of the input panorama.
  79212. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79213. * @return The cubemap data
  79214. */
  79215. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79216. if (!float32Array) {
  79217. throw "ConvertPanoramaToCubemap: input cannot be null";
  79218. }
  79219. if (float32Array.length != inputWidth * inputHeight * 3) {
  79220. throw "ConvertPanoramaToCubemap: input size is wrong";
  79221. }
  79222. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79223. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79224. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79225. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79226. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79227. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79228. return {
  79229. front: textureFront,
  79230. back: textureBack,
  79231. left: textureLeft,
  79232. right: textureRight,
  79233. up: textureUp,
  79234. down: textureDown,
  79235. size: size,
  79236. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79237. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79238. gammaSpace: false,
  79239. };
  79240. };
  79241. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79242. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79243. var textureArray = new Float32Array(buffer);
  79244. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79245. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79246. var dy = 1 / texSize;
  79247. var fy = 0;
  79248. for (var y = 0; y < texSize; y++) {
  79249. var xv1 = faceData[0];
  79250. var xv2 = faceData[2];
  79251. for (var x = 0; x < texSize; x++) {
  79252. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79253. v.normalize();
  79254. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79255. // 3 channels per pixels
  79256. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79257. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79258. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79259. xv1 = xv1.add(rotDX1);
  79260. xv2 = xv2.add(rotDX2);
  79261. }
  79262. fy += dy;
  79263. }
  79264. return textureArray;
  79265. };
  79266. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79267. var theta = Math.atan2(vDir.z, vDir.x);
  79268. var phi = Math.acos(vDir.y);
  79269. while (theta < -Math.PI)
  79270. theta += 2 * Math.PI;
  79271. while (theta > Math.PI)
  79272. theta -= 2 * Math.PI;
  79273. var dx = theta / Math.PI;
  79274. var dy = phi / Math.PI;
  79275. // recenter.
  79276. dx = dx * 0.5 + 0.5;
  79277. var px = Math.round(dx * inputWidth);
  79278. if (px < 0)
  79279. px = 0;
  79280. else if (px >= inputWidth)
  79281. px = inputWidth - 1;
  79282. var py = Math.round(dy * inputHeight);
  79283. if (py < 0)
  79284. py = 0;
  79285. else if (py >= inputHeight)
  79286. py = inputHeight - 1;
  79287. var inputY = (inputHeight - py - 1);
  79288. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79289. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79290. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79291. return {
  79292. r: r,
  79293. g: g,
  79294. b: b
  79295. };
  79296. };
  79297. PanoramaToCubeMapTools.FACE_FRONT = [
  79298. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79299. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79300. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79301. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79302. ];
  79303. PanoramaToCubeMapTools.FACE_BACK = [
  79304. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79305. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79306. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79307. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79308. ];
  79309. PanoramaToCubeMapTools.FACE_RIGHT = [
  79310. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79311. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79312. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79313. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79314. ];
  79315. PanoramaToCubeMapTools.FACE_LEFT = [
  79316. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79317. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79318. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79319. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79320. ];
  79321. PanoramaToCubeMapTools.FACE_DOWN = [
  79322. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79323. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79324. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79325. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79326. ];
  79327. PanoramaToCubeMapTools.FACE_UP = [
  79328. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79329. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79330. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79331. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79332. ];
  79333. return PanoramaToCubeMapTools;
  79334. }());
  79335. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79336. })(BABYLON || (BABYLON = {}));
  79337. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79338. var BABYLON;
  79339. (function (BABYLON) {
  79340. ;
  79341. /**
  79342. * This groups tools to convert HDR texture to native colors array.
  79343. */
  79344. var HDRTools = /** @class */ (function () {
  79345. function HDRTools() {
  79346. }
  79347. HDRTools.Ldexp = function (mantissa, exponent) {
  79348. if (exponent > 1023) {
  79349. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79350. }
  79351. if (exponent < -1074) {
  79352. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79353. }
  79354. return mantissa * Math.pow(2, exponent);
  79355. };
  79356. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79357. if (exponent > 0) { /*nonzero pixel*/
  79358. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79359. float32array[index + 0] = red * exponent;
  79360. float32array[index + 1] = green * exponent;
  79361. float32array[index + 2] = blue * exponent;
  79362. }
  79363. else {
  79364. float32array[index + 0] = 0;
  79365. float32array[index + 1] = 0;
  79366. float32array[index + 2] = 0;
  79367. }
  79368. };
  79369. HDRTools.readStringLine = function (uint8array, startIndex) {
  79370. var line = "";
  79371. var character = "";
  79372. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79373. character = String.fromCharCode(uint8array[i]);
  79374. if (character == "\n") {
  79375. break;
  79376. }
  79377. line += character;
  79378. }
  79379. return line;
  79380. };
  79381. /**
  79382. * Reads header information from an RGBE texture stored in a native array.
  79383. * More information on this format are available here:
  79384. * https://en.wikipedia.org/wiki/RGBE_image_format
  79385. *
  79386. * @param uint8array The binary file stored in native array.
  79387. * @return The header information.
  79388. */
  79389. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79390. var height = 0;
  79391. var width = 0;
  79392. var line = this.readStringLine(uint8array, 0);
  79393. if (line[0] != '#' || line[1] != '?') {
  79394. throw "Bad HDR Format.";
  79395. }
  79396. var endOfHeader = false;
  79397. var findFormat = false;
  79398. var lineIndex = 0;
  79399. do {
  79400. lineIndex += (line.length + 1);
  79401. line = this.readStringLine(uint8array, lineIndex);
  79402. if (line == "FORMAT=32-bit_rle_rgbe") {
  79403. findFormat = true;
  79404. }
  79405. else if (line.length == 0) {
  79406. endOfHeader = true;
  79407. }
  79408. } while (!endOfHeader);
  79409. if (!findFormat) {
  79410. throw "HDR Bad header format, unsupported FORMAT";
  79411. }
  79412. lineIndex += (line.length + 1);
  79413. line = this.readStringLine(uint8array, lineIndex);
  79414. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79415. var match = sizeRegexp.exec(line);
  79416. // TODO. Support +Y and -X if needed.
  79417. if (!match || match.length < 3) {
  79418. throw "HDR Bad header format, no size";
  79419. }
  79420. width = parseInt(match[2]);
  79421. height = parseInt(match[1]);
  79422. if (width < 8 || width > 0x7fff) {
  79423. throw "HDR Bad header format, unsupported size";
  79424. }
  79425. lineIndex += (line.length + 1);
  79426. return {
  79427. height: height,
  79428. width: width,
  79429. dataPosition: lineIndex
  79430. };
  79431. };
  79432. /**
  79433. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79434. * This RGBE texture needs to store the information as a panorama.
  79435. *
  79436. * More information on this format are available here:
  79437. * https://en.wikipedia.org/wiki/RGBE_image_format
  79438. *
  79439. * @param buffer The binary file stored in an array buffer.
  79440. * @param size The expected size of the extracted cubemap.
  79441. * @return The Cube Map information.
  79442. */
  79443. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79444. var uint8array = new Uint8Array(buffer);
  79445. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79446. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79447. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79448. return cubeMapData;
  79449. };
  79450. /**
  79451. * Returns the pixels data extracted from an RGBE texture.
  79452. * This pixels will be stored left to right up to down in the R G B order in one array.
  79453. *
  79454. * More information on this format are available here:
  79455. * https://en.wikipedia.org/wiki/RGBE_image_format
  79456. *
  79457. * @param uint8array The binary file stored in an array buffer.
  79458. * @param hdrInfo The header information of the file.
  79459. * @return The pixels data in RGB right to left up to down order.
  79460. */
  79461. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79462. // Keep for multi format supports.
  79463. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79464. };
  79465. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  79466. var num_scanlines = hdrInfo.height;
  79467. var scanline_width = hdrInfo.width;
  79468. var a, b, c, d, count;
  79469. var dataIndex = hdrInfo.dataPosition;
  79470. var index = 0, endIndex = 0, i = 0;
  79471. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  79472. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  79473. // 3 channels of 4 bytes per pixel in float.
  79474. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  79475. var resultArray = new Float32Array(resultBuffer);
  79476. // read in each successive scanline
  79477. while (num_scanlines > 0) {
  79478. a = uint8array[dataIndex++];
  79479. b = uint8array[dataIndex++];
  79480. c = uint8array[dataIndex++];
  79481. d = uint8array[dataIndex++];
  79482. if (a != 2 || b != 2 || (c & 0x80)) {
  79483. // this file is not run length encoded
  79484. throw "HDR Bad header format, not RLE";
  79485. }
  79486. if (((c << 8) | d) != scanline_width) {
  79487. throw "HDR Bad header format, wrong scan line width";
  79488. }
  79489. index = 0;
  79490. // read each of the four channels for the scanline into the buffer
  79491. for (i = 0; i < 4; i++) {
  79492. endIndex = (i + 1) * scanline_width;
  79493. while (index < endIndex) {
  79494. a = uint8array[dataIndex++];
  79495. b = uint8array[dataIndex++];
  79496. if (a > 128) {
  79497. // a run of the same value
  79498. count = a - 128;
  79499. if ((count == 0) || (count > endIndex - index)) {
  79500. throw "HDR Bad Format, bad scanline data (run)";
  79501. }
  79502. while (count-- > 0) {
  79503. scanLineArray[index++] = b;
  79504. }
  79505. }
  79506. else {
  79507. // a non-run
  79508. count = a;
  79509. if ((count == 0) || (count > endIndex - index)) {
  79510. throw "HDR Bad Format, bad scanline data (non-run)";
  79511. }
  79512. scanLineArray[index++] = b;
  79513. if (--count > 0) {
  79514. for (var j = 0; j < count; j++) {
  79515. scanLineArray[index++] = uint8array[dataIndex++];
  79516. }
  79517. }
  79518. }
  79519. }
  79520. }
  79521. // now convert data from buffer into floats
  79522. for (i = 0; i < scanline_width; i++) {
  79523. a = scanLineArray[i];
  79524. b = scanLineArray[i + scanline_width];
  79525. c = scanLineArray[i + 2 * scanline_width];
  79526. d = scanLineArray[i + 3 * scanline_width];
  79527. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  79528. }
  79529. num_scanlines--;
  79530. }
  79531. return resultArray;
  79532. };
  79533. return HDRTools;
  79534. }());
  79535. BABYLON.HDRTools = HDRTools;
  79536. })(BABYLON || (BABYLON = {}));
  79537. //# sourceMappingURL=babylon.hdr.js.map
  79538. var BABYLON;
  79539. (function (BABYLON) {
  79540. /**
  79541. * This represents a texture coming from an HDR input.
  79542. *
  79543. * The only supported format is currently panorama picture stored in RGBE format.
  79544. * Example of such files can be found on HDRLib: http://hdrlib.com/
  79545. */
  79546. var HDRCubeTexture = /** @class */ (function (_super) {
  79547. __extends(HDRCubeTexture, _super);
  79548. /**
  79549. * Instantiates an HDRTexture from the following parameters.
  79550. *
  79551. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  79552. * @param scene The scene the texture will be used in
  79553. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  79554. * @param noMipmap Forces to not generate the mipmap if true
  79555. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  79556. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  79557. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  79558. */
  79559. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  79560. if (noMipmap === void 0) { noMipmap = false; }
  79561. if (generateHarmonics === void 0) { generateHarmonics = true; }
  79562. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  79563. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  79564. if (onLoad === void 0) { onLoad = null; }
  79565. if (onError === void 0) { onError = null; }
  79566. var _this = _super.call(this, scene) || this;
  79567. _this._useInGammaSpace = false;
  79568. _this._generateHarmonics = true;
  79569. _this._isBABYLONPreprocessed = false;
  79570. _this._onLoad = null;
  79571. _this._onError = null;
  79572. /**
  79573. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  79574. */
  79575. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  79576. /**
  79577. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  79578. * This is usefull at run time to apply the good shader.
  79579. */
  79580. _this.isPMREM = false;
  79581. _this._isBlocking = true;
  79582. _this._rotationY = 0;
  79583. /**
  79584. * Gets or sets the center of the bounding box associated with the cube texture
  79585. * It must define where the camera used to render the texture was set
  79586. */
  79587. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  79588. if (!url) {
  79589. return _this;
  79590. }
  79591. _this.name = url;
  79592. _this.url = url;
  79593. _this.hasAlpha = false;
  79594. _this.isCube = true;
  79595. _this._textureMatrix = BABYLON.Matrix.Identity();
  79596. _this._onLoad = onLoad;
  79597. _this._onError = onError;
  79598. _this.gammaSpace = false;
  79599. var caps = scene.getEngine().getCaps();
  79600. if (size) {
  79601. _this._isBABYLONPreprocessed = false;
  79602. _this._noMipmap = noMipmap;
  79603. _this._size = size;
  79604. _this._useInGammaSpace = useInGammaSpace;
  79605. _this._usePMREMGenerator = usePMREMGenerator &&
  79606. caps.textureLOD &&
  79607. caps.textureFloat &&
  79608. !_this._useInGammaSpace;
  79609. }
  79610. else {
  79611. _this._isBABYLONPreprocessed = true;
  79612. _this._noMipmap = false;
  79613. _this._useInGammaSpace = false;
  79614. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  79615. !_this._useInGammaSpace;
  79616. }
  79617. _this.isPMREM = _this._usePMREMGenerator;
  79618. _this._texture = _this._getFromCache(url, _this._noMipmap);
  79619. if (!_this._texture) {
  79620. if (!scene.useDelayedTextureLoading) {
  79621. _this.loadTexture();
  79622. }
  79623. else {
  79624. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  79625. }
  79626. }
  79627. return _this;
  79628. }
  79629. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  79630. /**
  79631. * Gets wether or not the texture is blocking during loading.
  79632. */
  79633. get: function () {
  79634. return this._isBlocking;
  79635. },
  79636. /**
  79637. * Sets wether or not the texture is blocking during loading.
  79638. */
  79639. set: function (value) {
  79640. this._isBlocking = value;
  79641. },
  79642. enumerable: true,
  79643. configurable: true
  79644. });
  79645. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  79646. /**
  79647. * Gets texture matrix rotation angle around Y axis radians.
  79648. */
  79649. get: function () {
  79650. return this._rotationY;
  79651. },
  79652. /**
  79653. * Sets texture matrix rotation angle around Y axis in radians.
  79654. */
  79655. set: function (value) {
  79656. this._rotationY = value;
  79657. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  79658. },
  79659. enumerable: true,
  79660. configurable: true
  79661. });
  79662. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  79663. get: function () {
  79664. return this._boundingBoxSize;
  79665. },
  79666. /**
  79667. * Gets or sets the size of the bounding box associated with the cube texture
  79668. * When defined, the cubemap will switch to local mode
  79669. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  79670. * @example https://www.babylonjs-playground.com/#RNASML
  79671. */
  79672. set: function (value) {
  79673. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  79674. return;
  79675. }
  79676. this._boundingBoxSize = value;
  79677. var scene = this.getScene();
  79678. if (scene) {
  79679. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  79680. }
  79681. },
  79682. enumerable: true,
  79683. configurable: true
  79684. });
  79685. /**
  79686. * Occurs when the file is a preprocessed .babylon.hdr file.
  79687. */
  79688. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  79689. var _this = this;
  79690. var mipLevels = 0;
  79691. var floatArrayView = null;
  79692. var scene = this.getScene();
  79693. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  79694. var mips = new Array();
  79695. if (!floatArrayView) {
  79696. return mips;
  79697. }
  79698. var startIndex = 30;
  79699. for (var level = 0; level < mipLevels; level++) {
  79700. mips.push([]);
  79701. // Fill each pixel of the mip level.
  79702. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  79703. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79704. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  79705. mips[level].push(faceData);
  79706. startIndex += faceSize;
  79707. }
  79708. }
  79709. return mips;
  79710. } : null;
  79711. var callback = function (buffer) {
  79712. var scene = _this.getScene();
  79713. if (!scene) {
  79714. return null;
  79715. }
  79716. // Create Native Array Views
  79717. var intArrayView = new Int32Array(buffer);
  79718. floatArrayView = new Float32Array(buffer);
  79719. // Fill header.
  79720. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  79721. _this._size = intArrayView[1]; // CubeMap max mip face size.
  79722. // Update Texture Information.
  79723. if (!_this._texture) {
  79724. return null;
  79725. }
  79726. _this._texture.updateSize(_this._size, _this._size);
  79727. // Fill polynomial information.
  79728. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  79729. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  79730. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  79731. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  79732. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  79733. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  79734. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  79735. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  79736. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  79737. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  79738. _this.sphericalPolynomial = sphericalPolynomial;
  79739. // Fill pixel data.
  79740. mipLevels = intArrayView[29]; // Number of mip levels.
  79741. var startIndex = 30;
  79742. var data = [];
  79743. var faceSize = Math.pow(_this._size, 2) * 3;
  79744. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79745. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  79746. startIndex += faceSize;
  79747. }
  79748. var results = [];
  79749. var byteArray = null;
  79750. // Push each faces.
  79751. for (var k = 0; k < 6; k++) {
  79752. var dataFace = null;
  79753. // To be deprecated.
  79754. if (version === 1) {
  79755. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  79756. dataFace = data[j];
  79757. }
  79758. // If special cases.
  79759. if (!mipmapGenerator && dataFace) {
  79760. if (!scene.getEngine().getCaps().textureFloat) {
  79761. // 3 channels of 1 bytes per pixel in bytes.
  79762. var byteBuffer = new ArrayBuffer(faceSize);
  79763. byteArray = new Uint8Array(byteBuffer);
  79764. }
  79765. for (var i = 0; i < _this._size * _this._size; i++) {
  79766. // Put in gamma space if requested.
  79767. if (_this._useInGammaSpace) {
  79768. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79769. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79770. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79771. }
  79772. // Convert to int texture for fallback.
  79773. if (byteArray) {
  79774. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79775. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79776. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79777. // May use luminance instead if the result is not accurate.
  79778. var max = Math.max(Math.max(r, g), b);
  79779. if (max > 255) {
  79780. var scale = 255 / max;
  79781. r *= scale;
  79782. g *= scale;
  79783. b *= scale;
  79784. }
  79785. byteArray[(i * 3) + 0] = r;
  79786. byteArray[(i * 3) + 1] = g;
  79787. byteArray[(i * 3) + 2] = b;
  79788. }
  79789. }
  79790. }
  79791. // Fill the array accordingly.
  79792. if (byteArray) {
  79793. results.push(byteArray);
  79794. }
  79795. else {
  79796. results.push(dataFace);
  79797. }
  79798. }
  79799. return results;
  79800. };
  79801. if (scene) {
  79802. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  79803. }
  79804. };
  79805. /**
  79806. * Occurs when the file is raw .hdr file.
  79807. */
  79808. HDRCubeTexture.prototype.loadHDRTexture = function () {
  79809. var _this = this;
  79810. var callback = function (buffer) {
  79811. var scene = _this.getScene();
  79812. if (!scene) {
  79813. return null;
  79814. }
  79815. // Extract the raw linear data.
  79816. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  79817. // Generate harmonics if needed.
  79818. if (_this._generateHarmonics) {
  79819. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  79820. _this.sphericalPolynomial = sphericalPolynomial;
  79821. }
  79822. var results = [];
  79823. var byteArray = null;
  79824. // Push each faces.
  79825. for (var j = 0; j < 6; j++) {
  79826. // Create uintarray fallback.
  79827. if (!scene.getEngine().getCaps().textureFloat) {
  79828. // 3 channels of 1 bytes per pixel in bytes.
  79829. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  79830. byteArray = new Uint8Array(byteBuffer);
  79831. }
  79832. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  79833. // If special cases.
  79834. if (_this._useInGammaSpace || byteArray) {
  79835. for (var i = 0; i < _this._size * _this._size; i++) {
  79836. // Put in gamma space if requested.
  79837. if (_this._useInGammaSpace) {
  79838. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  79839. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  79840. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  79841. }
  79842. // Convert to int texture for fallback.
  79843. if (byteArray) {
  79844. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  79845. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  79846. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  79847. // May use luminance instead if the result is not accurate.
  79848. var max = Math.max(Math.max(r, g), b);
  79849. if (max > 255) {
  79850. var scale = 255 / max;
  79851. r *= scale;
  79852. g *= scale;
  79853. b *= scale;
  79854. }
  79855. byteArray[(i * 3) + 0] = r;
  79856. byteArray[(i * 3) + 1] = g;
  79857. byteArray[(i * 3) + 2] = b;
  79858. }
  79859. }
  79860. }
  79861. if (byteArray) {
  79862. results.push(byteArray);
  79863. }
  79864. else {
  79865. results.push(dataFace);
  79866. }
  79867. }
  79868. return results;
  79869. };
  79870. var mipmapGenerator = null;
  79871. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  79872. // if (!this._noMipmap &&
  79873. // this._usePMREMGenerator) {
  79874. // mipmapGenerator = (data: ArrayBufferView[]) => {
  79875. // // Custom setup of the generator matching with the PBR shader values.
  79876. // var generator = new BABYLON.PMREMGenerator(data,
  79877. // this._size,
  79878. // this._size,
  79879. // 0,
  79880. // 3,
  79881. // this.getScene().getEngine().getCaps().textureFloat,
  79882. // 2048,
  79883. // 0.25,
  79884. // false,
  79885. // true);
  79886. // return generator.filterCubeMap();
  79887. // };
  79888. // }
  79889. var scene = this.getScene();
  79890. if (scene) {
  79891. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  79892. }
  79893. };
  79894. /**
  79895. * Starts the loading process of the texture.
  79896. */
  79897. HDRCubeTexture.prototype.loadTexture = function () {
  79898. if (this._isBABYLONPreprocessed) {
  79899. this.loadBabylonTexture();
  79900. }
  79901. else {
  79902. this.loadHDRTexture();
  79903. }
  79904. };
  79905. HDRCubeTexture.prototype.clone = function () {
  79906. var scene = this.getScene();
  79907. if (!scene) {
  79908. return this;
  79909. }
  79910. var size = (this._isBABYLONPreprocessed ? null : this._size);
  79911. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  79912. // Base texture
  79913. newTexture.level = this.level;
  79914. newTexture.wrapU = this.wrapU;
  79915. newTexture.wrapV = this.wrapV;
  79916. newTexture.coordinatesIndex = this.coordinatesIndex;
  79917. newTexture.coordinatesMode = this.coordinatesMode;
  79918. return newTexture;
  79919. };
  79920. // Methods
  79921. HDRCubeTexture.prototype.delayLoad = function () {
  79922. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  79923. return;
  79924. }
  79925. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  79926. this._texture = this._getFromCache(this.url, this._noMipmap);
  79927. if (!this._texture) {
  79928. this.loadTexture();
  79929. }
  79930. };
  79931. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  79932. return this._textureMatrix;
  79933. };
  79934. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  79935. this._textureMatrix = value;
  79936. };
  79937. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  79938. var texture = null;
  79939. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  79940. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  79941. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  79942. texture.name = parsedTexture.name;
  79943. texture.hasAlpha = parsedTexture.hasAlpha;
  79944. texture.level = parsedTexture.level;
  79945. texture.coordinatesMode = parsedTexture.coordinatesMode;
  79946. texture.isBlocking = parsedTexture.isBlocking;
  79947. }
  79948. if (texture) {
  79949. if (parsedTexture.boundingBoxPosition) {
  79950. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  79951. }
  79952. if (parsedTexture.boundingBoxSize) {
  79953. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  79954. }
  79955. if (parsedTexture.rotationY) {
  79956. texture.rotationY = parsedTexture.rotationY;
  79957. }
  79958. }
  79959. return texture;
  79960. };
  79961. HDRCubeTexture.prototype.serialize = function () {
  79962. if (!this.name) {
  79963. return null;
  79964. }
  79965. var serializationObject = {};
  79966. serializationObject.name = this.name;
  79967. serializationObject.hasAlpha = this.hasAlpha;
  79968. serializationObject.isCube = true;
  79969. serializationObject.level = this.level;
  79970. serializationObject.size = this._size;
  79971. serializationObject.coordinatesMode = this.coordinatesMode;
  79972. serializationObject.useInGammaSpace = this._useInGammaSpace;
  79973. serializationObject.generateHarmonics = this._generateHarmonics;
  79974. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  79975. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  79976. serializationObject.customType = "BABYLON.HDRCubeTexture";
  79977. serializationObject.noMipmap = this._noMipmap;
  79978. serializationObject.isBlocking = this._isBlocking;
  79979. serializationObject.rotationY = this._rotationY;
  79980. return serializationObject;
  79981. };
  79982. /**
  79983. * Saves as a file the data contained in the texture in a binary format.
  79984. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  79985. * as the spherical used in the lighting.
  79986. * @param url The HDR file url.
  79987. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  79988. * @param onError Method called if any error happens during download.
  79989. * @return The packed binary data.
  79990. */
  79991. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  79992. if (onError === void 0) { onError = null; }
  79993. var callback = function (buffer) {
  79994. var data = new Blob([buffer], { type: 'application/octet-stream' });
  79995. // Returns a URL you can use as a href.
  79996. var objUrl = window.URL.createObjectURL(data);
  79997. // Simulates a link to it and click to dowload.
  79998. var a = document.createElement("a");
  79999. document.body.appendChild(a);
  80000. a.style.display = "none";
  80001. a.href = objUrl;
  80002. a.download = "envmap.babylon.hdr";
  80003. a.click();
  80004. };
  80005. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  80006. };
  80007. /**
  80008. * Serializes the data contained in the texture in a binary format.
  80009. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  80010. * as the spherical used in the lighting.
  80011. * @param url The HDR file url.
  80012. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  80013. * @param onError Method called if any error happens during download.
  80014. * @return The packed binary data.
  80015. */
  80016. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  80017. if (onError === void 0) { onError = null; }
  80018. // Needs the url tho create the texture.
  80019. if (!url) {
  80020. return;
  80021. }
  80022. // Check Power of two size.
  80023. if (!BABYLON.Tools.IsExponentOfTwo(size)) { // Need to check engine.needPOTTextures
  80024. return;
  80025. }
  80026. // Coming Back in 3.x.
  80027. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  80028. };
  80029. HDRCubeTexture._facesMapping = [
  80030. "right",
  80031. "left",
  80032. "up",
  80033. "down",
  80034. "front",
  80035. "back"
  80036. ];
  80037. return HDRCubeTexture;
  80038. }(BABYLON.BaseTexture));
  80039. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80040. })(BABYLON || (BABYLON = {}));
  80041. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80042. var BABYLON;
  80043. (function (BABYLON) {
  80044. var IndexedVector2 = /** @class */ (function (_super) {
  80045. __extends(IndexedVector2, _super);
  80046. function IndexedVector2(original, index) {
  80047. var _this = _super.call(this, original.x, original.y) || this;
  80048. _this.index = index;
  80049. return _this;
  80050. }
  80051. return IndexedVector2;
  80052. }(BABYLON.Vector2));
  80053. var PolygonPoints = /** @class */ (function () {
  80054. function PolygonPoints() {
  80055. this.elements = new Array();
  80056. }
  80057. PolygonPoints.prototype.add = function (originalPoints) {
  80058. var _this = this;
  80059. var result = new Array();
  80060. originalPoints.forEach(function (point) {
  80061. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80062. var newPoint = new IndexedVector2(point, _this.elements.length);
  80063. result.push(newPoint);
  80064. _this.elements.push(newPoint);
  80065. }
  80066. });
  80067. return result;
  80068. };
  80069. PolygonPoints.prototype.computeBounds = function () {
  80070. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80071. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80072. this.elements.forEach(function (point) {
  80073. // x
  80074. if (point.x < lmin.x) {
  80075. lmin.x = point.x;
  80076. }
  80077. else if (point.x > lmax.x) {
  80078. lmax.x = point.x;
  80079. }
  80080. // y
  80081. if (point.y < lmin.y) {
  80082. lmin.y = point.y;
  80083. }
  80084. else if (point.y > lmax.y) {
  80085. lmax.y = point.y;
  80086. }
  80087. });
  80088. return {
  80089. min: lmin,
  80090. max: lmax,
  80091. width: lmax.x - lmin.x,
  80092. height: lmax.y - lmin.y
  80093. };
  80094. };
  80095. return PolygonPoints;
  80096. }());
  80097. var Polygon = /** @class */ (function () {
  80098. function Polygon() {
  80099. }
  80100. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80101. return [
  80102. new BABYLON.Vector2(xmin, ymin),
  80103. new BABYLON.Vector2(xmax, ymin),
  80104. new BABYLON.Vector2(xmax, ymax),
  80105. new BABYLON.Vector2(xmin, ymax)
  80106. ];
  80107. };
  80108. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80109. if (cx === void 0) { cx = 0; }
  80110. if (cy === void 0) { cy = 0; }
  80111. if (numberOfSides === void 0) { numberOfSides = 32; }
  80112. var result = new Array();
  80113. var angle = 0;
  80114. var increment = (Math.PI * 2) / numberOfSides;
  80115. for (var i = 0; i < numberOfSides; i++) {
  80116. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80117. angle -= increment;
  80118. }
  80119. return result;
  80120. };
  80121. Polygon.Parse = function (input) {
  80122. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80123. var i, result = [];
  80124. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80125. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80126. }
  80127. return result;
  80128. };
  80129. Polygon.StartingAt = function (x, y) {
  80130. return BABYLON.Path2.StartingAt(x, y);
  80131. };
  80132. return Polygon;
  80133. }());
  80134. BABYLON.Polygon = Polygon;
  80135. var PolygonMeshBuilder = /** @class */ (function () {
  80136. function PolygonMeshBuilder(name, contours, scene) {
  80137. this._points = new PolygonPoints();
  80138. this._outlinepoints = new PolygonPoints();
  80139. this._holes = new Array();
  80140. this._epoints = new Array();
  80141. this._eholes = new Array();
  80142. this._name = name;
  80143. this._scene = scene;
  80144. var points;
  80145. if (contours instanceof BABYLON.Path2) {
  80146. points = contours.getPoints();
  80147. }
  80148. else {
  80149. points = contours;
  80150. }
  80151. this._addToepoint(points);
  80152. this._points.add(points);
  80153. this._outlinepoints.add(points);
  80154. if (typeof earcut === 'undefined') {
  80155. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80156. }
  80157. }
  80158. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80159. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80160. var p = points_1[_i];
  80161. this._epoints.push(p.x, p.y);
  80162. }
  80163. };
  80164. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80165. this._points.add(hole);
  80166. var holepoints = new PolygonPoints();
  80167. holepoints.add(hole);
  80168. this._holes.push(holepoints);
  80169. this._eholes.push(this._epoints.length / 2);
  80170. this._addToepoint(hole);
  80171. return this;
  80172. };
  80173. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80174. var _this = this;
  80175. if (updatable === void 0) { updatable = false; }
  80176. if (depth === void 0) { depth = 0; }
  80177. var result = new BABYLON.Mesh(this._name, this._scene);
  80178. var normals = new Array();
  80179. var positions = new Array();
  80180. var uvs = new Array();
  80181. var bounds = this._points.computeBounds();
  80182. this._points.elements.forEach(function (p) {
  80183. normals.push(0, 1.0, 0);
  80184. positions.push(p.x, 0, p.y);
  80185. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80186. });
  80187. var indices = new Array();
  80188. var res = earcut(this._epoints, this._eholes, 2);
  80189. for (var i = 0; i < res.length; i++) {
  80190. indices.push(res[i]);
  80191. }
  80192. if (depth > 0) {
  80193. var positionscount = (positions.length / 3); //get the current pointcount
  80194. this._points.elements.forEach(function (p) {
  80195. normals.push(0, -1.0, 0);
  80196. positions.push(p.x, -depth, p.y);
  80197. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80198. });
  80199. var totalCount = indices.length;
  80200. for (var i = 0; i < totalCount; i += 3) {
  80201. var i0 = indices[i + 0];
  80202. var i1 = indices[i + 1];
  80203. var i2 = indices[i + 2];
  80204. indices.push(i2 + positionscount);
  80205. indices.push(i1 + positionscount);
  80206. indices.push(i0 + positionscount);
  80207. }
  80208. //Add the sides
  80209. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80210. this._holes.forEach(function (hole) {
  80211. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80212. });
  80213. }
  80214. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80215. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80216. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80217. result.setIndices(indices);
  80218. return result;
  80219. };
  80220. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80221. var StartIndex = positions.length / 3;
  80222. var ulength = 0;
  80223. for (var i = 0; i < points.elements.length; i++) {
  80224. var p = points.elements[i];
  80225. var p1;
  80226. if ((i + 1) > points.elements.length - 1) {
  80227. p1 = points.elements[0];
  80228. }
  80229. else {
  80230. p1 = points.elements[i + 1];
  80231. }
  80232. positions.push(p.x, 0, p.y);
  80233. positions.push(p.x, -depth, p.y);
  80234. positions.push(p1.x, 0, p1.y);
  80235. positions.push(p1.x, -depth, p1.y);
  80236. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80237. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80238. var v3 = v2.subtract(v1);
  80239. var v4 = new BABYLON.Vector3(0, 1, 0);
  80240. var vn = BABYLON.Vector3.Cross(v3, v4);
  80241. vn = vn.normalize();
  80242. uvs.push(ulength / bounds.width, 0);
  80243. uvs.push(ulength / bounds.width, 1);
  80244. ulength += v3.length();
  80245. uvs.push((ulength / bounds.width), 0);
  80246. uvs.push((ulength / bounds.width), 1);
  80247. if (!flip) {
  80248. normals.push(-vn.x, -vn.y, -vn.z);
  80249. normals.push(-vn.x, -vn.y, -vn.z);
  80250. normals.push(-vn.x, -vn.y, -vn.z);
  80251. normals.push(-vn.x, -vn.y, -vn.z);
  80252. indices.push(StartIndex);
  80253. indices.push(StartIndex + 1);
  80254. indices.push(StartIndex + 2);
  80255. indices.push(StartIndex + 1);
  80256. indices.push(StartIndex + 3);
  80257. indices.push(StartIndex + 2);
  80258. }
  80259. else {
  80260. normals.push(vn.x, vn.y, vn.z);
  80261. normals.push(vn.x, vn.y, vn.z);
  80262. normals.push(vn.x, vn.y, vn.z);
  80263. normals.push(vn.x, vn.y, vn.z);
  80264. indices.push(StartIndex);
  80265. indices.push(StartIndex + 2);
  80266. indices.push(StartIndex + 1);
  80267. indices.push(StartIndex + 1);
  80268. indices.push(StartIndex + 2);
  80269. indices.push(StartIndex + 3);
  80270. }
  80271. StartIndex += 4;
  80272. }
  80273. ;
  80274. };
  80275. return PolygonMeshBuilder;
  80276. }());
  80277. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80278. })(BABYLON || (BABYLON = {}));
  80279. //# sourceMappingURL=babylon.polygonMesh.js.map
  80280. var BABYLON;
  80281. (function (BABYLON) {
  80282. // Unique ID when we import meshes from Babylon to CSG
  80283. var currentCSGMeshId = 0;
  80284. // # class Vertex
  80285. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80286. // one to provide additional features like texture coordinates and vertex
  80287. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80288. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80289. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80290. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80291. // is not used anywhere else.
  80292. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80293. var Vertex = /** @class */ (function () {
  80294. function Vertex(pos, normal, uv) {
  80295. this.pos = pos;
  80296. this.normal = normal;
  80297. this.uv = uv;
  80298. }
  80299. Vertex.prototype.clone = function () {
  80300. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80301. };
  80302. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80303. // orientation of a polygon is flipped.
  80304. Vertex.prototype.flip = function () {
  80305. this.normal = this.normal.scale(-1);
  80306. };
  80307. // Create a new vertex between this vertex and `other` by linearly
  80308. // interpolating all properties using a parameter of `t`. Subclasses should
  80309. // override this to interpolate additional properties.
  80310. Vertex.prototype.interpolate = function (other, t) {
  80311. 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));
  80312. };
  80313. return Vertex;
  80314. }());
  80315. // # class Plane
  80316. // Represents a plane in 3D space.
  80317. var Plane = /** @class */ (function () {
  80318. function Plane(normal, w) {
  80319. this.normal = normal;
  80320. this.w = w;
  80321. }
  80322. Plane.FromPoints = function (a, b, c) {
  80323. var v0 = c.subtract(a);
  80324. var v1 = b.subtract(a);
  80325. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80326. return null;
  80327. }
  80328. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80329. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80330. };
  80331. Plane.prototype.clone = function () {
  80332. return new Plane(this.normal.clone(), this.w);
  80333. };
  80334. Plane.prototype.flip = function () {
  80335. this.normal.scaleInPlace(-1);
  80336. this.w = -this.w;
  80337. };
  80338. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80339. // fragments in the appropriate lists. Coplanar polygons go into either
  80340. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80341. // respect to this plane. Polygons in front or in back of this plane go into
  80342. // either `front` or `back`.
  80343. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80344. var COPLANAR = 0;
  80345. var FRONT = 1;
  80346. var BACK = 2;
  80347. var SPANNING = 3;
  80348. // Classify each point as well as the entire polygon into one of the above
  80349. // four classes.
  80350. var polygonType = 0;
  80351. var types = [];
  80352. var i;
  80353. var t;
  80354. for (i = 0; i < polygon.vertices.length; i++) {
  80355. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80356. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80357. polygonType |= type;
  80358. types.push(type);
  80359. }
  80360. // Put the polygon in the correct list, splitting it when necessary.
  80361. switch (polygonType) {
  80362. case COPLANAR:
  80363. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80364. break;
  80365. case FRONT:
  80366. front.push(polygon);
  80367. break;
  80368. case BACK:
  80369. back.push(polygon);
  80370. break;
  80371. case SPANNING:
  80372. var f = [], b = [];
  80373. for (i = 0; i < polygon.vertices.length; i++) {
  80374. var j = (i + 1) % polygon.vertices.length;
  80375. var ti = types[i], tj = types[j];
  80376. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80377. if (ti !== BACK)
  80378. f.push(vi);
  80379. if (ti !== FRONT)
  80380. b.push(ti !== BACK ? vi.clone() : vi);
  80381. if ((ti | tj) === SPANNING) {
  80382. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80383. var v = vi.interpolate(vj, t);
  80384. f.push(v);
  80385. b.push(v.clone());
  80386. }
  80387. }
  80388. var poly;
  80389. if (f.length >= 3) {
  80390. poly = new Polygon(f, polygon.shared);
  80391. if (poly.plane)
  80392. front.push(poly);
  80393. }
  80394. if (b.length >= 3) {
  80395. poly = new Polygon(b, polygon.shared);
  80396. if (poly.plane)
  80397. back.push(poly);
  80398. }
  80399. break;
  80400. }
  80401. };
  80402. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80403. // point is on the plane.
  80404. Plane.EPSILON = 1e-5;
  80405. return Plane;
  80406. }());
  80407. // # class Polygon
  80408. // Represents a convex polygon. The vertices used to initialize a polygon must
  80409. // be coplanar and form a convex loop.
  80410. //
  80411. // Each convex polygon has a `shared` property, which is shared between all
  80412. // polygons that are clones of each other or were split from the same polygon.
  80413. // This can be used to define per-polygon properties (such as surface color).
  80414. var Polygon = /** @class */ (function () {
  80415. function Polygon(vertices, shared) {
  80416. this.vertices = vertices;
  80417. this.shared = shared;
  80418. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80419. }
  80420. Polygon.prototype.clone = function () {
  80421. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80422. return new Polygon(vertices, this.shared);
  80423. };
  80424. Polygon.prototype.flip = function () {
  80425. this.vertices.reverse().map(function (v) { v.flip(); });
  80426. this.plane.flip();
  80427. };
  80428. return Polygon;
  80429. }());
  80430. // # class Node
  80431. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80432. // by picking a polygon to split along. That polygon (and all other coplanar
  80433. // polygons) are added directly to that node and the other polygons are added to
  80434. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80435. // no distinction between internal and leaf nodes.
  80436. var Node = /** @class */ (function () {
  80437. function Node(polygons) {
  80438. this.plane = null;
  80439. this.front = null;
  80440. this.back = null;
  80441. this.polygons = new Array();
  80442. if (polygons) {
  80443. this.build(polygons);
  80444. }
  80445. }
  80446. Node.prototype.clone = function () {
  80447. var node = new Node();
  80448. node.plane = this.plane && this.plane.clone();
  80449. node.front = this.front && this.front.clone();
  80450. node.back = this.back && this.back.clone();
  80451. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80452. return node;
  80453. };
  80454. // Convert solid space to empty space and empty space to solid space.
  80455. Node.prototype.invert = function () {
  80456. for (var i = 0; i < this.polygons.length; i++) {
  80457. this.polygons[i].flip();
  80458. }
  80459. if (this.plane) {
  80460. this.plane.flip();
  80461. }
  80462. if (this.front) {
  80463. this.front.invert();
  80464. }
  80465. if (this.back) {
  80466. this.back.invert();
  80467. }
  80468. var temp = this.front;
  80469. this.front = this.back;
  80470. this.back = temp;
  80471. };
  80472. // Recursively remove all polygons in `polygons` that are inside this BSP
  80473. // tree.
  80474. Node.prototype.clipPolygons = function (polygons) {
  80475. if (!this.plane)
  80476. return polygons.slice();
  80477. var front = new Array(), back = new Array();
  80478. for (var i = 0; i < polygons.length; i++) {
  80479. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80480. }
  80481. if (this.front) {
  80482. front = this.front.clipPolygons(front);
  80483. }
  80484. if (this.back) {
  80485. back = this.back.clipPolygons(back);
  80486. }
  80487. else {
  80488. back = [];
  80489. }
  80490. return front.concat(back);
  80491. };
  80492. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80493. // `bsp`.
  80494. Node.prototype.clipTo = function (bsp) {
  80495. this.polygons = bsp.clipPolygons(this.polygons);
  80496. if (this.front)
  80497. this.front.clipTo(bsp);
  80498. if (this.back)
  80499. this.back.clipTo(bsp);
  80500. };
  80501. // Return a list of all polygons in this BSP tree.
  80502. Node.prototype.allPolygons = function () {
  80503. var polygons = this.polygons.slice();
  80504. if (this.front)
  80505. polygons = polygons.concat(this.front.allPolygons());
  80506. if (this.back)
  80507. polygons = polygons.concat(this.back.allPolygons());
  80508. return polygons;
  80509. };
  80510. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80511. // new polygons are filtered down to the bottom of the tree and become new
  80512. // nodes there. Each set of polygons is partitioned using the first polygon
  80513. // (no heuristic is used to pick a good split).
  80514. Node.prototype.build = function (polygons) {
  80515. if (!polygons.length)
  80516. return;
  80517. if (!this.plane)
  80518. this.plane = polygons[0].plane.clone();
  80519. var front = new Array(), back = new Array();
  80520. for (var i = 0; i < polygons.length; i++) {
  80521. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80522. }
  80523. if (front.length) {
  80524. if (!this.front)
  80525. this.front = new Node();
  80526. this.front.build(front);
  80527. }
  80528. if (back.length) {
  80529. if (!this.back)
  80530. this.back = new Node();
  80531. this.back.build(back);
  80532. }
  80533. };
  80534. return Node;
  80535. }());
  80536. var CSG = /** @class */ (function () {
  80537. function CSG() {
  80538. this.polygons = new Array();
  80539. }
  80540. // Convert BABYLON.Mesh to BABYLON.CSG
  80541. CSG.FromMesh = function (mesh) {
  80542. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80543. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80544. if (mesh instanceof BABYLON.Mesh) {
  80545. mesh.computeWorldMatrix(true);
  80546. matrix = mesh.getWorldMatrix();
  80547. meshPosition = mesh.position.clone();
  80548. meshRotation = mesh.rotation.clone();
  80549. if (mesh.rotationQuaternion) {
  80550. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80551. }
  80552. meshScaling = mesh.scaling.clone();
  80553. }
  80554. else {
  80555. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80556. }
  80557. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80558. var subMeshes = mesh.subMeshes;
  80559. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80560. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80561. vertices = [];
  80562. for (var j = 0; j < 3; j++) {
  80563. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80564. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80565. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80566. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80567. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80568. vertex = new Vertex(position, normal, uv);
  80569. vertices.push(vertex);
  80570. }
  80571. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80572. // To handle the case of degenerated triangle
  80573. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80574. if (polygon.plane)
  80575. polygons.push(polygon);
  80576. }
  80577. }
  80578. var csg = CSG.FromPolygons(polygons);
  80579. csg.matrix = matrix;
  80580. csg.position = meshPosition;
  80581. csg.rotation = meshRotation;
  80582. csg.scaling = meshScaling;
  80583. csg.rotationQuaternion = meshRotationQuaternion;
  80584. currentCSGMeshId++;
  80585. return csg;
  80586. };
  80587. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80588. CSG.FromPolygons = function (polygons) {
  80589. var csg = new CSG();
  80590. csg.polygons = polygons;
  80591. return csg;
  80592. };
  80593. CSG.prototype.clone = function () {
  80594. var csg = new CSG();
  80595. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80596. csg.copyTransformAttributes(this);
  80597. return csg;
  80598. };
  80599. CSG.prototype.union = function (csg) {
  80600. var a = new Node(this.clone().polygons);
  80601. var b = new Node(csg.clone().polygons);
  80602. a.clipTo(b);
  80603. b.clipTo(a);
  80604. b.invert();
  80605. b.clipTo(a);
  80606. b.invert();
  80607. a.build(b.allPolygons());
  80608. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80609. };
  80610. CSG.prototype.unionInPlace = function (csg) {
  80611. var a = new Node(this.polygons);
  80612. var b = new Node(csg.polygons);
  80613. a.clipTo(b);
  80614. b.clipTo(a);
  80615. b.invert();
  80616. b.clipTo(a);
  80617. b.invert();
  80618. a.build(b.allPolygons());
  80619. this.polygons = a.allPolygons();
  80620. };
  80621. CSG.prototype.subtract = function (csg) {
  80622. var a = new Node(this.clone().polygons);
  80623. var b = new Node(csg.clone().polygons);
  80624. a.invert();
  80625. a.clipTo(b);
  80626. b.clipTo(a);
  80627. b.invert();
  80628. b.clipTo(a);
  80629. b.invert();
  80630. a.build(b.allPolygons());
  80631. a.invert();
  80632. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80633. };
  80634. CSG.prototype.subtractInPlace = function (csg) {
  80635. var a = new Node(this.polygons);
  80636. var b = new Node(csg.polygons);
  80637. a.invert();
  80638. a.clipTo(b);
  80639. b.clipTo(a);
  80640. b.invert();
  80641. b.clipTo(a);
  80642. b.invert();
  80643. a.build(b.allPolygons());
  80644. a.invert();
  80645. this.polygons = a.allPolygons();
  80646. };
  80647. CSG.prototype.intersect = function (csg) {
  80648. var a = new Node(this.clone().polygons);
  80649. var b = new Node(csg.clone().polygons);
  80650. a.invert();
  80651. b.clipTo(a);
  80652. b.invert();
  80653. a.clipTo(b);
  80654. b.clipTo(a);
  80655. a.build(b.allPolygons());
  80656. a.invert();
  80657. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80658. };
  80659. CSG.prototype.intersectInPlace = function (csg) {
  80660. var a = new Node(this.polygons);
  80661. var b = new Node(csg.polygons);
  80662. a.invert();
  80663. b.clipTo(a);
  80664. b.invert();
  80665. a.clipTo(b);
  80666. b.clipTo(a);
  80667. a.build(b.allPolygons());
  80668. a.invert();
  80669. this.polygons = a.allPolygons();
  80670. };
  80671. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  80672. // not modified.
  80673. CSG.prototype.inverse = function () {
  80674. var csg = this.clone();
  80675. csg.inverseInPlace();
  80676. return csg;
  80677. };
  80678. CSG.prototype.inverseInPlace = function () {
  80679. this.polygons.map(function (p) { p.flip(); });
  80680. };
  80681. // This is used to keep meshes transformations so they can be restored
  80682. // when we build back a Babylon Mesh
  80683. // NB : All CSG operations are performed in world coordinates
  80684. CSG.prototype.copyTransformAttributes = function (csg) {
  80685. this.matrix = csg.matrix;
  80686. this.position = csg.position;
  80687. this.rotation = csg.rotation;
  80688. this.scaling = csg.scaling;
  80689. this.rotationQuaternion = csg.rotationQuaternion;
  80690. return this;
  80691. };
  80692. // Build Raw mesh from CSG
  80693. // Coordinates here are in world space
  80694. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  80695. var matrix = this.matrix.clone();
  80696. matrix.invert();
  80697. 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;
  80698. if (keepSubMeshes) {
  80699. // Sort Polygons, since subMeshes are indices range
  80700. polygons.sort(function (a, b) {
  80701. if (a.shared.meshId === b.shared.meshId) {
  80702. return a.shared.subMeshId - b.shared.subMeshId;
  80703. }
  80704. else {
  80705. return a.shared.meshId - b.shared.meshId;
  80706. }
  80707. });
  80708. }
  80709. for (var i = 0, il = polygons.length; i < il; i++) {
  80710. polygon = polygons[i];
  80711. // Building SubMeshes
  80712. if (!subMesh_dict[polygon.shared.meshId]) {
  80713. subMesh_dict[polygon.shared.meshId] = {};
  80714. }
  80715. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  80716. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  80717. indexStart: +Infinity,
  80718. indexEnd: -Infinity,
  80719. materialIndex: polygon.shared.materialIndex
  80720. };
  80721. }
  80722. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  80723. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  80724. polygonIndices[0] = 0;
  80725. polygonIndices[1] = j - 1;
  80726. polygonIndices[2] = j;
  80727. for (var k = 0; k < 3; k++) {
  80728. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  80729. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  80730. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  80731. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  80732. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  80733. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  80734. // Check if 2 points can be merged
  80735. if (!(typeof vertex_idx !== 'undefined' &&
  80736. normals[vertex_idx * 3] === localNormal.x &&
  80737. normals[vertex_idx * 3 + 1] === localNormal.y &&
  80738. normals[vertex_idx * 3 + 2] === localNormal.z &&
  80739. uvs[vertex_idx * 2] === uv.x &&
  80740. uvs[vertex_idx * 2 + 1] === uv.y)) {
  80741. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  80742. uvs.push(uv.x, uv.y);
  80743. normals.push(normal.x, normal.y, normal.z);
  80744. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  80745. }
  80746. indices.push(vertex_idx);
  80747. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  80748. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  80749. currentIndex++;
  80750. }
  80751. }
  80752. }
  80753. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  80754. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  80755. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  80756. mesh.setIndices(indices, null);
  80757. if (keepSubMeshes) {
  80758. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  80759. var materialIndexOffset = 0, materialMaxIndex;
  80760. mesh.subMeshes = new Array();
  80761. for (var m in subMesh_dict) {
  80762. materialMaxIndex = -1;
  80763. for (var sm in subMesh_dict[m]) {
  80764. subMesh_obj = subMesh_dict[m][sm];
  80765. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  80766. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  80767. }
  80768. materialIndexOffset += ++materialMaxIndex;
  80769. }
  80770. }
  80771. return mesh;
  80772. };
  80773. // Build Mesh from CSG taking material and transforms into account
  80774. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  80775. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  80776. mesh.material = material;
  80777. mesh.position.copyFrom(this.position);
  80778. mesh.rotation.copyFrom(this.rotation);
  80779. if (this.rotationQuaternion) {
  80780. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  80781. }
  80782. mesh.scaling.copyFrom(this.scaling);
  80783. mesh.computeWorldMatrix(true);
  80784. return mesh;
  80785. };
  80786. return CSG;
  80787. }());
  80788. BABYLON.CSG = CSG;
  80789. })(BABYLON || (BABYLON = {}));
  80790. //# sourceMappingURL=babylon.csg.js.map
  80791. var BABYLON;
  80792. (function (BABYLON) {
  80793. var LensFlare = /** @class */ (function () {
  80794. function LensFlare(size, position, color, imgUrl, system) {
  80795. this.size = size;
  80796. this.position = position;
  80797. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  80798. this.color = color || new BABYLON.Color3(1, 1, 1);
  80799. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  80800. this._system = system;
  80801. system.lensFlares.push(this);
  80802. }
  80803. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  80804. return new LensFlare(size, position, color, imgUrl, system);
  80805. };
  80806. LensFlare.prototype.dispose = function () {
  80807. if (this.texture) {
  80808. this.texture.dispose();
  80809. }
  80810. // Remove from scene
  80811. var index = this._system.lensFlares.indexOf(this);
  80812. this._system.lensFlares.splice(index, 1);
  80813. };
  80814. ;
  80815. return LensFlare;
  80816. }());
  80817. BABYLON.LensFlare = LensFlare;
  80818. })(BABYLON || (BABYLON = {}));
  80819. //# sourceMappingURL=babylon.lensFlare.js.map
  80820. var BABYLON;
  80821. (function (BABYLON) {
  80822. var LensFlareSystem = /** @class */ (function () {
  80823. function LensFlareSystem(name, emitter, scene) {
  80824. this.name = name;
  80825. this.lensFlares = new Array();
  80826. this.borderLimit = 300;
  80827. this.viewportBorder = 0;
  80828. this.layerMask = 0x0FFFFFFF;
  80829. this._vertexBuffers = {};
  80830. this._isEnabled = true;
  80831. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80832. this._emitter = emitter;
  80833. this.id = name;
  80834. scene.lensFlareSystems.push(this);
  80835. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  80836. var engine = scene.getEngine();
  80837. // VBO
  80838. var vertices = [];
  80839. vertices.push(1, 1);
  80840. vertices.push(-1, 1);
  80841. vertices.push(-1, -1);
  80842. vertices.push(1, -1);
  80843. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  80844. // Indices
  80845. var indices = [];
  80846. indices.push(0);
  80847. indices.push(1);
  80848. indices.push(2);
  80849. indices.push(0);
  80850. indices.push(2);
  80851. indices.push(3);
  80852. this._indexBuffer = engine.createIndexBuffer(indices);
  80853. // Effects
  80854. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  80855. }
  80856. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  80857. get: function () {
  80858. return this._isEnabled;
  80859. },
  80860. set: function (value) {
  80861. this._isEnabled = value;
  80862. },
  80863. enumerable: true,
  80864. configurable: true
  80865. });
  80866. LensFlareSystem.prototype.getScene = function () {
  80867. return this._scene;
  80868. };
  80869. LensFlareSystem.prototype.getEmitter = function () {
  80870. return this._emitter;
  80871. };
  80872. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  80873. this._emitter = newEmitter;
  80874. };
  80875. LensFlareSystem.prototype.getEmitterPosition = function () {
  80876. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  80877. };
  80878. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  80879. var position = this.getEmitterPosition();
  80880. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  80881. this._positionX = position.x;
  80882. this._positionY = position.y;
  80883. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  80884. if (this.viewportBorder > 0) {
  80885. globalViewport.x -= this.viewportBorder;
  80886. globalViewport.y -= this.viewportBorder;
  80887. globalViewport.width += this.viewportBorder * 2;
  80888. globalViewport.height += this.viewportBorder * 2;
  80889. position.x += this.viewportBorder;
  80890. position.y += this.viewportBorder;
  80891. this._positionX += this.viewportBorder;
  80892. this._positionY += this.viewportBorder;
  80893. }
  80894. if (position.z > 0) {
  80895. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  80896. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  80897. return true;
  80898. }
  80899. return true;
  80900. }
  80901. return false;
  80902. };
  80903. LensFlareSystem.prototype._isVisible = function () {
  80904. if (!this._isEnabled || !this._scene.activeCamera) {
  80905. return false;
  80906. }
  80907. var emitterPosition = this.getEmitterPosition();
  80908. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  80909. var distance = direction.length();
  80910. direction.normalize();
  80911. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  80912. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  80913. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  80914. };
  80915. LensFlareSystem.prototype.render = function () {
  80916. if (!this._effect.isReady() || !this._scene.activeCamera)
  80917. return false;
  80918. var engine = this._scene.getEngine();
  80919. var viewport = this._scene.activeCamera.viewport;
  80920. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  80921. // Position
  80922. if (!this.computeEffectivePosition(globalViewport)) {
  80923. return false;
  80924. }
  80925. // Visibility
  80926. if (!this._isVisible()) {
  80927. return false;
  80928. }
  80929. // Intensity
  80930. var awayX;
  80931. var awayY;
  80932. if (this._positionX < this.borderLimit + globalViewport.x) {
  80933. awayX = this.borderLimit + globalViewport.x - this._positionX;
  80934. }
  80935. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  80936. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  80937. }
  80938. else {
  80939. awayX = 0;
  80940. }
  80941. if (this._positionY < this.borderLimit + globalViewport.y) {
  80942. awayY = this.borderLimit + globalViewport.y - this._positionY;
  80943. }
  80944. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  80945. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  80946. }
  80947. else {
  80948. awayY = 0;
  80949. }
  80950. var away = (awayX > awayY) ? awayX : awayY;
  80951. away -= this.viewportBorder;
  80952. if (away > this.borderLimit) {
  80953. away = this.borderLimit;
  80954. }
  80955. var intensity = 1.0 - (away / this.borderLimit);
  80956. if (intensity < 0) {
  80957. return false;
  80958. }
  80959. if (intensity > 1.0) {
  80960. intensity = 1.0;
  80961. }
  80962. if (this.viewportBorder > 0) {
  80963. globalViewport.x += this.viewportBorder;
  80964. globalViewport.y += this.viewportBorder;
  80965. globalViewport.width -= this.viewportBorder * 2;
  80966. globalViewport.height -= this.viewportBorder * 2;
  80967. this._positionX -= this.viewportBorder;
  80968. this._positionY -= this.viewportBorder;
  80969. }
  80970. // Position
  80971. var centerX = globalViewport.x + globalViewport.width / 2;
  80972. var centerY = globalViewport.y + globalViewport.height / 2;
  80973. var distX = centerX - this._positionX;
  80974. var distY = centerY - this._positionY;
  80975. // Effects
  80976. engine.enableEffect(this._effect);
  80977. engine.setState(false);
  80978. engine.setDepthBuffer(false);
  80979. // VBOs
  80980. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  80981. // Flares
  80982. for (var index = 0; index < this.lensFlares.length; index++) {
  80983. var flare = this.lensFlares[index];
  80984. engine.setAlphaMode(flare.alphaMode);
  80985. var x = centerX - (distX * flare.position);
  80986. var y = centerY - (distY * flare.position);
  80987. var cw = flare.size;
  80988. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  80989. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  80990. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  80991. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  80992. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  80993. // Texture
  80994. this._effect.setTexture("textureSampler", flare.texture);
  80995. // Color
  80996. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  80997. // Draw order
  80998. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  80999. }
  81000. engine.setDepthBuffer(true);
  81001. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81002. return true;
  81003. };
  81004. LensFlareSystem.prototype.dispose = function () {
  81005. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81006. if (vertexBuffer) {
  81007. vertexBuffer.dispose();
  81008. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81009. }
  81010. if (this._indexBuffer) {
  81011. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81012. this._indexBuffer = null;
  81013. }
  81014. while (this.lensFlares.length) {
  81015. this.lensFlares[0].dispose();
  81016. }
  81017. // Remove from scene
  81018. var index = this._scene.lensFlareSystems.indexOf(this);
  81019. this._scene.lensFlareSystems.splice(index, 1);
  81020. };
  81021. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81022. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81023. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81024. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81025. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81026. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81027. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81028. var parsedFlare = parsedLensFlareSystem.flares[index];
  81029. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81030. }
  81031. return lensFlareSystem;
  81032. };
  81033. LensFlareSystem.prototype.serialize = function () {
  81034. var serializationObject = {};
  81035. serializationObject.id = this.id;
  81036. serializationObject.name = this.name;
  81037. serializationObject.emitterId = this.getEmitter().id;
  81038. serializationObject.borderLimit = this.borderLimit;
  81039. serializationObject.flares = [];
  81040. for (var index = 0; index < this.lensFlares.length; index++) {
  81041. var flare = this.lensFlares[index];
  81042. serializationObject.flares.push({
  81043. size: flare.size,
  81044. position: flare.position,
  81045. color: flare.color.asArray(),
  81046. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81047. });
  81048. }
  81049. return serializationObject;
  81050. };
  81051. return LensFlareSystem;
  81052. }());
  81053. BABYLON.LensFlareSystem = LensFlareSystem;
  81054. })(BABYLON || (BABYLON = {}));
  81055. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81056. var BABYLON;
  81057. (function (BABYLON) {
  81058. /**
  81059. * This is a holder class for the physics joint created by the physics plugin.
  81060. * It holds a set of functions to control the underlying joint.
  81061. */
  81062. var PhysicsJoint = /** @class */ (function () {
  81063. function PhysicsJoint(type, jointData) {
  81064. this.type = type;
  81065. this.jointData = jointData;
  81066. jointData.nativeParams = jointData.nativeParams || {};
  81067. }
  81068. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81069. get: function () {
  81070. return this._physicsJoint;
  81071. },
  81072. set: function (newJoint) {
  81073. if (this._physicsJoint) {
  81074. //remove from the wolrd
  81075. }
  81076. this._physicsJoint = newJoint;
  81077. },
  81078. enumerable: true,
  81079. configurable: true
  81080. });
  81081. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81082. set: function (physicsPlugin) {
  81083. this._physicsPlugin = physicsPlugin;
  81084. },
  81085. enumerable: true,
  81086. configurable: true
  81087. });
  81088. /**
  81089. * Execute a function that is physics-plugin specific.
  81090. * @param {Function} func the function that will be executed.
  81091. * It accepts two parameters: the physics world and the physics joint.
  81092. */
  81093. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81094. func(this._physicsPlugin.world, this._physicsJoint);
  81095. };
  81096. //TODO check if the native joints are the same
  81097. //Joint Types
  81098. PhysicsJoint.DistanceJoint = 0;
  81099. PhysicsJoint.HingeJoint = 1;
  81100. PhysicsJoint.BallAndSocketJoint = 2;
  81101. PhysicsJoint.WheelJoint = 3;
  81102. PhysicsJoint.SliderJoint = 4;
  81103. //OIMO
  81104. PhysicsJoint.PrismaticJoint = 5;
  81105. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81106. PhysicsJoint.UniversalJoint = 6;
  81107. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81108. //Cannon
  81109. //Similar to a Ball-Joint. Different in params
  81110. PhysicsJoint.PointToPointJoint = 8;
  81111. //Cannon only at the moment
  81112. PhysicsJoint.SpringJoint = 9;
  81113. PhysicsJoint.LockJoint = 10;
  81114. return PhysicsJoint;
  81115. }());
  81116. BABYLON.PhysicsJoint = PhysicsJoint;
  81117. /**
  81118. * A class representing a physics distance joint.
  81119. */
  81120. var DistanceJoint = /** @class */ (function (_super) {
  81121. __extends(DistanceJoint, _super);
  81122. function DistanceJoint(jointData) {
  81123. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81124. }
  81125. /**
  81126. * Update the predefined distance.
  81127. */
  81128. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81129. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81130. };
  81131. return DistanceJoint;
  81132. }(PhysicsJoint));
  81133. BABYLON.DistanceJoint = DistanceJoint;
  81134. var MotorEnabledJoint = /** @class */ (function (_super) {
  81135. __extends(MotorEnabledJoint, _super);
  81136. function MotorEnabledJoint(type, jointData) {
  81137. return _super.call(this, type, jointData) || this;
  81138. }
  81139. /**
  81140. * Set the motor values.
  81141. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81142. * @param {number} force the force to apply
  81143. * @param {number} maxForce max force for this motor.
  81144. */
  81145. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81146. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81147. };
  81148. /**
  81149. * Set the motor's limits.
  81150. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81151. */
  81152. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81153. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81154. };
  81155. return MotorEnabledJoint;
  81156. }(PhysicsJoint));
  81157. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81158. /**
  81159. * This class represents a single hinge physics joint
  81160. */
  81161. var HingeJoint = /** @class */ (function (_super) {
  81162. __extends(HingeJoint, _super);
  81163. function HingeJoint(jointData) {
  81164. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81165. }
  81166. /**
  81167. * Set the motor values.
  81168. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81169. * @param {number} force the force to apply
  81170. * @param {number} maxForce max force for this motor.
  81171. */
  81172. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81173. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81174. };
  81175. /**
  81176. * Set the motor's limits.
  81177. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81178. */
  81179. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81180. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81181. };
  81182. return HingeJoint;
  81183. }(MotorEnabledJoint));
  81184. BABYLON.HingeJoint = HingeJoint;
  81185. /**
  81186. * This class represents a dual hinge physics joint (same as wheel joint)
  81187. */
  81188. var Hinge2Joint = /** @class */ (function (_super) {
  81189. __extends(Hinge2Joint, _super);
  81190. function Hinge2Joint(jointData) {
  81191. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81192. }
  81193. /**
  81194. * Set the motor values.
  81195. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81196. * @param {number} force the force to apply
  81197. * @param {number} maxForce max force for this motor.
  81198. * @param {motorIndex} the motor's index, 0 or 1.
  81199. */
  81200. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81201. if (motorIndex === void 0) { motorIndex = 0; }
  81202. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81203. };
  81204. /**
  81205. * Set the motor limits.
  81206. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81207. * @param {number} upperLimit the upper limit
  81208. * @param {number} lowerLimit lower limit
  81209. * @param {motorIndex} the motor's index, 0 or 1.
  81210. */
  81211. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81212. if (motorIndex === void 0) { motorIndex = 0; }
  81213. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81214. };
  81215. return Hinge2Joint;
  81216. }(MotorEnabledJoint));
  81217. BABYLON.Hinge2Joint = Hinge2Joint;
  81218. })(BABYLON || (BABYLON = {}));
  81219. //# sourceMappingURL=babylon.physicsJoint.js.map
  81220. var BABYLON;
  81221. (function (BABYLON) {
  81222. var PhysicsImpostor = /** @class */ (function () {
  81223. function PhysicsImpostor(object, type, _options, _scene) {
  81224. if (_options === void 0) { _options = { mass: 0 }; }
  81225. var _this = this;
  81226. this.object = object;
  81227. this.type = type;
  81228. this._options = _options;
  81229. this._scene = _scene;
  81230. this._bodyUpdateRequired = false;
  81231. this._onBeforePhysicsStepCallbacks = new Array();
  81232. this._onAfterPhysicsStepCallbacks = new Array();
  81233. this._onPhysicsCollideCallbacks = [];
  81234. this._deltaPosition = BABYLON.Vector3.Zero();
  81235. this._isDisposed = false;
  81236. //temp variables for parent rotation calculations
  81237. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81238. this._tmpQuat = new BABYLON.Quaternion();
  81239. this._tmpQuat2 = new BABYLON.Quaternion();
  81240. /**
  81241. * this function is executed by the physics engine.
  81242. */
  81243. this.beforeStep = function () {
  81244. if (!_this._physicsEngine) {
  81245. return;
  81246. }
  81247. _this.object.translate(_this._deltaPosition, -1);
  81248. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81249. _this.object.computeWorldMatrix(false);
  81250. if (_this.object.parent && _this.object.rotationQuaternion) {
  81251. _this.getParentsRotation();
  81252. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81253. }
  81254. else {
  81255. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81256. }
  81257. if (!_this._options.disableBidirectionalTransformation) {
  81258. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81259. }
  81260. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81261. func(_this);
  81262. });
  81263. };
  81264. /**
  81265. * this function is executed by the physics engine.
  81266. */
  81267. this.afterStep = function () {
  81268. if (!_this._physicsEngine) {
  81269. return;
  81270. }
  81271. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81272. func(_this);
  81273. });
  81274. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81275. // object has now its world rotation. needs to be converted to local.
  81276. if (_this.object.parent && _this.object.rotationQuaternion) {
  81277. _this.getParentsRotation();
  81278. _this._tmpQuat.conjugateInPlace();
  81279. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81280. }
  81281. // take the position set and make it the absolute position of this object.
  81282. _this.object.setAbsolutePosition(_this.object.position);
  81283. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81284. _this.object.translate(_this._deltaPosition, 1);
  81285. };
  81286. /**
  81287. * Legacy collision detection event support
  81288. */
  81289. this.onCollideEvent = null;
  81290. //event and body object due to cannon's event-based architecture.
  81291. this.onCollide = function (e) {
  81292. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81293. return;
  81294. }
  81295. if (!_this._physicsEngine) {
  81296. return;
  81297. }
  81298. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81299. if (otherImpostor) {
  81300. // Legacy collision detection event support
  81301. if (_this.onCollideEvent) {
  81302. _this.onCollideEvent(_this, otherImpostor);
  81303. }
  81304. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81305. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81306. }).forEach(function (obj) {
  81307. obj.callback(_this, otherImpostor);
  81308. });
  81309. }
  81310. };
  81311. //sanity check!
  81312. if (!this.object) {
  81313. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81314. return;
  81315. }
  81316. //legacy support for old syntax.
  81317. if (!this._scene && object.getScene) {
  81318. this._scene = object.getScene();
  81319. }
  81320. if (!this._scene) {
  81321. return;
  81322. }
  81323. this._physicsEngine = this._scene.getPhysicsEngine();
  81324. if (!this._physicsEngine) {
  81325. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81326. }
  81327. else {
  81328. //set the object's quaternion, if not set
  81329. if (!this.object.rotationQuaternion) {
  81330. if (this.object.rotation) {
  81331. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81332. }
  81333. else {
  81334. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81335. }
  81336. }
  81337. //default options params
  81338. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81339. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81340. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81341. this._joints = [];
  81342. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81343. if (!this.object.parent || this._options.ignoreParent) {
  81344. this._init();
  81345. }
  81346. else if (this.object.parent.physicsImpostor) {
  81347. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81348. }
  81349. }
  81350. }
  81351. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81352. get: function () {
  81353. return this._isDisposed;
  81354. },
  81355. enumerable: true,
  81356. configurable: true
  81357. });
  81358. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81359. get: function () {
  81360. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81361. },
  81362. set: function (value) {
  81363. this.setMass(value);
  81364. },
  81365. enumerable: true,
  81366. configurable: true
  81367. });
  81368. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81369. get: function () {
  81370. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81371. },
  81372. set: function (value) {
  81373. if (!this._physicsEngine) {
  81374. return;
  81375. }
  81376. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81377. },
  81378. enumerable: true,
  81379. configurable: true
  81380. });
  81381. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81382. get: function () {
  81383. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81384. },
  81385. set: function (value) {
  81386. if (!this._physicsEngine) {
  81387. return;
  81388. }
  81389. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81390. },
  81391. enumerable: true,
  81392. configurable: true
  81393. });
  81394. /**
  81395. * This function will completly initialize this impostor.
  81396. * It will create a new body - but only if this mesh has no parent.
  81397. * If it has, this impostor will not be used other than to define the impostor
  81398. * of the child mesh.
  81399. */
  81400. PhysicsImpostor.prototype._init = function () {
  81401. if (!this._physicsEngine) {
  81402. return;
  81403. }
  81404. this._physicsEngine.removeImpostor(this);
  81405. this.physicsBody = null;
  81406. this._parent = this._parent || this._getPhysicsParent();
  81407. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81408. this._physicsEngine.addImpostor(this);
  81409. }
  81410. };
  81411. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81412. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81413. var parentMesh = this.object.parent;
  81414. return parentMesh.physicsImpostor;
  81415. }
  81416. return null;
  81417. };
  81418. /**
  81419. * Should a new body be generated.
  81420. */
  81421. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81422. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81423. };
  81424. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81425. this.forceUpdate();
  81426. };
  81427. /**
  81428. * Force a regeneration of this or the parent's impostor's body.
  81429. * Use under cautious - This will remove all joints already implemented.
  81430. */
  81431. PhysicsImpostor.prototype.forceUpdate = function () {
  81432. this._init();
  81433. if (this.parent && !this._options.ignoreParent) {
  81434. this.parent.forceUpdate();
  81435. }
  81436. };
  81437. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81438. /*public get mesh(): AbstractMesh {
  81439. return this._mesh;
  81440. }*/
  81441. /**
  81442. * Gets the body that holds this impostor. Either its own, or its parent.
  81443. */
  81444. get: function () {
  81445. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81446. },
  81447. /**
  81448. * Set the physics body. Used mainly by the physics engine/plugin
  81449. */
  81450. set: function (physicsBody) {
  81451. if (this._physicsBody && this._physicsEngine) {
  81452. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81453. }
  81454. this._physicsBody = physicsBody;
  81455. this.resetUpdateFlags();
  81456. },
  81457. enumerable: true,
  81458. configurable: true
  81459. });
  81460. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81461. get: function () {
  81462. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81463. },
  81464. set: function (value) {
  81465. this._parent = value;
  81466. },
  81467. enumerable: true,
  81468. configurable: true
  81469. });
  81470. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81471. this._bodyUpdateRequired = false;
  81472. };
  81473. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81474. if (this.object.getBoundingInfo) {
  81475. var q = this.object.rotationQuaternion;
  81476. //reset rotation
  81477. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81478. //calculate the world matrix with no rotation
  81479. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81480. var boundingInfo = this.object.getBoundingInfo();
  81481. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81482. //bring back the rotation
  81483. this.object.rotationQuaternion = q;
  81484. //calculate the world matrix with the new rotation
  81485. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81486. return size;
  81487. }
  81488. else {
  81489. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81490. }
  81491. };
  81492. PhysicsImpostor.prototype.getObjectCenter = function () {
  81493. if (this.object.getBoundingInfo) {
  81494. var boundingInfo = this.object.getBoundingInfo();
  81495. return boundingInfo.boundingBox.centerWorld;
  81496. }
  81497. else {
  81498. return this.object.position;
  81499. }
  81500. };
  81501. /**
  81502. * Get a specific parametes from the options parameter.
  81503. */
  81504. PhysicsImpostor.prototype.getParam = function (paramName) {
  81505. return this._options[paramName];
  81506. };
  81507. /**
  81508. * Sets a specific parameter in the options given to the physics plugin
  81509. */
  81510. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81511. this._options[paramName] = value;
  81512. this._bodyUpdateRequired = true;
  81513. };
  81514. /**
  81515. * Specifically change the body's mass option. Won't recreate the physics body object
  81516. */
  81517. PhysicsImpostor.prototype.setMass = function (mass) {
  81518. if (this.getParam("mass") !== mass) {
  81519. this.setParam("mass", mass);
  81520. }
  81521. if (this._physicsEngine) {
  81522. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81523. }
  81524. };
  81525. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81526. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81527. };
  81528. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81529. if (this._physicsEngine) {
  81530. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81531. }
  81532. };
  81533. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81534. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81535. };
  81536. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81537. if (this._physicsEngine) {
  81538. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81539. }
  81540. };
  81541. /**
  81542. * Execute a function with the physics plugin native code.
  81543. * Provide a function the will have two variables - the world object and the physics body object.
  81544. */
  81545. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81546. if (this._physicsEngine) {
  81547. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81548. }
  81549. };
  81550. /**
  81551. * Register a function that will be executed before the physics world is stepping forward.
  81552. */
  81553. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81554. this._onBeforePhysicsStepCallbacks.push(func);
  81555. };
  81556. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81557. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81558. if (index > -1) {
  81559. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81560. }
  81561. else {
  81562. BABYLON.Tools.Warn("Function to remove was not found");
  81563. }
  81564. };
  81565. /**
  81566. * Register a function that will be executed after the physics step
  81567. */
  81568. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81569. this._onAfterPhysicsStepCallbacks.push(func);
  81570. };
  81571. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81572. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81573. if (index > -1) {
  81574. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81575. }
  81576. else {
  81577. BABYLON.Tools.Warn("Function to remove was not found");
  81578. }
  81579. };
  81580. /**
  81581. * register a function that will be executed when this impostor collides against a different body.
  81582. */
  81583. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81584. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81585. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81586. };
  81587. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81588. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81589. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81590. if (index > -1) {
  81591. this._onPhysicsCollideCallbacks.splice(index, 1);
  81592. }
  81593. else {
  81594. BABYLON.Tools.Warn("Function to remove was not found");
  81595. }
  81596. };
  81597. PhysicsImpostor.prototype.getParentsRotation = function () {
  81598. var parent = this.object.parent;
  81599. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81600. while (parent) {
  81601. if (parent.rotationQuaternion) {
  81602. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81603. }
  81604. else {
  81605. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81606. }
  81607. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81608. parent = parent.parent;
  81609. }
  81610. return this._tmpQuat;
  81611. };
  81612. /**
  81613. * Apply a force
  81614. */
  81615. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81616. if (this._physicsEngine) {
  81617. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81618. }
  81619. return this;
  81620. };
  81621. /**
  81622. * Apply an impulse
  81623. */
  81624. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81625. if (this._physicsEngine) {
  81626. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81627. }
  81628. return this;
  81629. };
  81630. /**
  81631. * A help function to create a joint.
  81632. */
  81633. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81634. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81635. this.addJoint(otherImpostor, joint);
  81636. return this;
  81637. };
  81638. /**
  81639. * Add a joint to this impostor with a different impostor.
  81640. */
  81641. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81642. this._joints.push({
  81643. otherImpostor: otherImpostor,
  81644. joint: joint
  81645. });
  81646. if (this._physicsEngine) {
  81647. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81648. }
  81649. return this;
  81650. };
  81651. /**
  81652. * Will keep this body still, in a sleep mode.
  81653. */
  81654. PhysicsImpostor.prototype.sleep = function () {
  81655. if (this._physicsEngine) {
  81656. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81657. }
  81658. return this;
  81659. };
  81660. /**
  81661. * Wake the body up.
  81662. */
  81663. PhysicsImpostor.prototype.wakeUp = function () {
  81664. if (this._physicsEngine) {
  81665. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  81666. }
  81667. return this;
  81668. };
  81669. PhysicsImpostor.prototype.clone = function (newObject) {
  81670. if (!newObject)
  81671. return null;
  81672. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  81673. };
  81674. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  81675. var _this = this;
  81676. //no dispose if no physics engine is available.
  81677. if (!this._physicsEngine) {
  81678. return;
  81679. }
  81680. this._joints.forEach(function (j) {
  81681. if (_this._physicsEngine) {
  81682. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  81683. }
  81684. });
  81685. //dispose the physics body
  81686. this._physicsEngine.removeImpostor(this);
  81687. if (this.parent) {
  81688. this.parent.forceUpdate();
  81689. }
  81690. else {
  81691. /*this._object.getChildMeshes().forEach(function(mesh) {
  81692. if (mesh.physicsImpostor) {
  81693. if (disposeChildren) {
  81694. mesh.physicsImpostor.dispose();
  81695. mesh.physicsImpostor = null;
  81696. }
  81697. }
  81698. })*/
  81699. }
  81700. this._isDisposed = true;
  81701. };
  81702. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  81703. this._deltaPosition.copyFrom(position);
  81704. };
  81705. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  81706. if (!this._deltaRotation) {
  81707. this._deltaRotation = new BABYLON.Quaternion();
  81708. }
  81709. this._deltaRotation.copyFrom(rotation);
  81710. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  81711. };
  81712. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  81713. if (this._physicsEngine) {
  81714. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  81715. }
  81716. return this;
  81717. };
  81718. PhysicsImpostor.prototype.getRadius = function () {
  81719. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  81720. };
  81721. /**
  81722. * Sync a bone with this impostor
  81723. * @param bone The bone to sync to the impostor.
  81724. * @param boneMesh The mesh that the bone is influencing.
  81725. * @param jointPivot The pivot of the joint / bone in local space.
  81726. * @param distToJoint Optional distance from the impostor to the joint.
  81727. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81728. */
  81729. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  81730. var tempVec = PhysicsImpostor._tmpVecs[0];
  81731. var mesh = this.object;
  81732. if (mesh.rotationQuaternion) {
  81733. if (adjustRotation) {
  81734. var tempQuat = PhysicsImpostor._tmpQuat;
  81735. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  81736. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  81737. }
  81738. else {
  81739. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  81740. }
  81741. }
  81742. tempVec.x = 0;
  81743. tempVec.y = 0;
  81744. tempVec.z = 0;
  81745. if (jointPivot) {
  81746. tempVec.x = jointPivot.x;
  81747. tempVec.y = jointPivot.y;
  81748. tempVec.z = jointPivot.z;
  81749. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  81750. if (distToJoint === undefined || distToJoint === null) {
  81751. distToJoint = jointPivot.length();
  81752. }
  81753. tempVec.x *= distToJoint;
  81754. tempVec.y *= distToJoint;
  81755. tempVec.z *= distToJoint;
  81756. }
  81757. if (bone.getParent()) {
  81758. tempVec.addInPlace(mesh.getAbsolutePosition());
  81759. bone.setAbsolutePosition(tempVec, boneMesh);
  81760. }
  81761. else {
  81762. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  81763. boneMesh.position.x -= tempVec.x;
  81764. boneMesh.position.y -= tempVec.y;
  81765. boneMesh.position.z -= tempVec.z;
  81766. }
  81767. };
  81768. /**
  81769. * Sync impostor to a bone
  81770. * @param bone The bone that the impostor will be synced to.
  81771. * @param boneMesh The mesh that the bone is influencing.
  81772. * @param jointPivot The pivot of the joint / bone in local space.
  81773. * @param distToJoint Optional distance from the impostor to the joint.
  81774. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  81775. * @param boneAxis Optional vector3 axis the bone is aligned with
  81776. */
  81777. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  81778. var mesh = this.object;
  81779. if (mesh.rotationQuaternion) {
  81780. if (adjustRotation) {
  81781. var tempQuat = PhysicsImpostor._tmpQuat;
  81782. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  81783. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  81784. }
  81785. else {
  81786. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  81787. }
  81788. }
  81789. var pos = PhysicsImpostor._tmpVecs[0];
  81790. var boneDir = PhysicsImpostor._tmpVecs[1];
  81791. if (!boneAxis) {
  81792. boneAxis = PhysicsImpostor._tmpVecs[2];
  81793. boneAxis.x = 0;
  81794. boneAxis.y = 1;
  81795. boneAxis.z = 0;
  81796. }
  81797. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  81798. bone.getAbsolutePositionToRef(boneMesh, pos);
  81799. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  81800. distToJoint = jointPivot.length();
  81801. }
  81802. if (distToJoint !== undefined && distToJoint !== null) {
  81803. pos.x += boneDir.x * distToJoint;
  81804. pos.y += boneDir.y * distToJoint;
  81805. pos.z += boneDir.z * distToJoint;
  81806. }
  81807. mesh.setAbsolutePosition(pos);
  81808. };
  81809. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  81810. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  81811. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  81812. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  81813. //Impostor types
  81814. PhysicsImpostor.NoImpostor = 0;
  81815. PhysicsImpostor.SphereImpostor = 1;
  81816. PhysicsImpostor.BoxImpostor = 2;
  81817. PhysicsImpostor.PlaneImpostor = 3;
  81818. PhysicsImpostor.MeshImpostor = 4;
  81819. PhysicsImpostor.CylinderImpostor = 7;
  81820. PhysicsImpostor.ParticleImpostor = 8;
  81821. PhysicsImpostor.HeightmapImpostor = 9;
  81822. return PhysicsImpostor;
  81823. }());
  81824. BABYLON.PhysicsImpostor = PhysicsImpostor;
  81825. })(BABYLON || (BABYLON = {}));
  81826. //# sourceMappingURL=babylon.physicsImpostor.js.map
  81827. var BABYLON;
  81828. (function (BABYLON) {
  81829. var PhysicsEngine = /** @class */ (function () {
  81830. function PhysicsEngine(gravity, _physicsPlugin) {
  81831. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  81832. this._physicsPlugin = _physicsPlugin;
  81833. //new methods and parameters
  81834. this._impostors = [];
  81835. this._joints = [];
  81836. if (!this._physicsPlugin.isSupported()) {
  81837. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  81838. + "Please make sure it is included.");
  81839. }
  81840. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  81841. this.setGravity(gravity);
  81842. this.setTimeStep();
  81843. }
  81844. PhysicsEngine.prototype.setGravity = function (gravity) {
  81845. this.gravity = gravity;
  81846. this._physicsPlugin.setGravity(this.gravity);
  81847. };
  81848. /**
  81849. * Set the time step of the physics engine.
  81850. * default is 1/60.
  81851. * To slow it down, enter 1/600 for example.
  81852. * To speed it up, 1/30
  81853. * @param {number} newTimeStep the new timestep to apply to this world.
  81854. */
  81855. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  81856. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  81857. this._physicsPlugin.setTimeStep(newTimeStep);
  81858. };
  81859. /**
  81860. * Get the time step of the physics engine.
  81861. */
  81862. PhysicsEngine.prototype.getTimeStep = function () {
  81863. return this._physicsPlugin.getTimeStep();
  81864. };
  81865. PhysicsEngine.prototype.dispose = function () {
  81866. this._impostors.forEach(function (impostor) {
  81867. impostor.dispose();
  81868. });
  81869. this._physicsPlugin.dispose();
  81870. };
  81871. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  81872. return this._physicsPlugin.name;
  81873. };
  81874. /**
  81875. * Adding a new impostor for the impostor tracking.
  81876. * This will be done by the impostor itself.
  81877. * @param {PhysicsImpostor} impostor the impostor to add
  81878. */
  81879. PhysicsEngine.prototype.addImpostor = function (impostor) {
  81880. impostor.uniqueId = this._impostors.push(impostor);
  81881. //if no parent, generate the body
  81882. if (!impostor.parent) {
  81883. this._physicsPlugin.generatePhysicsBody(impostor);
  81884. }
  81885. };
  81886. /**
  81887. * Remove an impostor from the engine.
  81888. * This impostor and its mesh will not longer be updated by the physics engine.
  81889. * @param {PhysicsImpostor} impostor the impostor to remove
  81890. */
  81891. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  81892. var index = this._impostors.indexOf(impostor);
  81893. if (index > -1) {
  81894. var removed = this._impostors.splice(index, 1);
  81895. //Is it needed?
  81896. if (removed.length) {
  81897. //this will also remove it from the world.
  81898. removed[0].physicsBody = null;
  81899. }
  81900. }
  81901. };
  81902. /**
  81903. * Add a joint to the physics engine
  81904. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  81905. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  81906. * @param {PhysicsJoint} the joint that will connect both impostors.
  81907. */
  81908. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  81909. var impostorJoint = {
  81910. mainImpostor: mainImpostor,
  81911. connectedImpostor: connectedImpostor,
  81912. joint: joint
  81913. };
  81914. joint.physicsPlugin = this._physicsPlugin;
  81915. this._joints.push(impostorJoint);
  81916. this._physicsPlugin.generateJoint(impostorJoint);
  81917. };
  81918. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  81919. var matchingJoints = this._joints.filter(function (impostorJoint) {
  81920. return (impostorJoint.connectedImpostor === connectedImpostor
  81921. && impostorJoint.joint === joint
  81922. && impostorJoint.mainImpostor === mainImpostor);
  81923. });
  81924. if (matchingJoints.length) {
  81925. this._physicsPlugin.removeJoint(matchingJoints[0]);
  81926. //TODO remove it from the list as well
  81927. }
  81928. };
  81929. /**
  81930. * Called by the scene. no need to call it.
  81931. */
  81932. PhysicsEngine.prototype._step = function (delta) {
  81933. var _this = this;
  81934. //check if any mesh has no body / requires an update
  81935. this._impostors.forEach(function (impostor) {
  81936. if (impostor.isBodyInitRequired()) {
  81937. _this._physicsPlugin.generatePhysicsBody(impostor);
  81938. }
  81939. });
  81940. if (delta > 0.1) {
  81941. delta = 0.1;
  81942. }
  81943. else if (delta <= 0) {
  81944. delta = 1.0 / 60.0;
  81945. }
  81946. this._physicsPlugin.executeStep(delta, this._impostors);
  81947. };
  81948. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  81949. return this._physicsPlugin;
  81950. };
  81951. PhysicsEngine.prototype.getImpostors = function () {
  81952. return this._impostors;
  81953. };
  81954. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  81955. for (var i = 0; i < this._impostors.length; ++i) {
  81956. if (this._impostors[i].object === object) {
  81957. return this._impostors[i];
  81958. }
  81959. }
  81960. return null;
  81961. };
  81962. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  81963. for (var i = 0; i < this._impostors.length; ++i) {
  81964. if (this._impostors[i].physicsBody === body) {
  81965. return this._impostors[i];
  81966. }
  81967. }
  81968. return null;
  81969. };
  81970. // Statics
  81971. PhysicsEngine.Epsilon = 0.001;
  81972. return PhysicsEngine;
  81973. }());
  81974. BABYLON.PhysicsEngine = PhysicsEngine;
  81975. })(BABYLON || (BABYLON = {}));
  81976. //# sourceMappingURL=babylon.physicsEngine.js.map
  81977. var BABYLON;
  81978. (function (BABYLON) {
  81979. var PhysicsHelper = /** @class */ (function () {
  81980. function PhysicsHelper(scene) {
  81981. this._scene = scene;
  81982. this._physicsEngine = this._scene.getPhysicsEngine();
  81983. if (!this._physicsEngine) {
  81984. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  81985. }
  81986. }
  81987. /**
  81988. * @param {Vector3} origin the origin of the explosion
  81989. * @param {number} radius the explosion radius
  81990. * @param {number} strength the explosion strength
  81991. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  81992. */
  81993. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  81994. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  81995. if (!this._physicsEngine) {
  81996. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  81997. return null;
  81998. }
  81999. var impostors = this._physicsEngine.getImpostors();
  82000. if (impostors.length === 0) {
  82001. return null;
  82002. }
  82003. var event = new PhysicsRadialExplosionEvent(this._scene);
  82004. impostors.forEach(function (impostor) {
  82005. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82006. if (!impostorForceAndContactPoint) {
  82007. return;
  82008. }
  82009. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82010. });
  82011. event.dispose(false);
  82012. return event;
  82013. };
  82014. /**
  82015. * @param {Vector3} origin the origin of the explosion
  82016. * @param {number} radius the explosion radius
  82017. * @param {number} strength the explosion strength
  82018. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82019. */
  82020. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82021. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82022. if (!this._physicsEngine) {
  82023. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82024. return null;
  82025. }
  82026. var impostors = this._physicsEngine.getImpostors();
  82027. if (impostors.length === 0) {
  82028. return null;
  82029. }
  82030. var event = new PhysicsRadialExplosionEvent(this._scene);
  82031. impostors.forEach(function (impostor) {
  82032. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82033. if (!impostorForceAndContactPoint) {
  82034. return;
  82035. }
  82036. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82037. });
  82038. event.dispose(false);
  82039. return event;
  82040. };
  82041. /**
  82042. * @param {Vector3} origin the origin of the explosion
  82043. * @param {number} radius the explosion radius
  82044. * @param {number} strength the explosion strength
  82045. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82046. */
  82047. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82048. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82049. if (!this._physicsEngine) {
  82050. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82051. return null;
  82052. }
  82053. var impostors = this._physicsEngine.getImpostors();
  82054. if (impostors.length === 0) {
  82055. return null;
  82056. }
  82057. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82058. event.dispose(false);
  82059. return event;
  82060. };
  82061. /**
  82062. * @param {Vector3} origin the origin of the updraft
  82063. * @param {number} radius the radius of the updraft
  82064. * @param {number} strength the strength of the updraft
  82065. * @param {number} height the height of the updraft
  82066. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82067. */
  82068. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82069. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82070. if (!this._physicsEngine) {
  82071. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82072. return null;
  82073. }
  82074. if (this._physicsEngine.getImpostors().length === 0) {
  82075. return null;
  82076. }
  82077. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82078. event.dispose(false);
  82079. return event;
  82080. };
  82081. /**
  82082. * @param {Vector3} origin the of the vortex
  82083. * @param {number} radius the radius of the vortex
  82084. * @param {number} strength the strength of the vortex
  82085. * @param {number} height the height of the vortex
  82086. */
  82087. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82088. if (!this._physicsEngine) {
  82089. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82090. return null;
  82091. }
  82092. if (this._physicsEngine.getImpostors().length === 0) {
  82093. return null;
  82094. }
  82095. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82096. event.dispose(false);
  82097. return event;
  82098. };
  82099. return PhysicsHelper;
  82100. }());
  82101. BABYLON.PhysicsHelper = PhysicsHelper;
  82102. /***** Radial explosion *****/
  82103. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82104. function PhysicsRadialExplosionEvent(scene) {
  82105. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82106. this._rays = [];
  82107. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82108. this._scene = scene;
  82109. }
  82110. /**
  82111. * Returns the data related to the radial explosion event (sphere & rays).
  82112. * @returns {PhysicsRadialExplosionEventData}
  82113. */
  82114. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82115. this._dataFetched = true;
  82116. return {
  82117. sphere: this._sphere,
  82118. rays: this._rays,
  82119. };
  82120. };
  82121. /**
  82122. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82123. * @param impostor
  82124. * @param {Vector3} origin the origin of the explosion
  82125. * @param {number} radius the explosion radius
  82126. * @param {number} strength the explosion strength
  82127. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82128. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82129. */
  82130. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82131. if (impostor.mass === 0) {
  82132. return null;
  82133. }
  82134. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82135. return null;
  82136. }
  82137. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82138. return null;
  82139. }
  82140. var impostorObjectCenter = impostor.getObjectCenter();
  82141. var direction = impostorObjectCenter.subtract(origin);
  82142. var ray = new BABYLON.Ray(origin, direction, radius);
  82143. this._rays.push(ray);
  82144. var hit = ray.intersectsMesh(impostor.object);
  82145. var contactPoint = hit.pickedPoint;
  82146. if (!contactPoint) {
  82147. return null;
  82148. }
  82149. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82150. if (distanceFromOrigin > radius) {
  82151. return null;
  82152. }
  82153. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82154. ? strength
  82155. : strength * (1 - (distanceFromOrigin / radius));
  82156. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82157. return { force: force, contactPoint: contactPoint };
  82158. };
  82159. /**
  82160. * Disposes the sphere.
  82161. * @param {bolean} force
  82162. */
  82163. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82164. var _this = this;
  82165. if (force === void 0) { force = true; }
  82166. if (force) {
  82167. this._sphere.dispose();
  82168. }
  82169. else {
  82170. setTimeout(function () {
  82171. if (!_this._dataFetched) {
  82172. _this._sphere.dispose();
  82173. }
  82174. }, 0);
  82175. }
  82176. };
  82177. /*** Helpers ***/
  82178. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82179. if (!this._sphere) {
  82180. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82181. this._sphere.isVisible = false;
  82182. }
  82183. };
  82184. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82185. var impostorObject = impostor.object;
  82186. this._prepareSphere();
  82187. this._sphere.position = origin;
  82188. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82189. this._sphere._updateBoundingInfo();
  82190. this._sphere.computeWorldMatrix(true);
  82191. return this._sphere.intersectsMesh(impostorObject, true);
  82192. };
  82193. return PhysicsRadialExplosionEvent;
  82194. }());
  82195. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82196. /***** Gravitational Field *****/
  82197. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82198. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82199. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82200. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82201. this._physicsHelper = physicsHelper;
  82202. this._scene = scene;
  82203. this._origin = origin;
  82204. this._radius = radius;
  82205. this._strength = strength;
  82206. this._falloff = falloff;
  82207. this._tickCallback = this._tick.bind(this);
  82208. }
  82209. /**
  82210. * Returns the data related to the gravitational field event (sphere).
  82211. * @returns {PhysicsGravitationalFieldEventData}
  82212. */
  82213. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82214. this._dataFetched = true;
  82215. return {
  82216. sphere: this._sphere,
  82217. };
  82218. };
  82219. /**
  82220. * Enables the gravitational field.
  82221. */
  82222. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82223. this._tickCallback.call(this);
  82224. this._scene.registerBeforeRender(this._tickCallback);
  82225. };
  82226. /**
  82227. * Disables the gravitational field.
  82228. */
  82229. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82230. this._scene.unregisterBeforeRender(this._tickCallback);
  82231. };
  82232. /**
  82233. * Disposes the sphere.
  82234. * @param {bolean} force
  82235. */
  82236. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82237. var _this = this;
  82238. if (force === void 0) { force = true; }
  82239. if (force) {
  82240. this._sphere.dispose();
  82241. }
  82242. else {
  82243. setTimeout(function () {
  82244. if (!_this._dataFetched) {
  82245. _this._sphere.dispose();
  82246. }
  82247. }, 0);
  82248. }
  82249. };
  82250. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82251. // Since the params won't change, we fetch the event only once
  82252. if (this._sphere) {
  82253. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82254. }
  82255. else {
  82256. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82257. if (radialExplosionEvent) {
  82258. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82259. }
  82260. }
  82261. };
  82262. return PhysicsGravitationalFieldEvent;
  82263. }());
  82264. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82265. /***** Updraft *****/
  82266. var PhysicsUpdraftEvent = /** @class */ (function () {
  82267. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82268. this._scene = _scene;
  82269. this._origin = _origin;
  82270. this._radius = _radius;
  82271. this._strength = _strength;
  82272. this._height = _height;
  82273. this._updraftMode = _updraftMode;
  82274. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82275. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82276. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82277. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82278. this._physicsEngine = this._scene.getPhysicsEngine();
  82279. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82280. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82281. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82282. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82283. }
  82284. this._tickCallback = this._tick.bind(this);
  82285. }
  82286. /**
  82287. * Returns the data related to the updraft event (cylinder).
  82288. * @returns {PhysicsUpdraftEventData}
  82289. */
  82290. PhysicsUpdraftEvent.prototype.getData = function () {
  82291. this._dataFetched = true;
  82292. return {
  82293. cylinder: this._cylinder,
  82294. };
  82295. };
  82296. /**
  82297. * Enables the updraft.
  82298. */
  82299. PhysicsUpdraftEvent.prototype.enable = function () {
  82300. this._tickCallback.call(this);
  82301. this._scene.registerBeforeRender(this._tickCallback);
  82302. };
  82303. /**
  82304. * Disables the cortex.
  82305. */
  82306. PhysicsUpdraftEvent.prototype.disable = function () {
  82307. this._scene.unregisterBeforeRender(this._tickCallback);
  82308. };
  82309. /**
  82310. * Disposes the sphere.
  82311. * @param {bolean} force
  82312. */
  82313. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82314. var _this = this;
  82315. if (force === void 0) { force = true; }
  82316. if (force) {
  82317. this._cylinder.dispose();
  82318. }
  82319. else {
  82320. setTimeout(function () {
  82321. if (!_this._dataFetched) {
  82322. _this._cylinder.dispose();
  82323. }
  82324. }, 0);
  82325. }
  82326. };
  82327. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82328. if (impostor.mass === 0) {
  82329. return null;
  82330. }
  82331. if (!this._intersectsWithCylinder(impostor)) {
  82332. return null;
  82333. }
  82334. var impostorObjectCenter = impostor.getObjectCenter();
  82335. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82336. var direction = this._originDirection;
  82337. }
  82338. else {
  82339. var direction = impostorObjectCenter.subtract(this._originTop);
  82340. }
  82341. var multiplier = this._strength * -1;
  82342. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82343. return { force: force, contactPoint: impostorObjectCenter };
  82344. };
  82345. PhysicsUpdraftEvent.prototype._tick = function () {
  82346. var _this = this;
  82347. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82348. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82349. if (!impostorForceAndContactPoint) {
  82350. return;
  82351. }
  82352. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82353. });
  82354. };
  82355. /*** Helpers ***/
  82356. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82357. if (!this._cylinder) {
  82358. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82359. height: this._height,
  82360. diameter: this._radius * 2,
  82361. }, this._scene);
  82362. this._cylinder.isVisible = false;
  82363. }
  82364. };
  82365. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82366. var impostorObject = impostor.object;
  82367. this._prepareCylinder();
  82368. this._cylinder.position = this._cylinderPosition;
  82369. return this._cylinder.intersectsMesh(impostorObject, true);
  82370. };
  82371. return PhysicsUpdraftEvent;
  82372. }());
  82373. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82374. /***** Vortex *****/
  82375. var PhysicsVortexEvent = /** @class */ (function () {
  82376. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82377. this._scene = _scene;
  82378. this._origin = _origin;
  82379. this._radius = _radius;
  82380. this._strength = _strength;
  82381. this._height = _height;
  82382. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82383. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82384. this._updraftMultiplier = 0.02;
  82385. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82386. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82387. this._physicsEngine = this._scene.getPhysicsEngine();
  82388. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82389. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82390. this._tickCallback = this._tick.bind(this);
  82391. }
  82392. /**
  82393. * Returns the data related to the vortex event (cylinder).
  82394. * @returns {PhysicsVortexEventData}
  82395. */
  82396. PhysicsVortexEvent.prototype.getData = function () {
  82397. this._dataFetched = true;
  82398. return {
  82399. cylinder: this._cylinder,
  82400. };
  82401. };
  82402. /**
  82403. * Enables the vortex.
  82404. */
  82405. PhysicsVortexEvent.prototype.enable = function () {
  82406. this._tickCallback.call(this);
  82407. this._scene.registerBeforeRender(this._tickCallback);
  82408. };
  82409. /**
  82410. * Disables the cortex.
  82411. */
  82412. PhysicsVortexEvent.prototype.disable = function () {
  82413. this._scene.unregisterBeforeRender(this._tickCallback);
  82414. };
  82415. /**
  82416. * Disposes the sphere.
  82417. * @param {bolean} force
  82418. */
  82419. PhysicsVortexEvent.prototype.dispose = function (force) {
  82420. var _this = this;
  82421. if (force === void 0) { force = true; }
  82422. if (force) {
  82423. this._cylinder.dispose();
  82424. }
  82425. else {
  82426. setTimeout(function () {
  82427. if (!_this._dataFetched) {
  82428. _this._cylinder.dispose();
  82429. }
  82430. }, 0);
  82431. }
  82432. };
  82433. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82434. if (impostor.mass === 0) {
  82435. return null;
  82436. }
  82437. if (!this._intersectsWithCylinder(impostor)) {
  82438. return null;
  82439. }
  82440. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82441. return null;
  82442. }
  82443. var impostorObjectCenter = impostor.getObjectCenter();
  82444. 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)
  82445. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82446. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82447. var hit = ray.intersectsMesh(impostor.object);
  82448. var contactPoint = hit.pickedPoint;
  82449. if (!contactPoint) {
  82450. return null;
  82451. }
  82452. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82453. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82454. var directionToOrigin = contactPoint.normalize();
  82455. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82456. directionToOrigin = directionToOrigin.negate();
  82457. }
  82458. // TODO: find a more physically based solution
  82459. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82460. var forceX = directionToOrigin.x * this._strength / 8;
  82461. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82462. var forceZ = directionToOrigin.z * this._strength / 8;
  82463. }
  82464. else {
  82465. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82466. var forceY = this._originTop.y * this._updraftMultiplier;
  82467. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82468. }
  82469. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82470. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82471. return { force: force, contactPoint: impostorObjectCenter };
  82472. };
  82473. PhysicsVortexEvent.prototype._tick = function () {
  82474. var _this = this;
  82475. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82476. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82477. if (!impostorForceAndContactPoint) {
  82478. return;
  82479. }
  82480. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82481. });
  82482. };
  82483. /*** Helpers ***/
  82484. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82485. if (!this._cylinder) {
  82486. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82487. height: this._height,
  82488. diameter: this._radius * 2,
  82489. }, this._scene);
  82490. this._cylinder.isVisible = false;
  82491. }
  82492. };
  82493. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82494. var impostorObject = impostor.object;
  82495. this._prepareCylinder();
  82496. this._cylinder.position = this._cylinderPosition;
  82497. return this._cylinder.intersectsMesh(impostorObject, true);
  82498. };
  82499. return PhysicsVortexEvent;
  82500. }());
  82501. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82502. /***** Enums *****/
  82503. /**
  82504. * The strenght of the force in correspondence to the distance of the affected object
  82505. */
  82506. var PhysicsRadialImpulseFalloff;
  82507. (function (PhysicsRadialImpulseFalloff) {
  82508. /** Defines that impulse is constant in strength across it's whole radius */
  82509. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82510. /** DEfines that impulse gets weaker if it's further from the origin */
  82511. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82512. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82513. /**
  82514. * The strenght of the force in correspondence to the distance of the affected object
  82515. */
  82516. var PhysicsUpdraftMode;
  82517. (function (PhysicsUpdraftMode) {
  82518. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82519. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82520. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82521. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82522. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82523. })(BABYLON || (BABYLON = {}));
  82524. //# sourceMappingURL=babylon.physicsHelper.js.map
  82525. var BABYLON;
  82526. (function (BABYLON) {
  82527. var CannonJSPlugin = /** @class */ (function () {
  82528. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82529. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82530. if (iterations === void 0) { iterations = 10; }
  82531. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82532. this.name = "CannonJSPlugin";
  82533. this._physicsMaterials = new Array();
  82534. this._fixedTimeStep = 1 / 60;
  82535. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82536. this.BJSCANNON = CANNON;
  82537. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82538. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82539. this._tmpPosition = BABYLON.Vector3.Zero();
  82540. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82541. this._tmpUnityRotation = new BABYLON.Quaternion();
  82542. if (!this.isSupported()) {
  82543. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82544. return;
  82545. }
  82546. this._extendNamespace();
  82547. this.world = new this.BJSCANNON.World();
  82548. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82549. this.world.solver.iterations = iterations;
  82550. }
  82551. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82552. this.world.gravity.copy(gravity);
  82553. };
  82554. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82555. this._fixedTimeStep = timeStep;
  82556. };
  82557. CannonJSPlugin.prototype.getTimeStep = function () {
  82558. return this._fixedTimeStep;
  82559. };
  82560. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82561. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82562. };
  82563. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82564. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82565. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82566. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82567. };
  82568. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82569. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82570. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82571. impostor.physicsBody.applyForce(impulse, worldPoint);
  82572. };
  82573. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82574. //parent-child relationship. Does this impostor has a parent impostor?
  82575. if (impostor.parent) {
  82576. if (impostor.physicsBody) {
  82577. this.removePhysicsBody(impostor);
  82578. //TODO is that needed?
  82579. impostor.forceUpdate();
  82580. }
  82581. return;
  82582. }
  82583. //should a new body be created for this impostor?
  82584. if (impostor.isBodyInitRequired()) {
  82585. var shape = this._createShape(impostor);
  82586. //unregister events, if body is being changed
  82587. var oldBody = impostor.physicsBody;
  82588. if (oldBody) {
  82589. this.removePhysicsBody(impostor);
  82590. }
  82591. //create the body and material
  82592. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82593. var bodyCreationObject = {
  82594. mass: impostor.getParam("mass"),
  82595. material: material
  82596. };
  82597. // A simple extend, in case native options were used.
  82598. var nativeOptions = impostor.getParam("nativeOptions");
  82599. for (var key in nativeOptions) {
  82600. if (nativeOptions.hasOwnProperty(key)) {
  82601. bodyCreationObject[key] = nativeOptions[key];
  82602. }
  82603. }
  82604. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82605. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82606. this.world.addEventListener("preStep", impostor.beforeStep);
  82607. this.world.addEventListener("postStep", impostor.afterStep);
  82608. impostor.physicsBody.addShape(shape);
  82609. this.world.add(impostor.physicsBody);
  82610. //try to keep the body moving in the right direction by taking old properties.
  82611. //Should be tested!
  82612. if (oldBody) {
  82613. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82614. impostor.physicsBody[param].copy(oldBody[param]);
  82615. });
  82616. }
  82617. this._processChildMeshes(impostor);
  82618. }
  82619. //now update the body's transformation
  82620. this._updatePhysicsBodyTransformation(impostor);
  82621. };
  82622. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82623. var _this = this;
  82624. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82625. var currentRotation = mainImpostor.object.rotationQuaternion;
  82626. if (meshChildren.length) {
  82627. var processMesh = function (localPosition, mesh) {
  82628. if (!currentRotation || !mesh.rotationQuaternion) {
  82629. return;
  82630. }
  82631. var childImpostor = mesh.getPhysicsImpostor();
  82632. if (childImpostor) {
  82633. var parent = childImpostor.parent;
  82634. if (parent !== mainImpostor) {
  82635. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82636. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82637. if (childImpostor.physicsBody) {
  82638. _this.removePhysicsBody(childImpostor);
  82639. childImpostor.physicsBody = null;
  82640. }
  82641. childImpostor.parent = mainImpostor;
  82642. childImpostor.resetUpdateFlags();
  82643. 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));
  82644. //Add the mass of the children.
  82645. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82646. }
  82647. }
  82648. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82649. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82650. };
  82651. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82652. }
  82653. };
  82654. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82655. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82656. this.world.removeEventListener("preStep", impostor.beforeStep);
  82657. this.world.removeEventListener("postStep", impostor.afterStep);
  82658. this.world.remove(impostor.physicsBody);
  82659. };
  82660. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82661. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82662. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82663. if (!mainBody || !connectedBody) {
  82664. return;
  82665. }
  82666. var constraint;
  82667. var jointData = impostorJoint.joint.jointData;
  82668. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  82669. var constraintData = {
  82670. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  82671. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  82672. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  82673. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  82674. maxForce: jointData.nativeParams.maxForce,
  82675. collideConnected: !!jointData.collision
  82676. };
  82677. switch (impostorJoint.joint.type) {
  82678. case BABYLON.PhysicsJoint.HingeJoint:
  82679. case BABYLON.PhysicsJoint.Hinge2Joint:
  82680. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  82681. break;
  82682. case BABYLON.PhysicsJoint.DistanceJoint:
  82683. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  82684. break;
  82685. case BABYLON.PhysicsJoint.SpringJoint:
  82686. var springData = jointData;
  82687. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  82688. restLength: springData.length,
  82689. stiffness: springData.stiffness,
  82690. damping: springData.damping,
  82691. localAnchorA: constraintData.pivotA,
  82692. localAnchorB: constraintData.pivotB
  82693. });
  82694. break;
  82695. case BABYLON.PhysicsJoint.LockJoint:
  82696. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  82697. break;
  82698. case BABYLON.PhysicsJoint.PointToPointJoint:
  82699. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  82700. default:
  82701. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  82702. break;
  82703. }
  82704. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  82705. constraint.collideConnected = !!jointData.collision;
  82706. impostorJoint.joint.physicsJoint = constraint;
  82707. //don't add spring as constraint, as it is not one.
  82708. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  82709. this.world.addConstraint(constraint);
  82710. }
  82711. else {
  82712. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  82713. constraint.applyForce();
  82714. });
  82715. }
  82716. };
  82717. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  82718. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  82719. };
  82720. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  82721. var index;
  82722. var mat;
  82723. for (index = 0; index < this._physicsMaterials.length; index++) {
  82724. mat = this._physicsMaterials[index];
  82725. if (mat.friction === friction && mat.restitution === restitution) {
  82726. return mat;
  82727. }
  82728. }
  82729. var currentMat = new this.BJSCANNON.Material(name);
  82730. currentMat.friction = friction;
  82731. currentMat.restitution = restitution;
  82732. this._physicsMaterials.push(currentMat);
  82733. return currentMat;
  82734. };
  82735. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  82736. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  82737. };
  82738. CannonJSPlugin.prototype._createShape = function (impostor) {
  82739. var object = impostor.object;
  82740. var returnValue;
  82741. var extendSize = impostor.getObjectExtendSize();
  82742. switch (impostor.type) {
  82743. case BABYLON.PhysicsImpostor.SphereImpostor:
  82744. var radiusX = extendSize.x;
  82745. var radiusY = extendSize.y;
  82746. var radiusZ = extendSize.z;
  82747. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  82748. break;
  82749. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  82750. case BABYLON.PhysicsImpostor.CylinderImpostor:
  82751. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  82752. break;
  82753. case BABYLON.PhysicsImpostor.BoxImpostor:
  82754. var box = extendSize.scale(0.5);
  82755. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  82756. break;
  82757. case BABYLON.PhysicsImpostor.PlaneImpostor:
  82758. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  82759. returnValue = new this.BJSCANNON.Plane();
  82760. break;
  82761. case BABYLON.PhysicsImpostor.MeshImpostor:
  82762. // should transform the vertex data to world coordinates!!
  82763. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  82764. var rawFaces = object.getIndices ? object.getIndices() : [];
  82765. if (!rawVerts)
  82766. return;
  82767. // get only scale! so the object could transform correctly.
  82768. var oldPosition = object.position.clone();
  82769. var oldRotation = object.rotation && object.rotation.clone();
  82770. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  82771. object.position.copyFromFloats(0, 0, 0);
  82772. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82773. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82774. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82775. var transform = object.computeWorldMatrix(true);
  82776. // convert rawVerts to object space
  82777. var temp = new Array();
  82778. var index;
  82779. for (index = 0; index < rawVerts.length; index += 3) {
  82780. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  82781. }
  82782. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  82783. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  82784. //now set back the transformation!
  82785. object.position.copyFrom(oldPosition);
  82786. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  82787. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  82788. break;
  82789. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  82790. var oldPosition2 = object.position.clone();
  82791. var oldRotation2 = object.rotation && object.rotation.clone();
  82792. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  82793. object.position.copyFromFloats(0, 0, 0);
  82794. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  82795. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  82796. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  82797. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  82798. returnValue = this._createHeightmap(object);
  82799. object.position.copyFrom(oldPosition2);
  82800. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  82801. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  82802. object.computeWorldMatrix(true);
  82803. break;
  82804. case BABYLON.PhysicsImpostor.ParticleImpostor:
  82805. returnValue = new this.BJSCANNON.Particle();
  82806. break;
  82807. }
  82808. return returnValue;
  82809. };
  82810. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  82811. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  82812. var transform = object.computeWorldMatrix(true);
  82813. // convert rawVerts to object space
  82814. var temp = new Array();
  82815. var index;
  82816. for (index = 0; index < pos.length; index += 3) {
  82817. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  82818. }
  82819. pos = temp;
  82820. var matrix = new Array();
  82821. //For now pointDepth will not be used and will be automatically calculated.
  82822. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  82823. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  82824. var boundingInfo = object.getBoundingInfo();
  82825. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  82826. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  82827. var elementSize = dim * 2 / arraySize;
  82828. for (var i = 0; i < pos.length; i = i + 3) {
  82829. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  82830. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  82831. var y = -pos[i + 2] + minY;
  82832. if (!matrix[x]) {
  82833. matrix[x] = [];
  82834. }
  82835. if (!matrix[x][z]) {
  82836. matrix[x][z] = y;
  82837. }
  82838. matrix[x][z] = Math.max(y, matrix[x][z]);
  82839. }
  82840. for (var x = 0; x <= arraySize; ++x) {
  82841. if (!matrix[x]) {
  82842. var loc = 1;
  82843. while (!matrix[(x + loc) % arraySize]) {
  82844. loc++;
  82845. }
  82846. matrix[x] = matrix[(x + loc) % arraySize].slice();
  82847. //console.log("missing x", x);
  82848. }
  82849. for (var z = 0; z <= arraySize; ++z) {
  82850. if (!matrix[x][z]) {
  82851. var loc = 1;
  82852. var newValue;
  82853. while (newValue === undefined) {
  82854. newValue = matrix[x][(z + loc++) % arraySize];
  82855. }
  82856. matrix[x][z] = newValue;
  82857. }
  82858. }
  82859. }
  82860. var shape = new this.BJSCANNON.Heightfield(matrix, {
  82861. elementSize: elementSize
  82862. });
  82863. //For future reference, needed for body transformation
  82864. shape.minY = minY;
  82865. return shape;
  82866. };
  82867. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  82868. var object = impostor.object;
  82869. //make sure it is updated...
  82870. object.computeWorldMatrix && object.computeWorldMatrix(true);
  82871. // The delta between the mesh position and the mesh bounding box center
  82872. var bInfo = object.getBoundingInfo();
  82873. if (!bInfo)
  82874. return;
  82875. var center = impostor.getObjectCenter();
  82876. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  82877. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  82878. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  82879. this._tmpPosition.copyFrom(center);
  82880. var quaternion = object.rotationQuaternion;
  82881. if (!quaternion) {
  82882. return;
  82883. }
  82884. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  82885. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  82886. //-90 DEG in X, precalculated
  82887. quaternion = quaternion.multiply(this._minus90X);
  82888. //Invert! (Precalculated, 90 deg in X)
  82889. //No need to clone. this will never change.
  82890. impostor.setDeltaRotation(this._plus90X);
  82891. }
  82892. //If it is a heightfield, if should be centered.
  82893. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  82894. var mesh = object;
  82895. var boundingInfo = mesh.getBoundingInfo();
  82896. //calculate the correct body position:
  82897. var rotationQuaternion = mesh.rotationQuaternion;
  82898. mesh.rotationQuaternion = this._tmpUnityRotation;
  82899. mesh.computeWorldMatrix(true);
  82900. //get original center with no rotation
  82901. var c = center.clone();
  82902. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  82903. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  82904. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  82905. mesh.setPreTransformMatrix(p);
  82906. mesh.computeWorldMatrix(true);
  82907. //calculate the translation
  82908. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  82909. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  82910. //add it inverted to the delta
  82911. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  82912. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  82913. //rotation is back
  82914. mesh.rotationQuaternion = rotationQuaternion;
  82915. mesh.setPreTransformMatrix(oldPivot);
  82916. mesh.computeWorldMatrix(true);
  82917. }
  82918. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  82919. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  82920. //this._tmpPosition.copyFrom(object.position);
  82921. }
  82922. impostor.setDeltaPosition(this._tmpDeltaPosition);
  82923. //Now update the impostor object
  82924. impostor.physicsBody.position.copy(this._tmpPosition);
  82925. impostor.physicsBody.quaternion.copy(quaternion);
  82926. };
  82927. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  82928. impostor.object.position.copyFrom(impostor.physicsBody.position);
  82929. if (impostor.object.rotationQuaternion) {
  82930. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  82931. }
  82932. };
  82933. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  82934. impostor.physicsBody.position.copy(newPosition);
  82935. impostor.physicsBody.quaternion.copy(newRotation);
  82936. };
  82937. CannonJSPlugin.prototype.isSupported = function () {
  82938. return this.BJSCANNON !== undefined;
  82939. };
  82940. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  82941. impostor.physicsBody.velocity.copy(velocity);
  82942. };
  82943. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  82944. impostor.physicsBody.angularVelocity.copy(velocity);
  82945. };
  82946. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  82947. var v = impostor.physicsBody.velocity;
  82948. if (!v) {
  82949. return null;
  82950. }
  82951. return new BABYLON.Vector3(v.x, v.y, v.z);
  82952. };
  82953. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  82954. var v = impostor.physicsBody.angularVelocity;
  82955. if (!v) {
  82956. return null;
  82957. }
  82958. return new BABYLON.Vector3(v.x, v.y, v.z);
  82959. };
  82960. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  82961. impostor.physicsBody.mass = mass;
  82962. impostor.physicsBody.updateMassProperties();
  82963. };
  82964. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  82965. return impostor.physicsBody.mass;
  82966. };
  82967. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  82968. return impostor.physicsBody.material.friction;
  82969. };
  82970. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  82971. impostor.physicsBody.material.friction = friction;
  82972. };
  82973. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  82974. return impostor.physicsBody.material.restitution;
  82975. };
  82976. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  82977. impostor.physicsBody.material.restitution = restitution;
  82978. };
  82979. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  82980. impostor.physicsBody.sleep();
  82981. };
  82982. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  82983. impostor.physicsBody.wakeUp();
  82984. };
  82985. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  82986. joint.physicsJoint.distance = maxDistance;
  82987. };
  82988. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82989. // if (!motorIndex) {
  82990. // joint.physicsJoint.enableMotor();
  82991. // }
  82992. // }
  82993. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  82994. // if (!motorIndex) {
  82995. // joint.physicsJoint.disableMotor();
  82996. // }
  82997. // }
  82998. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  82999. if (!motorIndex) {
  83000. joint.physicsJoint.enableMotor();
  83001. joint.physicsJoint.setMotorSpeed(speed);
  83002. if (maxForce) {
  83003. this.setLimit(joint, maxForce);
  83004. }
  83005. }
  83006. };
  83007. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83008. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83009. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83010. };
  83011. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83012. var body = impostor.physicsBody;
  83013. mesh.position.x = body.position.x;
  83014. mesh.position.y = body.position.y;
  83015. mesh.position.z = body.position.z;
  83016. if (mesh.rotationQuaternion) {
  83017. mesh.rotationQuaternion.x = body.quaternion.x;
  83018. mesh.rotationQuaternion.y = body.quaternion.y;
  83019. mesh.rotationQuaternion.z = body.quaternion.z;
  83020. mesh.rotationQuaternion.w = body.quaternion.w;
  83021. }
  83022. };
  83023. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83024. var shape = impostor.physicsBody.shapes[0];
  83025. return shape.boundingSphereRadius;
  83026. };
  83027. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83028. var shape = impostor.physicsBody.shapes[0];
  83029. result.x = shape.halfExtents.x * 2;
  83030. result.y = shape.halfExtents.y * 2;
  83031. result.z = shape.halfExtents.z * 2;
  83032. };
  83033. CannonJSPlugin.prototype.dispose = function () {
  83034. };
  83035. CannonJSPlugin.prototype._extendNamespace = function () {
  83036. //this will force cannon to execute at least one step when using interpolation
  83037. var step_tmp1 = new this.BJSCANNON.Vec3();
  83038. var Engine = this.BJSCANNON;
  83039. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83040. maxSubSteps = maxSubSteps || 10;
  83041. timeSinceLastCalled = timeSinceLastCalled || 0;
  83042. if (timeSinceLastCalled === 0) {
  83043. this.internalStep(dt);
  83044. this.time += dt;
  83045. }
  83046. else {
  83047. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83048. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83049. var t0 = performance.now();
  83050. for (var i = 0; i !== internalSteps; i++) {
  83051. this.internalStep(dt);
  83052. if (performance.now() - t0 > dt * 1000) {
  83053. break;
  83054. }
  83055. }
  83056. this.time += timeSinceLastCalled;
  83057. var h = this.time % dt;
  83058. var h_div_dt = h / dt;
  83059. var interpvelo = step_tmp1;
  83060. var bodies = this.bodies;
  83061. for (var j = 0; j !== bodies.length; j++) {
  83062. var b = bodies[j];
  83063. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83064. b.position.vsub(b.previousPosition, interpvelo);
  83065. interpvelo.scale(h_div_dt, interpvelo);
  83066. b.position.vadd(interpvelo, b.interpolatedPosition);
  83067. }
  83068. else {
  83069. b.interpolatedPosition.copy(b.position);
  83070. b.interpolatedQuaternion.copy(b.quaternion);
  83071. }
  83072. }
  83073. }
  83074. };
  83075. };
  83076. return CannonJSPlugin;
  83077. }());
  83078. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83079. })(BABYLON || (BABYLON = {}));
  83080. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83081. var BABYLON;
  83082. (function (BABYLON) {
  83083. var OimoJSPlugin = /** @class */ (function () {
  83084. function OimoJSPlugin(iterations) {
  83085. this.name = "OimoJSPlugin";
  83086. this._tmpImpostorsArray = [];
  83087. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83088. this.BJSOIMO = OIMO;
  83089. this.world = new this.BJSOIMO.World({
  83090. iterations: iterations
  83091. });
  83092. this.world.clear();
  83093. }
  83094. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83095. this.world.gravity.copy(gravity);
  83096. };
  83097. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83098. this.world.timeStep = timeStep;
  83099. };
  83100. OimoJSPlugin.prototype.getTimeStep = function () {
  83101. return this.world.timeStep;
  83102. };
  83103. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83104. var _this = this;
  83105. impostors.forEach(function (impostor) {
  83106. impostor.beforeStep();
  83107. });
  83108. this.world.step();
  83109. impostors.forEach(function (impostor) {
  83110. impostor.afterStep();
  83111. //update the ordered impostors array
  83112. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83113. });
  83114. //check for collisions
  83115. var contact = this.world.contacts;
  83116. while (contact !== null) {
  83117. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83118. contact = contact.next;
  83119. continue;
  83120. }
  83121. //is this body colliding with any other? get the impostor
  83122. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83123. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83124. if (!mainImpostor || !collidingImpostor) {
  83125. contact = contact.next;
  83126. continue;
  83127. }
  83128. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83129. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83130. contact = contact.next;
  83131. }
  83132. };
  83133. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83134. var mass = impostor.physicsBody.mass;
  83135. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83136. };
  83137. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83138. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83139. this.applyImpulse(impostor, force, contactPoint);
  83140. };
  83141. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83142. var _this = this;
  83143. //parent-child relationship. Does this impostor has a parent impostor?
  83144. if (impostor.parent) {
  83145. if (impostor.physicsBody) {
  83146. this.removePhysicsBody(impostor);
  83147. //TODO is that needed?
  83148. impostor.forceUpdate();
  83149. }
  83150. return;
  83151. }
  83152. if (impostor.isBodyInitRequired()) {
  83153. var bodyConfig = {
  83154. name: impostor.uniqueId,
  83155. //Oimo must have mass, also for static objects.
  83156. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83157. size: [],
  83158. type: [],
  83159. pos: [],
  83160. posShape: [],
  83161. rot: [],
  83162. rotShape: [],
  83163. move: impostor.getParam("mass") !== 0,
  83164. density: impostor.getParam("mass"),
  83165. friction: impostor.getParam("friction"),
  83166. restitution: impostor.getParam("restitution"),
  83167. //Supporting older versions of Oimo
  83168. world: this.world
  83169. };
  83170. var impostors = [impostor];
  83171. var addToArray = function (parent) {
  83172. if (!parent.getChildMeshes)
  83173. return;
  83174. parent.getChildMeshes().forEach(function (m) {
  83175. if (m.physicsImpostor) {
  83176. impostors.push(m.physicsImpostor);
  83177. //m.physicsImpostor._init();
  83178. }
  83179. });
  83180. };
  83181. addToArray(impostor.object);
  83182. var checkWithEpsilon_1 = function (value) {
  83183. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83184. };
  83185. impostors.forEach(function (i) {
  83186. if (!i.object.rotationQuaternion) {
  83187. return;
  83188. }
  83189. //get the correct bounding box
  83190. var oldQuaternion = i.object.rotationQuaternion;
  83191. var rot = oldQuaternion.toEulerAngles();
  83192. var extendSize = i.getObjectExtendSize();
  83193. var radToDeg = 57.295779513082320876;
  83194. if (i === impostor) {
  83195. var center = impostor.getObjectCenter();
  83196. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83197. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83198. //Can also use Array.prototype.push.apply
  83199. bodyConfig.pos.push(center.x);
  83200. bodyConfig.pos.push(center.y);
  83201. bodyConfig.pos.push(center.z);
  83202. bodyConfig.posShape.push(0, 0, 0);
  83203. //tmp solution
  83204. bodyConfig.rot.push(rot.x * radToDeg);
  83205. bodyConfig.rot.push(rot.y * radToDeg);
  83206. bodyConfig.rot.push(rot.z * radToDeg);
  83207. bodyConfig.rotShape.push(0, 0, 0);
  83208. }
  83209. else {
  83210. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83211. bodyConfig.posShape.push(localPosition.x);
  83212. bodyConfig.posShape.push(localPosition.y);
  83213. bodyConfig.posShape.push(localPosition.z);
  83214. bodyConfig.pos.push(0, 0, 0);
  83215. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83216. bodyConfig.rot.push(0);
  83217. bodyConfig.rot.push(0);
  83218. bodyConfig.rot.push(0);
  83219. bodyConfig.rotShape.push(rot.x * radToDeg);
  83220. bodyConfig.rotShape.push(rot.y * radToDeg);
  83221. bodyConfig.rotShape.push(rot.z * radToDeg);
  83222. }
  83223. // register mesh
  83224. switch (i.type) {
  83225. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83226. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83227. case BABYLON.PhysicsImpostor.SphereImpostor:
  83228. var radiusX = extendSize.x;
  83229. var radiusY = extendSize.y;
  83230. var radiusZ = extendSize.z;
  83231. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83232. bodyConfig.type.push('sphere');
  83233. //due to the way oimo works with compounds, add 3 times
  83234. bodyConfig.size.push(size);
  83235. bodyConfig.size.push(size);
  83236. bodyConfig.size.push(size);
  83237. break;
  83238. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83239. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83240. var sizeY = checkWithEpsilon_1(extendSize.y);
  83241. bodyConfig.type.push('cylinder');
  83242. bodyConfig.size.push(sizeX);
  83243. bodyConfig.size.push(sizeY);
  83244. //due to the way oimo works with compounds, add one more value.
  83245. bodyConfig.size.push(sizeY);
  83246. break;
  83247. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83248. case BABYLON.PhysicsImpostor.BoxImpostor:
  83249. default:
  83250. var sizeX = checkWithEpsilon_1(extendSize.x);
  83251. var sizeY = checkWithEpsilon_1(extendSize.y);
  83252. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83253. bodyConfig.type.push('box');
  83254. //if (i === impostor) {
  83255. bodyConfig.size.push(sizeX);
  83256. bodyConfig.size.push(sizeY);
  83257. bodyConfig.size.push(sizeZ);
  83258. //} else {
  83259. // bodyConfig.size.push(0,0,0);
  83260. //}
  83261. break;
  83262. }
  83263. //actually not needed, but hey...
  83264. i.object.rotationQuaternion = oldQuaternion;
  83265. });
  83266. impostor.physicsBody = this.world.add(bodyConfig);
  83267. }
  83268. else {
  83269. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83270. }
  83271. impostor.setDeltaPosition(this._tmpPositionVector);
  83272. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83273. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83274. };
  83275. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83276. //impostor.physicsBody.dispose();
  83277. //Same as : (older oimo versions)
  83278. this.world.removeRigidBody(impostor.physicsBody);
  83279. };
  83280. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83281. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83282. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83283. if (!mainBody || !connectedBody) {
  83284. return;
  83285. }
  83286. var jointData = impostorJoint.joint.jointData;
  83287. var options = jointData.nativeParams || {};
  83288. var type;
  83289. var nativeJointData = {
  83290. body1: mainBody,
  83291. body2: connectedBody,
  83292. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83293. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83294. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83295. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83296. min: options.min,
  83297. max: options.max,
  83298. collision: options.collision || jointData.collision,
  83299. spring: options.spring,
  83300. //supporting older version of Oimo
  83301. world: this.world
  83302. };
  83303. switch (impostorJoint.joint.type) {
  83304. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83305. type = "jointBall";
  83306. break;
  83307. case BABYLON.PhysicsJoint.SpringJoint:
  83308. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83309. var springData = jointData;
  83310. nativeJointData.min = springData.length || nativeJointData.min;
  83311. //Max should also be set, just make sure it is at least min
  83312. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83313. case BABYLON.PhysicsJoint.DistanceJoint:
  83314. type = "jointDistance";
  83315. nativeJointData.max = jointData.maxDistance;
  83316. break;
  83317. case BABYLON.PhysicsJoint.PrismaticJoint:
  83318. type = "jointPrisme";
  83319. break;
  83320. case BABYLON.PhysicsJoint.SliderJoint:
  83321. type = "jointSlide";
  83322. break;
  83323. case BABYLON.PhysicsJoint.WheelJoint:
  83324. type = "jointWheel";
  83325. break;
  83326. case BABYLON.PhysicsJoint.HingeJoint:
  83327. default:
  83328. type = "jointHinge";
  83329. break;
  83330. }
  83331. nativeJointData.type = type;
  83332. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83333. };
  83334. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83335. //Bug in Oimo prevents us from disposing a joint in the playground
  83336. //joint.joint.physicsJoint.dispose();
  83337. //So we will bruteforce it!
  83338. try {
  83339. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83340. }
  83341. catch (e) {
  83342. BABYLON.Tools.Warn(e);
  83343. }
  83344. };
  83345. OimoJSPlugin.prototype.isSupported = function () {
  83346. return this.BJSOIMO !== undefined;
  83347. };
  83348. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83349. if (!impostor.physicsBody.sleeping) {
  83350. //TODO check that
  83351. /*if (impostor.physicsBody.shapes.next) {
  83352. var parentShape = this._getLastShape(impostor.physicsBody);
  83353. impostor.object.position.copyFrom(parentShape.position);
  83354. console.log(parentShape.position);
  83355. } else {*/
  83356. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83357. //}
  83358. if (impostor.object.rotationQuaternion) {
  83359. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83360. }
  83361. }
  83362. };
  83363. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83364. var body = impostor.physicsBody;
  83365. body.position.copy(newPosition);
  83366. body.orientation.copy(newRotation);
  83367. body.syncShapes();
  83368. body.awake();
  83369. };
  83370. /*private _getLastShape(body: any): any {
  83371. var lastShape = body.shapes;
  83372. while (lastShape.next) {
  83373. lastShape = lastShape.next;
  83374. }
  83375. return lastShape;
  83376. }*/
  83377. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83378. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83379. };
  83380. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83381. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83382. };
  83383. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83384. var v = impostor.physicsBody.linearVelocity;
  83385. if (!v) {
  83386. return null;
  83387. }
  83388. return new BABYLON.Vector3(v.x, v.y, v.z);
  83389. };
  83390. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83391. var v = impostor.physicsBody.angularVelocity;
  83392. if (!v) {
  83393. return null;
  83394. }
  83395. return new BABYLON.Vector3(v.x, v.y, v.z);
  83396. };
  83397. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83398. var staticBody = mass === 0;
  83399. //this will actually set the body's density and not its mass.
  83400. //But this is how oimo treats the mass variable.
  83401. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83402. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83403. };
  83404. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83405. return impostor.physicsBody.shapes.density;
  83406. };
  83407. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83408. return impostor.physicsBody.shapes.friction;
  83409. };
  83410. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83411. impostor.physicsBody.shapes.friction = friction;
  83412. };
  83413. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83414. return impostor.physicsBody.shapes.restitution;
  83415. };
  83416. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83417. impostor.physicsBody.shapes.restitution = restitution;
  83418. };
  83419. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83420. impostor.physicsBody.sleep();
  83421. };
  83422. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83423. impostor.physicsBody.awake();
  83424. };
  83425. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83426. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83427. if (minDistance !== void 0) {
  83428. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83429. }
  83430. };
  83431. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83432. //TODO separate rotational and transational motors.
  83433. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83434. if (motor) {
  83435. motor.setMotor(speed, maxForce);
  83436. }
  83437. };
  83438. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83439. //TODO separate rotational and transational motors.
  83440. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83441. if (motor) {
  83442. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83443. }
  83444. };
  83445. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83446. var body = impostor.physicsBody;
  83447. mesh.position.x = body.position.x;
  83448. mesh.position.y = body.position.y;
  83449. mesh.position.z = body.position.z;
  83450. if (mesh.rotationQuaternion) {
  83451. mesh.rotationQuaternion.x = body.orientation.x;
  83452. mesh.rotationQuaternion.y = body.orientation.y;
  83453. mesh.rotationQuaternion.z = body.orientation.z;
  83454. mesh.rotationQuaternion.w = body.orientation.s;
  83455. }
  83456. };
  83457. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83458. return impostor.physicsBody.shapes.radius;
  83459. };
  83460. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83461. var shape = impostor.physicsBody.shapes;
  83462. result.x = shape.halfWidth * 2;
  83463. result.y = shape.halfHeight * 2;
  83464. result.z = shape.halfDepth * 2;
  83465. };
  83466. OimoJSPlugin.prototype.dispose = function () {
  83467. this.world.clear();
  83468. };
  83469. return OimoJSPlugin;
  83470. }());
  83471. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83472. })(BABYLON || (BABYLON = {}));
  83473. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83474. var BABYLON;
  83475. (function (BABYLON) {
  83476. /*
  83477. * Based on jsTGALoader - Javascript loader for TGA file
  83478. * By Vincent Thibault
  83479. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83480. */
  83481. var TGATools = /** @class */ (function () {
  83482. function TGATools() {
  83483. }
  83484. TGATools.GetTGAHeader = function (data) {
  83485. var offset = 0;
  83486. var header = {
  83487. id_length: data[offset++],
  83488. colormap_type: data[offset++],
  83489. image_type: data[offset++],
  83490. colormap_index: data[offset++] | data[offset++] << 8,
  83491. colormap_length: data[offset++] | data[offset++] << 8,
  83492. colormap_size: data[offset++],
  83493. origin: [
  83494. data[offset++] | data[offset++] << 8,
  83495. data[offset++] | data[offset++] << 8
  83496. ],
  83497. width: data[offset++] | data[offset++] << 8,
  83498. height: data[offset++] | data[offset++] << 8,
  83499. pixel_size: data[offset++],
  83500. flags: data[offset++]
  83501. };
  83502. return header;
  83503. };
  83504. TGATools.UploadContent = function (gl, data) {
  83505. // Not enough data to contain header ?
  83506. if (data.length < 19) {
  83507. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83508. return;
  83509. }
  83510. // Read Header
  83511. var offset = 18;
  83512. var header = TGATools.GetTGAHeader(data);
  83513. // Assume it's a valid Targa file.
  83514. if (header.id_length + offset > data.length) {
  83515. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83516. return;
  83517. }
  83518. // Skip not needed data
  83519. offset += header.id_length;
  83520. var use_rle = false;
  83521. var use_pal = false;
  83522. var use_grey = false;
  83523. // Get some informations.
  83524. switch (header.image_type) {
  83525. case TGATools._TYPE_RLE_INDEXED:
  83526. use_rle = true;
  83527. case TGATools._TYPE_INDEXED:
  83528. use_pal = true;
  83529. break;
  83530. case TGATools._TYPE_RLE_RGB:
  83531. use_rle = true;
  83532. case TGATools._TYPE_RGB:
  83533. // use_rgb = true;
  83534. break;
  83535. case TGATools._TYPE_RLE_GREY:
  83536. use_rle = true;
  83537. case TGATools._TYPE_GREY:
  83538. use_grey = true;
  83539. break;
  83540. }
  83541. var pixel_data;
  83542. // var numAlphaBits = header.flags & 0xf;
  83543. var pixel_size = header.pixel_size >> 3;
  83544. var pixel_total = header.width * header.height * pixel_size;
  83545. // Read palettes
  83546. var palettes;
  83547. if (use_pal) {
  83548. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83549. }
  83550. // Read LRE
  83551. if (use_rle) {
  83552. pixel_data = new Uint8Array(pixel_total);
  83553. var c, count, i;
  83554. var localOffset = 0;
  83555. var pixels = new Uint8Array(pixel_size);
  83556. while (offset < pixel_total && localOffset < pixel_total) {
  83557. c = data[offset++];
  83558. count = (c & 0x7f) + 1;
  83559. // RLE pixels
  83560. if (c & 0x80) {
  83561. // Bind pixel tmp array
  83562. for (i = 0; i < pixel_size; ++i) {
  83563. pixels[i] = data[offset++];
  83564. }
  83565. // Copy pixel array
  83566. for (i = 0; i < count; ++i) {
  83567. pixel_data.set(pixels, localOffset + i * pixel_size);
  83568. }
  83569. localOffset += pixel_size * count;
  83570. }
  83571. // Raw pixels
  83572. else {
  83573. count *= pixel_size;
  83574. for (i = 0; i < count; ++i) {
  83575. pixel_data[localOffset + i] = data[offset++];
  83576. }
  83577. localOffset += count;
  83578. }
  83579. }
  83580. }
  83581. // RAW Pixels
  83582. else {
  83583. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83584. }
  83585. // Load to texture
  83586. var x_start, y_start, x_step, y_step, y_end, x_end;
  83587. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83588. default:
  83589. case TGATools._ORIGIN_UL:
  83590. x_start = 0;
  83591. x_step = 1;
  83592. x_end = header.width;
  83593. y_start = 0;
  83594. y_step = 1;
  83595. y_end = header.height;
  83596. break;
  83597. case TGATools._ORIGIN_BL:
  83598. x_start = 0;
  83599. x_step = 1;
  83600. x_end = header.width;
  83601. y_start = header.height - 1;
  83602. y_step = -1;
  83603. y_end = -1;
  83604. break;
  83605. case TGATools._ORIGIN_UR:
  83606. x_start = header.width - 1;
  83607. x_step = -1;
  83608. x_end = -1;
  83609. y_start = 0;
  83610. y_step = 1;
  83611. y_end = header.height;
  83612. break;
  83613. case TGATools._ORIGIN_BR:
  83614. x_start = header.width - 1;
  83615. x_step = -1;
  83616. x_end = -1;
  83617. y_start = header.height - 1;
  83618. y_step = -1;
  83619. y_end = -1;
  83620. break;
  83621. }
  83622. // Load the specify method
  83623. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83624. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83625. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83626. };
  83627. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83628. var image = pixel_data, colormap = palettes;
  83629. var width = header.width, height = header.height;
  83630. var color, i = 0, x, y;
  83631. var imageData = new Uint8Array(width * height * 4);
  83632. for (y = y_start; y !== y_end; y += y_step) {
  83633. for (x = x_start; x !== x_end; x += x_step, i++) {
  83634. color = image[i];
  83635. imageData[(x + width * y) * 4 + 3] = 255;
  83636. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83637. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83638. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83639. }
  83640. }
  83641. return imageData;
  83642. };
  83643. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83644. var image = pixel_data;
  83645. var width = header.width, height = header.height;
  83646. var color, i = 0, x, y;
  83647. var imageData = new Uint8Array(width * height * 4);
  83648. for (y = y_start; y !== y_end; y += y_step) {
  83649. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83650. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83651. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83652. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83653. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83654. imageData[(x + width * y) * 4 + 0] = r;
  83655. imageData[(x + width * y) * 4 + 1] = g;
  83656. imageData[(x + width * y) * 4 + 2] = b;
  83657. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83658. }
  83659. }
  83660. return imageData;
  83661. };
  83662. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83663. var image = pixel_data;
  83664. var width = header.width, height = header.height;
  83665. var i = 0, x, y;
  83666. var imageData = new Uint8Array(width * height * 4);
  83667. for (y = y_start; y !== y_end; y += y_step) {
  83668. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  83669. imageData[(x + width * y) * 4 + 3] = 255;
  83670. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83671. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83672. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83673. }
  83674. }
  83675. return imageData;
  83676. };
  83677. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83678. var image = pixel_data;
  83679. var width = header.width, height = header.height;
  83680. var i = 0, x, y;
  83681. var imageData = new Uint8Array(width * height * 4);
  83682. for (y = y_start; y !== y_end; y += y_step) {
  83683. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  83684. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83685. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83686. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83687. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  83688. }
  83689. }
  83690. return imageData;
  83691. };
  83692. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83693. var image = pixel_data;
  83694. var width = header.width, height = header.height;
  83695. var color, i = 0, x, y;
  83696. var imageData = new Uint8Array(width * height * 4);
  83697. for (y = y_start; y !== y_end; y += y_step) {
  83698. for (x = x_start; x !== x_end; x += x_step, i++) {
  83699. color = image[i];
  83700. imageData[(x + width * y) * 4 + 0] = color;
  83701. imageData[(x + width * y) * 4 + 1] = color;
  83702. imageData[(x + width * y) * 4 + 2] = color;
  83703. imageData[(x + width * y) * 4 + 3] = 255;
  83704. }
  83705. }
  83706. return imageData;
  83707. };
  83708. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83709. var image = pixel_data;
  83710. var width = header.width, height = header.height;
  83711. var i = 0, x, y;
  83712. var imageData = new Uint8Array(width * height * 4);
  83713. for (y = y_start; y !== y_end; y += y_step) {
  83714. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83715. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  83716. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  83717. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83718. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  83719. }
  83720. }
  83721. return imageData;
  83722. };
  83723. //private static _TYPE_NO_DATA = 0;
  83724. TGATools._TYPE_INDEXED = 1;
  83725. TGATools._TYPE_RGB = 2;
  83726. TGATools._TYPE_GREY = 3;
  83727. TGATools._TYPE_RLE_INDEXED = 9;
  83728. TGATools._TYPE_RLE_RGB = 10;
  83729. TGATools._TYPE_RLE_GREY = 11;
  83730. TGATools._ORIGIN_MASK = 0x30;
  83731. TGATools._ORIGIN_SHIFT = 0x04;
  83732. TGATools._ORIGIN_BL = 0x00;
  83733. TGATools._ORIGIN_BR = 0x01;
  83734. TGATools._ORIGIN_UL = 0x02;
  83735. TGATools._ORIGIN_UR = 0x03;
  83736. return TGATools;
  83737. }());
  83738. BABYLON.TGATools = TGATools;
  83739. })(BABYLON || (BABYLON = {}));
  83740. //# sourceMappingURL=babylon.tga.js.map
  83741. var BABYLON;
  83742. (function (BABYLON) {
  83743. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  83744. // All values and structures referenced from:
  83745. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  83746. var DDS_MAGIC = 0x20534444;
  83747. var
  83748. //DDSD_CAPS = 0x1,
  83749. //DDSD_HEIGHT = 0x2,
  83750. //DDSD_WIDTH = 0x4,
  83751. //DDSD_PITCH = 0x8,
  83752. //DDSD_PIXELFORMAT = 0x1000,
  83753. DDSD_MIPMAPCOUNT = 0x20000;
  83754. //DDSD_LINEARSIZE = 0x80000,
  83755. //DDSD_DEPTH = 0x800000;
  83756. // var DDSCAPS_COMPLEX = 0x8,
  83757. // DDSCAPS_MIPMAP = 0x400000,
  83758. // DDSCAPS_TEXTURE = 0x1000;
  83759. var DDSCAPS2_CUBEMAP = 0x200;
  83760. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  83761. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  83762. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  83763. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  83764. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  83765. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  83766. // DDSCAPS2_VOLUME = 0x200000;
  83767. var
  83768. //DDPF_ALPHAPIXELS = 0x1,
  83769. //DDPF_ALPHA = 0x2,
  83770. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  83771. //DDPF_YUV = 0x200,
  83772. DDPF_LUMINANCE = 0x20000;
  83773. function FourCCToInt32(value) {
  83774. return value.charCodeAt(0) +
  83775. (value.charCodeAt(1) << 8) +
  83776. (value.charCodeAt(2) << 16) +
  83777. (value.charCodeAt(3) << 24);
  83778. }
  83779. function Int32ToFourCC(value) {
  83780. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  83781. }
  83782. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  83783. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  83784. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  83785. var FOURCC_DX10 = FourCCToInt32("DX10");
  83786. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  83787. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  83788. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  83789. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  83790. var headerLengthInt = 31; // The header length in 32 bit ints
  83791. // Offsets into the header array
  83792. var off_magic = 0;
  83793. var off_size = 1;
  83794. var off_flags = 2;
  83795. var off_height = 3;
  83796. var off_width = 4;
  83797. var off_mipmapCount = 7;
  83798. var off_pfFlags = 20;
  83799. var off_pfFourCC = 21;
  83800. var off_RGBbpp = 22;
  83801. var off_RMask = 23;
  83802. var off_GMask = 24;
  83803. var off_BMask = 25;
  83804. var off_AMask = 26;
  83805. // var off_caps1 = 27;
  83806. var off_caps2 = 28;
  83807. // var off_caps3 = 29;
  83808. // var off_caps4 = 30;
  83809. var off_dxgiFormat = 32;
  83810. ;
  83811. var DDSTools = /** @class */ (function () {
  83812. function DDSTools() {
  83813. }
  83814. DDSTools.GetDDSInfo = function (arrayBuffer) {
  83815. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  83816. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  83817. var mipmapCount = 1;
  83818. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  83819. mipmapCount = Math.max(1, header[off_mipmapCount]);
  83820. }
  83821. var fourCC = header[off_pfFourCC];
  83822. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  83823. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  83824. switch (fourCC) {
  83825. case FOURCC_D3DFMT_R16G16B16A16F:
  83826. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83827. break;
  83828. case FOURCC_D3DFMT_R32G32B32A32F:
  83829. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83830. break;
  83831. case FOURCC_DX10:
  83832. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  83833. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83834. break;
  83835. }
  83836. }
  83837. return {
  83838. width: header[off_width],
  83839. height: header[off_height],
  83840. mipmapCount: mipmapCount,
  83841. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  83842. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  83843. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  83844. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  83845. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  83846. dxgiFormat: dxgiFormat,
  83847. textureType: textureType
  83848. };
  83849. };
  83850. DDSTools._ToHalfFloat = function (value) {
  83851. if (!DDSTools._FloatView) {
  83852. DDSTools._FloatView = new Float32Array(1);
  83853. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  83854. }
  83855. DDSTools._FloatView[0] = value;
  83856. var x = DDSTools._Int32View[0];
  83857. var bits = (x >> 16) & 0x8000; /* Get the sign */
  83858. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  83859. var e = (x >> 23) & 0xff; /* Using int is faster here */
  83860. /* If zero, or denormal, or exponent underflows too much for a denormal
  83861. * half, return signed zero. */
  83862. if (e < 103) {
  83863. return bits;
  83864. }
  83865. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  83866. if (e > 142) {
  83867. bits |= 0x7c00;
  83868. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  83869. * not Inf, so make sure we set one mantissa bit too. */
  83870. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  83871. return bits;
  83872. }
  83873. /* If exponent underflows but not too much, return a denormal */
  83874. if (e < 113) {
  83875. m |= 0x0800;
  83876. /* Extra rounding may overflow and set mantissa to 0 and exponent
  83877. * to 1, which is OK. */
  83878. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  83879. return bits;
  83880. }
  83881. bits |= ((e - 112) << 10) | (m >> 1);
  83882. bits += m & 1;
  83883. return bits;
  83884. };
  83885. DDSTools._FromHalfFloat = function (value) {
  83886. var s = (value & 0x8000) >> 15;
  83887. var e = (value & 0x7C00) >> 10;
  83888. var f = value & 0x03FF;
  83889. if (e === 0) {
  83890. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  83891. }
  83892. else if (e == 0x1F) {
  83893. return f ? NaN : ((s ? -1 : 1) * Infinity);
  83894. }
  83895. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  83896. };
  83897. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83898. var destArray = new Float32Array(dataLength);
  83899. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83900. var index = 0;
  83901. for (var y = 0; y < height; y++) {
  83902. for (var x = 0; x < width; x++) {
  83903. var srcPos = (x + y * width) * 4;
  83904. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  83905. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  83906. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  83907. if (DDSTools.StoreLODInAlphaChannel) {
  83908. destArray[index + 3] = lod;
  83909. }
  83910. else {
  83911. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  83912. }
  83913. index += 4;
  83914. }
  83915. }
  83916. return destArray;
  83917. };
  83918. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83919. if (DDSTools.StoreLODInAlphaChannel) {
  83920. var destArray = new Uint16Array(dataLength);
  83921. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83922. var index = 0;
  83923. for (var y = 0; y < height; y++) {
  83924. for (var x = 0; x < width; x++) {
  83925. var srcPos = (x + y * width) * 4;
  83926. destArray[index] = srcData[srcPos];
  83927. destArray[index + 1] = srcData[srcPos + 1];
  83928. destArray[index + 2] = srcData[srcPos + 2];
  83929. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  83930. index += 4;
  83931. }
  83932. }
  83933. return destArray;
  83934. }
  83935. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  83936. };
  83937. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83938. if (DDSTools.StoreLODInAlphaChannel) {
  83939. var destArray = new Float32Array(dataLength);
  83940. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83941. var index = 0;
  83942. for (var y = 0; y < height; y++) {
  83943. for (var x = 0; x < width; x++) {
  83944. var srcPos = (x + y * width) * 4;
  83945. destArray[index] = srcData[srcPos];
  83946. destArray[index + 1] = srcData[srcPos + 1];
  83947. destArray[index + 2] = srcData[srcPos + 2];
  83948. destArray[index + 3] = lod;
  83949. index += 4;
  83950. }
  83951. }
  83952. return destArray;
  83953. }
  83954. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  83955. };
  83956. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83957. var destArray = new Uint8Array(dataLength);
  83958. var srcData = new Float32Array(arrayBuffer, dataOffset);
  83959. var index = 0;
  83960. for (var y = 0; y < height; y++) {
  83961. for (var x = 0; x < width; x++) {
  83962. var srcPos = (x + y * width) * 4;
  83963. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  83964. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  83965. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  83966. if (DDSTools.StoreLODInAlphaChannel) {
  83967. destArray[index + 3] = lod;
  83968. }
  83969. else {
  83970. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  83971. }
  83972. index += 4;
  83973. }
  83974. }
  83975. return destArray;
  83976. };
  83977. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  83978. var destArray = new Uint8Array(dataLength);
  83979. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  83980. var index = 0;
  83981. for (var y = 0; y < height; y++) {
  83982. for (var x = 0; x < width; x++) {
  83983. var srcPos = (x + y * width) * 4;
  83984. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  83985. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  83986. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  83987. if (DDSTools.StoreLODInAlphaChannel) {
  83988. destArray[index + 3] = lod;
  83989. }
  83990. else {
  83991. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  83992. }
  83993. index += 4;
  83994. }
  83995. }
  83996. return destArray;
  83997. };
  83998. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  83999. var byteArray = new Uint8Array(dataLength);
  84000. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84001. var index = 0;
  84002. for (var y = 0; y < height; y++) {
  84003. for (var x = 0; x < width; x++) {
  84004. var srcPos = (x + y * width) * 4;
  84005. byteArray[index] = srcData[srcPos + rOffset];
  84006. byteArray[index + 1] = srcData[srcPos + gOffset];
  84007. byteArray[index + 2] = srcData[srcPos + bOffset];
  84008. byteArray[index + 3] = srcData[srcPos + aOffset];
  84009. index += 4;
  84010. }
  84011. }
  84012. return byteArray;
  84013. };
  84014. DDSTools._ExtractLongWordOrder = function (value) {
  84015. if (value === 0 || value === 255 || value === -16777216) {
  84016. return 0;
  84017. }
  84018. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84019. };
  84020. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84021. var byteArray = new Uint8Array(dataLength);
  84022. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84023. var index = 0;
  84024. for (var y = 0; y < height; y++) {
  84025. for (var x = 0; x < width; x++) {
  84026. var srcPos = (x + y * width) * 3;
  84027. byteArray[index] = srcData[srcPos + rOffset];
  84028. byteArray[index + 1] = srcData[srcPos + gOffset];
  84029. byteArray[index + 2] = srcData[srcPos + bOffset];
  84030. index += 3;
  84031. }
  84032. }
  84033. return byteArray;
  84034. };
  84035. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84036. var byteArray = new Uint8Array(dataLength);
  84037. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84038. var index = 0;
  84039. for (var y = 0; y < height; y++) {
  84040. for (var x = 0; x < width; x++) {
  84041. var srcPos = (x + y * width);
  84042. byteArray[index] = srcData[srcPos];
  84043. index++;
  84044. }
  84045. }
  84046. return byteArray;
  84047. };
  84048. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84049. if (lodIndex === void 0) { lodIndex = -1; }
  84050. var ext = engine.getCaps().s3tc;
  84051. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84052. var fourCC, width, height, dataLength = 0, dataOffset;
  84053. var byteArray, mipmapCount, mip;
  84054. var internalFormat = 0;
  84055. var format = 0;
  84056. var blockBytes = 1;
  84057. if (header[off_magic] !== DDS_MAGIC) {
  84058. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84059. return;
  84060. }
  84061. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84062. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84063. return;
  84064. }
  84065. if (info.isCompressed && !ext) {
  84066. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84067. return;
  84068. }
  84069. var bpp = header[off_RGBbpp];
  84070. dataOffset = header[off_size] + 4;
  84071. var computeFormats = false;
  84072. if (info.isFourCC) {
  84073. fourCC = header[off_pfFourCC];
  84074. switch (fourCC) {
  84075. case FOURCC_DXT1:
  84076. blockBytes = 8;
  84077. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84078. break;
  84079. case FOURCC_DXT3:
  84080. blockBytes = 16;
  84081. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84082. break;
  84083. case FOURCC_DXT5:
  84084. blockBytes = 16;
  84085. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84086. break;
  84087. case FOURCC_D3DFMT_R16G16B16A16F:
  84088. computeFormats = true;
  84089. break;
  84090. case FOURCC_D3DFMT_R32G32B32A32F:
  84091. computeFormats = true;
  84092. break;
  84093. case FOURCC_DX10:
  84094. // There is an additionnal header so dataOffset need to be changed
  84095. dataOffset += 5 * 4; // 5 uints
  84096. var supported = false;
  84097. switch (info.dxgiFormat) {
  84098. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84099. computeFormats = true;
  84100. supported = true;
  84101. break;
  84102. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84103. info.isRGB = true;
  84104. info.isFourCC = false;
  84105. bpp = 32;
  84106. supported = true;
  84107. break;
  84108. }
  84109. if (supported) {
  84110. break;
  84111. }
  84112. default:
  84113. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84114. return;
  84115. }
  84116. }
  84117. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84118. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84119. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84120. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84121. if (computeFormats) {
  84122. format = engine._getWebGLTextureType(info.textureType);
  84123. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84124. }
  84125. mipmapCount = 1;
  84126. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84127. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84128. }
  84129. for (var face = 0; face < faces; face++) {
  84130. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84131. width = header[off_width];
  84132. height = header[off_height];
  84133. for (mip = 0; mip < mipmapCount; ++mip) {
  84134. if (lodIndex === -1 || lodIndex === mip) {
  84135. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84136. var i = (lodIndex === -1) ? mip : 0;
  84137. if (!info.isCompressed && info.isFourCC) {
  84138. dataLength = width * height * 4;
  84139. var floatArray = null;
  84140. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84141. if (bpp === 128) {
  84142. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84143. }
  84144. else if (bpp === 64) {
  84145. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84146. }
  84147. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84148. format = engine._getWebGLTextureType(info.textureType);
  84149. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84150. }
  84151. else {
  84152. if (bpp === 128) {
  84153. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84154. }
  84155. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84156. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84157. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84158. format = engine._getWebGLTextureType(info.textureType);
  84159. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84160. }
  84161. else { // 64
  84162. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84163. }
  84164. }
  84165. if (floatArray) {
  84166. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84167. }
  84168. }
  84169. else if (info.isRGB) {
  84170. if (bpp === 24) {
  84171. dataLength = width * height * 3;
  84172. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84173. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84174. }
  84175. else { // 32
  84176. dataLength = width * height * 4;
  84177. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84178. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84179. }
  84180. }
  84181. else if (info.isLuminance) {
  84182. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84183. var unpaddedRowSize = width;
  84184. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84185. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84186. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84187. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84188. }
  84189. else {
  84190. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84191. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84192. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84193. }
  84194. }
  84195. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84196. width *= 0.5;
  84197. height *= 0.5;
  84198. width = Math.max(1.0, width);
  84199. height = Math.max(1.0, height);
  84200. }
  84201. if (currentFace !== undefined) {
  84202. // Loading a single face
  84203. break;
  84204. }
  84205. }
  84206. };
  84207. DDSTools.StoreLODInAlphaChannel = false;
  84208. return DDSTools;
  84209. }());
  84210. BABYLON.DDSTools = DDSTools;
  84211. })(BABYLON || (BABYLON = {}));
  84212. //# sourceMappingURL=babylon.dds.js.map
  84213. var BABYLON;
  84214. (function (BABYLON) {
  84215. /**
  84216. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84217. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84218. */
  84219. var KhronosTextureContainer = /** @class */ (function () {
  84220. /**
  84221. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84222. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84223. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84224. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84225. */
  84226. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84227. this.arrayBuffer = arrayBuffer;
  84228. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84229. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84230. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84231. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84232. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84233. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84234. BABYLON.Tools.Error("texture missing KTX identifier");
  84235. return;
  84236. }
  84237. // load the reset of the header in native 32 bit int
  84238. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84239. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84240. var oppositeEndianess = header[0] === 0x01020304;
  84241. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84242. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84243. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84244. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84245. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84246. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84247. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84248. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84249. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84250. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84251. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84252. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84253. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84254. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84255. if (this.glType !== 0) {
  84256. BABYLON.Tools.Error("only compressed formats currently supported");
  84257. return;
  84258. }
  84259. else {
  84260. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84261. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84262. }
  84263. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84264. BABYLON.Tools.Error("only 2D textures currently supported");
  84265. return;
  84266. }
  84267. if (this.numberOfArrayElements !== 0) {
  84268. BABYLON.Tools.Error("texture arrays not currently supported");
  84269. return;
  84270. }
  84271. if (this.numberOfFaces !== facesExpected) {
  84272. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84273. return;
  84274. }
  84275. // we now have a completely validated file, so could use existence of loadType as success
  84276. // would need to make this more elaborate & adjust checks above to support more than one load type
  84277. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84278. }
  84279. // not as fast hardware based, but will probably never need to use
  84280. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84281. return ((val & 0xFF) << 24)
  84282. | ((val & 0xFF00) << 8)
  84283. | ((val >> 8) & 0xFF00)
  84284. | ((val >> 24) & 0xFF);
  84285. };
  84286. /**
  84287. * It is assumed that the texture has already been created & is currently bound
  84288. */
  84289. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84290. switch (this.loadType) {
  84291. case KhronosTextureContainer.COMPRESSED_2D:
  84292. this._upload2DCompressedLevels(gl, loadMipmaps);
  84293. break;
  84294. case KhronosTextureContainer.TEX_2D:
  84295. case KhronosTextureContainer.COMPRESSED_3D:
  84296. case KhronosTextureContainer.TEX_3D:
  84297. }
  84298. };
  84299. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84300. // initialize width & height for level 1
  84301. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84302. var width = this.pixelWidth;
  84303. var height = this.pixelHeight;
  84304. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84305. for (var level = 0; level < mipmapCount; level++) {
  84306. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84307. for (var face = 0; face < this.numberOfFaces; face++) {
  84308. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84309. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84310. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84311. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84312. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84313. }
  84314. width = Math.max(1.0, width * 0.5);
  84315. height = Math.max(1.0, height * 0.5);
  84316. }
  84317. };
  84318. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84319. // load types
  84320. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84321. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84322. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84323. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84324. return KhronosTextureContainer;
  84325. }());
  84326. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84327. })(BABYLON || (BABYLON = {}));
  84328. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84329. var BABYLON;
  84330. (function (BABYLON) {
  84331. var Debug;
  84332. (function (Debug) {
  84333. /**
  84334. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84335. */
  84336. var SkeletonViewer = /** @class */ (function () {
  84337. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84338. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84339. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84340. this.skeleton = skeleton;
  84341. this.mesh = mesh;
  84342. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84343. this.renderingGroupId = renderingGroupId;
  84344. this.color = BABYLON.Color3.White();
  84345. this._debugLines = new Array();
  84346. this._isEnabled = false;
  84347. this._scene = scene;
  84348. this.update();
  84349. this._renderFunction = this.update.bind(this);
  84350. }
  84351. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84352. get: function () {
  84353. return this._isEnabled;
  84354. },
  84355. set: function (value) {
  84356. if (this._isEnabled === value) {
  84357. return;
  84358. }
  84359. this._isEnabled = value;
  84360. if (value) {
  84361. this._scene.registerBeforeRender(this._renderFunction);
  84362. }
  84363. else {
  84364. this._scene.unregisterBeforeRender(this._renderFunction);
  84365. }
  84366. },
  84367. enumerable: true,
  84368. configurable: true
  84369. });
  84370. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84371. if (x === void 0) { x = 0; }
  84372. if (y === void 0) { y = 0; }
  84373. if (z === void 0) { z = 0; }
  84374. var tmat = BABYLON.Tmp.Matrix[0];
  84375. var parentBone = bone.getParent();
  84376. tmat.copyFrom(bone.getLocalMatrix());
  84377. if (x !== 0 || y !== 0 || z !== 0) {
  84378. var tmat2 = BABYLON.Tmp.Matrix[1];
  84379. BABYLON.Matrix.IdentityToRef(tmat2);
  84380. tmat2.m[12] = x;
  84381. tmat2.m[13] = y;
  84382. tmat2.m[14] = z;
  84383. tmat2.multiplyToRef(tmat, tmat);
  84384. }
  84385. if (parentBone) {
  84386. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84387. }
  84388. tmat.multiplyToRef(meshMat, tmat);
  84389. position.x = tmat.m[12];
  84390. position.y = tmat.m[13];
  84391. position.z = tmat.m[14];
  84392. };
  84393. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84394. var len = bones.length;
  84395. var meshPos = this.mesh.position;
  84396. for (var i = 0; i < len; i++) {
  84397. var bone = bones[i];
  84398. var points = this._debugLines[i];
  84399. if (!points) {
  84400. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84401. this._debugLines[i] = points;
  84402. }
  84403. this._getBonePosition(points[0], bone, meshMat);
  84404. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84405. points[0].subtractInPlace(meshPos);
  84406. points[1].subtractInPlace(meshPos);
  84407. }
  84408. };
  84409. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84410. var len = bones.length;
  84411. var boneNum = 0;
  84412. var meshPos = this.mesh.position;
  84413. for (var i = len - 1; i >= 0; i--) {
  84414. var childBone = bones[i];
  84415. var parentBone = childBone.getParent();
  84416. if (!parentBone) {
  84417. continue;
  84418. }
  84419. var points = this._debugLines[boneNum];
  84420. if (!points) {
  84421. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84422. this._debugLines[boneNum] = points;
  84423. }
  84424. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84425. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84426. points[0].subtractInPlace(meshPos);
  84427. points[1].subtractInPlace(meshPos);
  84428. boneNum++;
  84429. }
  84430. };
  84431. SkeletonViewer.prototype.update = function () {
  84432. if (this.autoUpdateBonesMatrices) {
  84433. this.skeleton.computeAbsoluteTransforms();
  84434. }
  84435. if (this.skeleton.bones[0].length === undefined) {
  84436. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84437. }
  84438. else {
  84439. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84440. }
  84441. if (!this._debugMesh) {
  84442. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84443. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84444. }
  84445. else {
  84446. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84447. }
  84448. this._debugMesh.position.copyFrom(this.mesh.position);
  84449. this._debugMesh.color = this.color;
  84450. };
  84451. SkeletonViewer.prototype.dispose = function () {
  84452. if (this._debugMesh) {
  84453. this.isEnabled = false;
  84454. this._debugMesh.dispose();
  84455. this._debugMesh = null;
  84456. }
  84457. };
  84458. return SkeletonViewer;
  84459. }());
  84460. Debug.SkeletonViewer = SkeletonViewer;
  84461. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84462. })(BABYLON || (BABYLON = {}));
  84463. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84464. /**
  84465. * Module Debug contains the (visual) components to debug a scene correctly
  84466. */
  84467. var BABYLON;
  84468. (function (BABYLON) {
  84469. var Debug;
  84470. (function (Debug) {
  84471. /**
  84472. * The Axes viewer will show 3 axes in a specific point in space
  84473. */
  84474. var AxesViewer = /** @class */ (function () {
  84475. function AxesViewer(scene, scaleLines) {
  84476. if (scaleLines === void 0) { scaleLines = 1; }
  84477. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84478. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84479. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84480. this.scaleLines = 1;
  84481. this.scaleLines = scaleLines;
  84482. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84483. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84484. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84485. this._xmesh.renderingGroupId = 2;
  84486. this._ymesh.renderingGroupId = 2;
  84487. this._zmesh.renderingGroupId = 2;
  84488. this._xmesh.material.checkReadyOnlyOnce = true;
  84489. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84490. this._ymesh.material.checkReadyOnlyOnce = true;
  84491. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84492. this._zmesh.material.checkReadyOnlyOnce = true;
  84493. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84494. this.scene = scene;
  84495. }
  84496. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84497. var scaleLines = this.scaleLines;
  84498. if (this._xmesh) {
  84499. this._xmesh.position.copyFrom(position);
  84500. }
  84501. if (this._ymesh) {
  84502. this._ymesh.position.copyFrom(position);
  84503. }
  84504. if (this._zmesh) {
  84505. this._zmesh.position.copyFrom(position);
  84506. }
  84507. var point2 = this._xline[1];
  84508. point2.x = xaxis.x * scaleLines;
  84509. point2.y = xaxis.y * scaleLines;
  84510. point2.z = xaxis.z * scaleLines;
  84511. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84512. point2 = this._yline[1];
  84513. point2.x = yaxis.x * scaleLines;
  84514. point2.y = yaxis.y * scaleLines;
  84515. point2.z = yaxis.z * scaleLines;
  84516. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84517. point2 = this._zline[1];
  84518. point2.x = zaxis.x * scaleLines;
  84519. point2.y = zaxis.y * scaleLines;
  84520. point2.z = zaxis.z * scaleLines;
  84521. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84522. };
  84523. AxesViewer.prototype.dispose = function () {
  84524. if (this._xmesh) {
  84525. this._xmesh.dispose();
  84526. }
  84527. if (this._ymesh) {
  84528. this._ymesh.dispose();
  84529. }
  84530. if (this._zmesh) {
  84531. this._zmesh.dispose();
  84532. }
  84533. this._xmesh = null;
  84534. this._ymesh = null;
  84535. this._zmesh = null;
  84536. this.scene = null;
  84537. };
  84538. return AxesViewer;
  84539. }());
  84540. Debug.AxesViewer = AxesViewer;
  84541. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84542. })(BABYLON || (BABYLON = {}));
  84543. //# sourceMappingURL=babylon.axesViewer.js.map
  84544. var BABYLON;
  84545. (function (BABYLON) {
  84546. var Debug;
  84547. (function (Debug) {
  84548. /**
  84549. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84550. */
  84551. var BoneAxesViewer = /** @class */ (function (_super) {
  84552. __extends(BoneAxesViewer, _super);
  84553. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84554. if (scaleLines === void 0) { scaleLines = 1; }
  84555. var _this = _super.call(this, scene, scaleLines) || this;
  84556. _this.pos = BABYLON.Vector3.Zero();
  84557. _this.xaxis = BABYLON.Vector3.Zero();
  84558. _this.yaxis = BABYLON.Vector3.Zero();
  84559. _this.zaxis = BABYLON.Vector3.Zero();
  84560. _this.mesh = mesh;
  84561. _this.bone = bone;
  84562. return _this;
  84563. }
  84564. BoneAxesViewer.prototype.update = function () {
  84565. if (!this.mesh || !this.bone) {
  84566. return;
  84567. }
  84568. var bone = this.bone;
  84569. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84570. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84571. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84572. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84573. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84574. };
  84575. BoneAxesViewer.prototype.dispose = function () {
  84576. if (this.mesh) {
  84577. this.mesh = null;
  84578. this.bone = null;
  84579. _super.prototype.dispose.call(this);
  84580. }
  84581. };
  84582. return BoneAxesViewer;
  84583. }(Debug.AxesViewer));
  84584. Debug.BoneAxesViewer = BoneAxesViewer;
  84585. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84586. })(BABYLON || (BABYLON = {}));
  84587. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84588. var BABYLON;
  84589. (function (BABYLON) {
  84590. var RayHelper = /** @class */ (function () {
  84591. function RayHelper(ray) {
  84592. this.ray = ray;
  84593. }
  84594. RayHelper.CreateAndShow = function (ray, scene, color) {
  84595. var helper = new RayHelper(ray);
  84596. helper.show(scene, color);
  84597. return helper;
  84598. };
  84599. RayHelper.prototype.show = function (scene, color) {
  84600. if (!this._renderFunction && this.ray) {
  84601. var ray = this.ray;
  84602. this._renderFunction = this._render.bind(this);
  84603. this._scene = scene;
  84604. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84605. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84606. if (this._renderFunction) {
  84607. this._scene.registerBeforeRender(this._renderFunction);
  84608. }
  84609. }
  84610. if (color && this._renderLine) {
  84611. this._renderLine.color.copyFrom(color);
  84612. }
  84613. };
  84614. RayHelper.prototype.hide = function () {
  84615. if (this._renderFunction && this._scene) {
  84616. this._scene.unregisterBeforeRender(this._renderFunction);
  84617. this._scene = null;
  84618. this._renderFunction = null;
  84619. if (this._renderLine) {
  84620. this._renderLine.dispose();
  84621. this._renderLine = null;
  84622. }
  84623. this._renderPoints = [];
  84624. }
  84625. };
  84626. RayHelper.prototype._render = function () {
  84627. var ray = this.ray;
  84628. if (!ray) {
  84629. return;
  84630. }
  84631. var point = this._renderPoints[1];
  84632. var len = Math.min(ray.length, 1000000);
  84633. point.copyFrom(ray.direction);
  84634. point.scaleInPlace(len);
  84635. point.addInPlace(ray.origin);
  84636. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  84637. };
  84638. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  84639. this._attachedToMesh = mesh;
  84640. var ray = this.ray;
  84641. if (!ray) {
  84642. return;
  84643. }
  84644. if (!ray.direction) {
  84645. ray.direction = BABYLON.Vector3.Zero();
  84646. }
  84647. if (!ray.origin) {
  84648. ray.origin = BABYLON.Vector3.Zero();
  84649. }
  84650. if (length) {
  84651. ray.length = length;
  84652. }
  84653. if (!meshSpaceOrigin) {
  84654. meshSpaceOrigin = BABYLON.Vector3.Zero();
  84655. }
  84656. if (!meshSpaceDirection) {
  84657. // -1 so that this will work with Mesh.lookAt
  84658. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  84659. }
  84660. if (!this._meshSpaceDirection) {
  84661. this._meshSpaceDirection = meshSpaceDirection.clone();
  84662. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  84663. }
  84664. else {
  84665. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  84666. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  84667. }
  84668. if (!this._updateToMeshFunction) {
  84669. this._updateToMeshFunction = this._updateToMesh.bind(this);
  84670. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  84671. }
  84672. this._updateToMesh();
  84673. };
  84674. RayHelper.prototype.detachFromMesh = function () {
  84675. if (this._attachedToMesh) {
  84676. if (this._updateToMeshFunction) {
  84677. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  84678. }
  84679. this._attachedToMesh = null;
  84680. this._updateToMeshFunction = null;
  84681. }
  84682. };
  84683. RayHelper.prototype._updateToMesh = function () {
  84684. var ray = this.ray;
  84685. if (!this._attachedToMesh || !ray) {
  84686. return;
  84687. }
  84688. if (this._attachedToMesh._isDisposed) {
  84689. this.detachFromMesh();
  84690. return;
  84691. }
  84692. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  84693. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  84694. };
  84695. RayHelper.prototype.dispose = function () {
  84696. this.hide();
  84697. this.detachFromMesh();
  84698. this.ray = null;
  84699. };
  84700. return RayHelper;
  84701. }());
  84702. BABYLON.RayHelper = RayHelper;
  84703. })(BABYLON || (BABYLON = {}));
  84704. //# sourceMappingURL=babylon.rayHelper.js.map
  84705. var BABYLON;
  84706. (function (BABYLON) {
  84707. // load the inspector using require, if not present in the global namespace.
  84708. var DebugLayer = /** @class */ (function () {
  84709. function DebugLayer(scene) {
  84710. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84711. this._scene = scene;
  84712. // load inspector using require, if it doesn't exist on the global namespace.
  84713. }
  84714. /** Creates the inspector window. */
  84715. DebugLayer.prototype._createInspector = function (config) {
  84716. if (config === void 0) { config = {}; }
  84717. var popup = config.popup || false;
  84718. var initialTab = config.initialTab || 0;
  84719. var parentElement = config.parentElement || null;
  84720. if (!this._inspector) {
  84721. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  84722. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  84723. } // else nothing to do,; instance is already existing
  84724. };
  84725. DebugLayer.prototype.isVisible = function () {
  84726. if (!this._inspector) {
  84727. return false;
  84728. }
  84729. return true;
  84730. };
  84731. DebugLayer.prototype.hide = function () {
  84732. if (this._inspector) {
  84733. try {
  84734. this._inspector.dispose();
  84735. }
  84736. catch (e) {
  84737. // If the inspector has been removed directly from the inspector tool
  84738. }
  84739. this._inspector = null;
  84740. }
  84741. };
  84742. DebugLayer.prototype.show = function (config) {
  84743. if (config === void 0) { config = {}; }
  84744. if (typeof this.BJSINSPECTOR == 'undefined') {
  84745. // Load inspector and add it to the DOM
  84746. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  84747. }
  84748. else {
  84749. // Otherwise creates the inspector
  84750. this._createInspector(config);
  84751. }
  84752. };
  84753. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  84754. return DebugLayer;
  84755. }());
  84756. BABYLON.DebugLayer = DebugLayer;
  84757. })(BABYLON || (BABYLON = {}));
  84758. //# sourceMappingURL=babylon.debugLayer.js.map
  84759. var BABYLON;
  84760. (function (BABYLON) {
  84761. var Debug;
  84762. (function (Debug) {
  84763. /**
  84764. * Used to show the physics impostor around the specific mesh.
  84765. */
  84766. var PhysicsViewer = /** @class */ (function () {
  84767. function PhysicsViewer(scene) {
  84768. this._impostors = [];
  84769. this._meshes = [];
  84770. this._numMeshes = 0;
  84771. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  84772. var physicEngine = this._scene.getPhysicsEngine();
  84773. if (physicEngine) {
  84774. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  84775. }
  84776. }
  84777. PhysicsViewer.prototype._updateDebugMeshes = function () {
  84778. var plugin = this._physicsEnginePlugin;
  84779. for (var i = 0; i < this._numMeshes; i++) {
  84780. var impostor = this._impostors[i];
  84781. if (!impostor) {
  84782. continue;
  84783. }
  84784. if (impostor.isDisposed) {
  84785. this.hideImpostor(this._impostors[i--]);
  84786. }
  84787. else {
  84788. var mesh = this._meshes[i];
  84789. if (mesh && plugin) {
  84790. plugin.syncMeshWithImpostor(mesh, impostor);
  84791. }
  84792. }
  84793. }
  84794. };
  84795. PhysicsViewer.prototype.showImpostor = function (impostor) {
  84796. if (!this._scene) {
  84797. return;
  84798. }
  84799. for (var i = 0; i < this._numMeshes; i++) {
  84800. if (this._impostors[i] == impostor) {
  84801. return;
  84802. }
  84803. }
  84804. var debugMesh = this._getDebugMesh(impostor, this._scene);
  84805. if (debugMesh) {
  84806. this._impostors[this._numMeshes] = impostor;
  84807. this._meshes[this._numMeshes] = debugMesh;
  84808. if (this._numMeshes === 0) {
  84809. this._renderFunction = this._updateDebugMeshes.bind(this);
  84810. this._scene.registerBeforeRender(this._renderFunction);
  84811. }
  84812. this._numMeshes++;
  84813. }
  84814. };
  84815. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  84816. if (!impostor || !this._scene) {
  84817. return;
  84818. }
  84819. var removed = false;
  84820. for (var i = 0; i < this._numMeshes; i++) {
  84821. if (this._impostors[i] == impostor) {
  84822. var mesh = this._meshes[i];
  84823. if (!mesh) {
  84824. continue;
  84825. }
  84826. this._scene.removeMesh(mesh);
  84827. mesh.dispose();
  84828. this._numMeshes--;
  84829. if (this._numMeshes > 0) {
  84830. this._meshes[i] = this._meshes[this._numMeshes];
  84831. this._impostors[i] = this._impostors[this._numMeshes];
  84832. this._meshes[this._numMeshes] = null;
  84833. this._impostors[this._numMeshes] = null;
  84834. }
  84835. else {
  84836. this._meshes[0] = null;
  84837. this._impostors[0] = null;
  84838. }
  84839. removed = true;
  84840. break;
  84841. }
  84842. }
  84843. if (removed && this._numMeshes === 0) {
  84844. this._scene.unregisterBeforeRender(this._renderFunction);
  84845. }
  84846. };
  84847. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  84848. if (!this._debugMaterial) {
  84849. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  84850. this._debugMaterial.wireframe = true;
  84851. }
  84852. return this._debugMaterial;
  84853. };
  84854. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  84855. if (!this._debugBoxMesh) {
  84856. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  84857. this._debugBoxMesh.renderingGroupId = 1;
  84858. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84859. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  84860. scene.removeMesh(this._debugBoxMesh);
  84861. }
  84862. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  84863. };
  84864. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  84865. if (!this._debugSphereMesh) {
  84866. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  84867. this._debugSphereMesh.renderingGroupId = 1;
  84868. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  84869. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  84870. scene.removeMesh(this._debugSphereMesh);
  84871. }
  84872. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  84873. };
  84874. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  84875. var mesh = null;
  84876. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  84877. mesh = this._getDebugBoxMesh(scene);
  84878. impostor.getBoxSizeToRef(mesh.scaling);
  84879. }
  84880. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  84881. mesh = this._getDebugSphereMesh(scene);
  84882. var radius = impostor.getRadius();
  84883. mesh.scaling.x = radius * 2;
  84884. mesh.scaling.y = radius * 2;
  84885. mesh.scaling.z = radius * 2;
  84886. }
  84887. return mesh;
  84888. };
  84889. PhysicsViewer.prototype.dispose = function () {
  84890. for (var i = 0; i < this._numMeshes; i++) {
  84891. this.hideImpostor(this._impostors[i]);
  84892. }
  84893. if (this._debugBoxMesh) {
  84894. this._debugBoxMesh.dispose();
  84895. }
  84896. if (this._debugSphereMesh) {
  84897. this._debugSphereMesh.dispose();
  84898. }
  84899. if (this._debugMaterial) {
  84900. this._debugMaterial.dispose();
  84901. }
  84902. this._impostors.length = 0;
  84903. this._scene = null;
  84904. this._physicsEnginePlugin = null;
  84905. };
  84906. return PhysicsViewer;
  84907. }());
  84908. Debug.PhysicsViewer = PhysicsViewer;
  84909. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84910. })(BABYLON || (BABYLON = {}));
  84911. //# sourceMappingURL=babylon.physicsViewer.js.map
  84912. var BABYLON;
  84913. (function (BABYLON) {
  84914. var BoundingBoxRenderer = /** @class */ (function () {
  84915. function BoundingBoxRenderer(scene) {
  84916. this.frontColor = new BABYLON.Color3(1, 1, 1);
  84917. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  84918. this.showBackLines = true;
  84919. this.renderList = new BABYLON.SmartArray(32);
  84920. this._vertexBuffers = {};
  84921. this._scene = scene;
  84922. }
  84923. BoundingBoxRenderer.prototype._prepareRessources = function () {
  84924. if (this._colorShader) {
  84925. return;
  84926. }
  84927. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  84928. attributes: [BABYLON.VertexBuffer.PositionKind],
  84929. uniforms: ["world", "viewProjection", "color"]
  84930. });
  84931. var engine = this._scene.getEngine();
  84932. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  84933. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  84934. this._createIndexBuffer();
  84935. };
  84936. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  84937. var engine = this._scene.getEngine();
  84938. 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]);
  84939. };
  84940. BoundingBoxRenderer.prototype._rebuild = function () {
  84941. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84942. if (vb) {
  84943. vb._rebuild();
  84944. }
  84945. this._createIndexBuffer();
  84946. };
  84947. BoundingBoxRenderer.prototype.reset = function () {
  84948. this.renderList.reset();
  84949. };
  84950. BoundingBoxRenderer.prototype.render = function () {
  84951. if (this.renderList.length === 0) {
  84952. return;
  84953. }
  84954. this._prepareRessources();
  84955. if (!this._colorShader.isReady()) {
  84956. return;
  84957. }
  84958. var engine = this._scene.getEngine();
  84959. engine.setDepthWrite(false);
  84960. this._colorShader._preBind();
  84961. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  84962. var boundingBox = this.renderList.data[boundingBoxIndex];
  84963. var min = boundingBox.minimum;
  84964. var max = boundingBox.maximum;
  84965. var diff = max.subtract(min);
  84966. var median = min.add(diff.scale(0.5));
  84967. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  84968. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  84969. .multiply(boundingBox.getWorldMatrix());
  84970. // VBOs
  84971. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  84972. if (this.showBackLines) {
  84973. // Back
  84974. engine.setDepthFunctionToGreaterOrEqual();
  84975. this._scene.resetCachedMaterial();
  84976. this._colorShader.setColor4("color", this.backColor.toColor4());
  84977. this._colorShader.bind(worldMatrix);
  84978. // Draw order
  84979. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84980. }
  84981. // Front
  84982. engine.setDepthFunctionToLess();
  84983. this._scene.resetCachedMaterial();
  84984. this._colorShader.setColor4("color", this.frontColor.toColor4());
  84985. this._colorShader.bind(worldMatrix);
  84986. // Draw order
  84987. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  84988. }
  84989. this._colorShader.unbind();
  84990. engine.setDepthFunctionToLessOrEqual();
  84991. engine.setDepthWrite(true);
  84992. };
  84993. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  84994. this._prepareRessources();
  84995. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  84996. return;
  84997. }
  84998. var engine = this._scene.getEngine();
  84999. engine.setDepthWrite(false);
  85000. engine.setColorWrite(false);
  85001. this._colorShader._preBind();
  85002. var boundingBox = mesh._boundingInfo.boundingBox;
  85003. var min = boundingBox.minimum;
  85004. var max = boundingBox.maximum;
  85005. var diff = max.subtract(min);
  85006. var median = min.add(diff.scale(0.5));
  85007. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85008. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85009. .multiply(boundingBox.getWorldMatrix());
  85010. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85011. engine.setDepthFunctionToLess();
  85012. this._scene.resetCachedMaterial();
  85013. this._colorShader.bind(worldMatrix);
  85014. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85015. this._colorShader.unbind();
  85016. engine.setDepthFunctionToLessOrEqual();
  85017. engine.setDepthWrite(true);
  85018. engine.setColorWrite(true);
  85019. };
  85020. BoundingBoxRenderer.prototype.dispose = function () {
  85021. if (!this._colorShader) {
  85022. return;
  85023. }
  85024. this.renderList.dispose();
  85025. this._colorShader.dispose();
  85026. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85027. if (buffer) {
  85028. buffer.dispose();
  85029. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85030. }
  85031. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85032. };
  85033. return BoundingBoxRenderer;
  85034. }());
  85035. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85036. })(BABYLON || (BABYLON = {}));
  85037. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85038. var BABYLON;
  85039. (function (BABYLON) {
  85040. /**
  85041. * Defines a target to use with MorphTargetManager
  85042. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85043. */
  85044. var MorphTarget = /** @class */ (function () {
  85045. /**
  85046. * Creates a new MorphTarget
  85047. * @param name defines the name of the target
  85048. * @param influence defines the influence to use
  85049. */
  85050. function MorphTarget(
  85051. /** defines the name of the target */
  85052. name, influence) {
  85053. if (influence === void 0) { influence = 0; }
  85054. this.name = name;
  85055. /**
  85056. * Gets or sets the list of animations
  85057. */
  85058. this.animations = new Array();
  85059. this._positions = null;
  85060. this._normals = null;
  85061. this._tangents = null;
  85062. /**
  85063. * Observable raised when the influence changes
  85064. */
  85065. this.onInfluenceChanged = new BABYLON.Observable();
  85066. this.influence = influence;
  85067. }
  85068. Object.defineProperty(MorphTarget.prototype, "influence", {
  85069. /**
  85070. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85071. */
  85072. get: function () {
  85073. return this._influence;
  85074. },
  85075. set: function (influence) {
  85076. if (this._influence === influence) {
  85077. return;
  85078. }
  85079. var previous = this._influence;
  85080. this._influence = influence;
  85081. if (this.onInfluenceChanged.hasObservers) {
  85082. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85083. }
  85084. },
  85085. enumerable: true,
  85086. configurable: true
  85087. });
  85088. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85089. /**
  85090. * Gets a boolean defining if the target contains position data
  85091. */
  85092. get: function () {
  85093. return !!this._positions;
  85094. },
  85095. enumerable: true,
  85096. configurable: true
  85097. });
  85098. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85099. /**
  85100. * Gets a boolean defining if the target contains normal data
  85101. */
  85102. get: function () {
  85103. return !!this._normals;
  85104. },
  85105. enumerable: true,
  85106. configurable: true
  85107. });
  85108. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85109. /**
  85110. * Gets a boolean defining if the target contains tangent data
  85111. */
  85112. get: function () {
  85113. return !!this._tangents;
  85114. },
  85115. enumerable: true,
  85116. configurable: true
  85117. });
  85118. /**
  85119. * Affects position data to this target
  85120. * @param data defines the position data to use
  85121. */
  85122. MorphTarget.prototype.setPositions = function (data) {
  85123. this._positions = data;
  85124. };
  85125. /**
  85126. * Gets the position data stored in this target
  85127. * @returns a FloatArray containing the position data (or null if not present)
  85128. */
  85129. MorphTarget.prototype.getPositions = function () {
  85130. return this._positions;
  85131. };
  85132. /**
  85133. * Affects normal data to this target
  85134. * @param data defines the normal data to use
  85135. */
  85136. MorphTarget.prototype.setNormals = function (data) {
  85137. this._normals = data;
  85138. };
  85139. /**
  85140. * Gets the normal data stored in this target
  85141. * @returns a FloatArray containing the normal data (or null if not present)
  85142. */
  85143. MorphTarget.prototype.getNormals = function () {
  85144. return this._normals;
  85145. };
  85146. /**
  85147. * Affects tangent data to this target
  85148. * @param data defines the tangent data to use
  85149. */
  85150. MorphTarget.prototype.setTangents = function (data) {
  85151. this._tangents = data;
  85152. };
  85153. /**
  85154. * Gets the tangent data stored in this target
  85155. * @returns a FloatArray containing the tangent data (or null if not present)
  85156. */
  85157. MorphTarget.prototype.getTangents = function () {
  85158. return this._tangents;
  85159. };
  85160. /**
  85161. * Serializes the current target into a Serialization object
  85162. * @returns the serialized object
  85163. */
  85164. MorphTarget.prototype.serialize = function () {
  85165. var serializationObject = {};
  85166. serializationObject.name = this.name;
  85167. serializationObject.influence = this.influence;
  85168. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85169. if (this.hasNormals) {
  85170. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85171. }
  85172. if (this.hasTangents) {
  85173. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85174. }
  85175. // Animations
  85176. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85177. return serializationObject;
  85178. };
  85179. // Statics
  85180. /**
  85181. * Creates a new target from serialized data
  85182. * @param serializationObject defines the serialized data to use
  85183. * @returns a new MorphTarget
  85184. */
  85185. MorphTarget.Parse = function (serializationObject) {
  85186. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85187. result.setPositions(serializationObject.positions);
  85188. if (serializationObject.normals) {
  85189. result.setNormals(serializationObject.normals);
  85190. }
  85191. if (serializationObject.tangents) {
  85192. result.setTangents(serializationObject.tangents);
  85193. }
  85194. // Animations
  85195. if (serializationObject.animations) {
  85196. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85197. var parsedAnimation = serializationObject.animations[animationIndex];
  85198. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85199. }
  85200. }
  85201. return result;
  85202. };
  85203. /**
  85204. * Creates a MorphTarget from mesh data
  85205. * @param mesh defines the source mesh
  85206. * @param name defines the name to use for the new target
  85207. * @param influence defines the influence to attach to the target
  85208. * @returns a new MorphTarget
  85209. */
  85210. MorphTarget.FromMesh = function (mesh, name, influence) {
  85211. if (!name) {
  85212. name = mesh.name;
  85213. }
  85214. var result = new MorphTarget(name, influence);
  85215. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85217. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85218. }
  85219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85220. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85221. }
  85222. return result;
  85223. };
  85224. return MorphTarget;
  85225. }());
  85226. BABYLON.MorphTarget = MorphTarget;
  85227. })(BABYLON || (BABYLON = {}));
  85228. //# sourceMappingURL=babylon.morphTarget.js.map
  85229. var BABYLON;
  85230. (function (BABYLON) {
  85231. /**
  85232. * This class is used to deform meshes using morphing between different targets
  85233. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85234. */
  85235. var MorphTargetManager = /** @class */ (function () {
  85236. /**
  85237. * Creates a new MorphTargetManager
  85238. * @param scene defines the current scene
  85239. */
  85240. function MorphTargetManager(scene) {
  85241. if (scene === void 0) { scene = null; }
  85242. this._targets = new Array();
  85243. this._targetObservable = new Array();
  85244. this._activeTargets = new BABYLON.SmartArray(16);
  85245. this._supportsNormals = false;
  85246. this._supportsTangents = false;
  85247. this._vertexCount = 0;
  85248. this._uniqueId = 0;
  85249. this._tempInfluences = new Array();
  85250. if (!scene) {
  85251. scene = BABYLON.Engine.LastCreatedScene;
  85252. }
  85253. this._scene = scene;
  85254. if (this._scene) {
  85255. this._scene.morphTargetManagers.push(this);
  85256. this._uniqueId = this._scene.getUniqueId();
  85257. }
  85258. }
  85259. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85260. /**
  85261. * Gets the unique ID of this manager
  85262. */
  85263. get: function () {
  85264. return this._uniqueId;
  85265. },
  85266. enumerable: true,
  85267. configurable: true
  85268. });
  85269. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85270. /**
  85271. * Gets the number of vertices handled by this manager
  85272. */
  85273. get: function () {
  85274. return this._vertexCount;
  85275. },
  85276. enumerable: true,
  85277. configurable: true
  85278. });
  85279. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85280. /**
  85281. * Gets a boolean indicating if this manager supports morphing of normals
  85282. */
  85283. get: function () {
  85284. return this._supportsNormals;
  85285. },
  85286. enumerable: true,
  85287. configurable: true
  85288. });
  85289. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85290. /**
  85291. * Gets a boolean indicating if this manager supports morphing of tangents
  85292. */
  85293. get: function () {
  85294. return this._supportsTangents;
  85295. },
  85296. enumerable: true,
  85297. configurable: true
  85298. });
  85299. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85300. /**
  85301. * Gets the number of targets stored in this manager
  85302. */
  85303. get: function () {
  85304. return this._targets.length;
  85305. },
  85306. enumerable: true,
  85307. configurable: true
  85308. });
  85309. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85310. /**
  85311. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85312. */
  85313. get: function () {
  85314. return this._activeTargets.length;
  85315. },
  85316. enumerable: true,
  85317. configurable: true
  85318. });
  85319. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85320. /**
  85321. * Gets the list of influences (one per target)
  85322. */
  85323. get: function () {
  85324. return this._influences;
  85325. },
  85326. enumerable: true,
  85327. configurable: true
  85328. });
  85329. /**
  85330. * Gets the active target at specified index. An active target is a target with an influence > 0
  85331. * @param index defines the index to check
  85332. * @returns the requested target
  85333. */
  85334. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85335. return this._activeTargets.data[index];
  85336. };
  85337. /**
  85338. * Gets the target at specified index
  85339. * @param index defines the index to check
  85340. * @returns the requested target
  85341. */
  85342. MorphTargetManager.prototype.getTarget = function (index) {
  85343. return this._targets[index];
  85344. };
  85345. /**
  85346. * Add a new target to this manager
  85347. * @param target defines the target to add
  85348. */
  85349. MorphTargetManager.prototype.addTarget = function (target) {
  85350. var _this = this;
  85351. this._targets.push(target);
  85352. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85353. _this._syncActiveTargets(needUpdate);
  85354. }));
  85355. this._syncActiveTargets(true);
  85356. };
  85357. /**
  85358. * Removes a target from the manager
  85359. * @param target defines the target to remove
  85360. */
  85361. MorphTargetManager.prototype.removeTarget = function (target) {
  85362. var index = this._targets.indexOf(target);
  85363. if (index >= 0) {
  85364. this._targets.splice(index, 1);
  85365. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85366. this._syncActiveTargets(true);
  85367. }
  85368. };
  85369. /**
  85370. * Serializes the current manager into a Serialization object
  85371. * @returns the serialized object
  85372. */
  85373. MorphTargetManager.prototype.serialize = function () {
  85374. var serializationObject = {};
  85375. serializationObject.id = this.uniqueId;
  85376. serializationObject.targets = [];
  85377. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85378. var target = _a[_i];
  85379. serializationObject.targets.push(target.serialize());
  85380. }
  85381. return serializationObject;
  85382. };
  85383. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85384. var influenceCount = 0;
  85385. this._activeTargets.reset();
  85386. this._supportsNormals = true;
  85387. this._supportsTangents = true;
  85388. this._vertexCount = 0;
  85389. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85390. var target = _a[_i];
  85391. this._activeTargets.push(target);
  85392. this._tempInfluences[influenceCount++] = target.influence;
  85393. var positions = target.getPositions();
  85394. if (positions) {
  85395. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85396. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85397. var vertexCount = positions.length / 3;
  85398. if (this._vertexCount === 0) {
  85399. this._vertexCount = vertexCount;
  85400. }
  85401. else if (this._vertexCount !== vertexCount) {
  85402. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85403. return;
  85404. }
  85405. }
  85406. }
  85407. if (!this._influences || this._influences.length !== influenceCount) {
  85408. this._influences = new Float32Array(influenceCount);
  85409. }
  85410. for (var index = 0; index < influenceCount; index++) {
  85411. this._influences[index] = this._tempInfluences[index];
  85412. }
  85413. if (needUpdate) {
  85414. this.synchronize();
  85415. }
  85416. };
  85417. /**
  85418. * Syncrhonize the targets with all the meshes using this morph target manager
  85419. */
  85420. MorphTargetManager.prototype.synchronize = function () {
  85421. if (!this._scene) {
  85422. return;
  85423. }
  85424. // Flag meshes as dirty to resync with the active targets
  85425. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85426. var mesh = _a[_i];
  85427. if (mesh.morphTargetManager === this) {
  85428. mesh._syncGeometryWithMorphTargetManager();
  85429. }
  85430. }
  85431. };
  85432. // Statics
  85433. /**
  85434. * Creates a new MorphTargetManager from serialized data
  85435. * @param serializationObject defines the serialized data
  85436. * @param scene defines the hosting scene
  85437. * @returns the new MorphTargetManager
  85438. */
  85439. MorphTargetManager.Parse = function (serializationObject, scene) {
  85440. var result = new MorphTargetManager(scene);
  85441. result._uniqueId = serializationObject.id;
  85442. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85443. var targetData = _a[_i];
  85444. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85445. }
  85446. return result;
  85447. };
  85448. return MorphTargetManager;
  85449. }());
  85450. BABYLON.MorphTargetManager = MorphTargetManager;
  85451. })(BABYLON || (BABYLON = {}));
  85452. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85453. var BABYLON;
  85454. (function (BABYLON) {
  85455. var Octree = /** @class */ (function () {
  85456. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85457. if (maxDepth === void 0) { maxDepth = 2; }
  85458. this.maxDepth = maxDepth;
  85459. this.dynamicContent = new Array();
  85460. this._maxBlockCapacity = maxBlockCapacity || 64;
  85461. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85462. this._creationFunc = creationFunc;
  85463. }
  85464. // Methods
  85465. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85466. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85467. };
  85468. Octree.prototype.addMesh = function (entry) {
  85469. for (var index = 0; index < this.blocks.length; index++) {
  85470. var block = this.blocks[index];
  85471. block.addEntry(entry);
  85472. }
  85473. };
  85474. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85475. this._selectionContent.reset();
  85476. for (var index = 0; index < this.blocks.length; index++) {
  85477. var block = this.blocks[index];
  85478. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85479. }
  85480. if (allowDuplicate) {
  85481. this._selectionContent.concat(this.dynamicContent);
  85482. }
  85483. else {
  85484. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85485. }
  85486. return this._selectionContent;
  85487. };
  85488. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85489. this._selectionContent.reset();
  85490. for (var index = 0; index < this.blocks.length; index++) {
  85491. var block = this.blocks[index];
  85492. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85493. }
  85494. if (allowDuplicate) {
  85495. this._selectionContent.concat(this.dynamicContent);
  85496. }
  85497. else {
  85498. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85499. }
  85500. return this._selectionContent;
  85501. };
  85502. Octree.prototype.intersectsRay = function (ray) {
  85503. this._selectionContent.reset();
  85504. for (var index = 0; index < this.blocks.length; index++) {
  85505. var block = this.blocks[index];
  85506. block.intersectsRay(ray, this._selectionContent);
  85507. }
  85508. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85509. return this._selectionContent;
  85510. };
  85511. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85512. target.blocks = new Array();
  85513. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85514. // Segmenting space
  85515. for (var x = 0; x < 2; x++) {
  85516. for (var y = 0; y < 2; y++) {
  85517. for (var z = 0; z < 2; z++) {
  85518. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85519. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85520. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85521. block.addEntries(entries);
  85522. target.blocks.push(block);
  85523. }
  85524. }
  85525. }
  85526. };
  85527. Octree.CreationFuncForMeshes = function (entry, block) {
  85528. var boundingInfo = entry.getBoundingInfo();
  85529. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85530. block.entries.push(entry);
  85531. }
  85532. };
  85533. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85534. var boundingInfo = entry.getBoundingInfo();
  85535. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85536. block.entries.push(entry);
  85537. }
  85538. };
  85539. return Octree;
  85540. }());
  85541. BABYLON.Octree = Octree;
  85542. })(BABYLON || (BABYLON = {}));
  85543. //# sourceMappingURL=babylon.octree.js.map
  85544. var BABYLON;
  85545. (function (BABYLON) {
  85546. var OctreeBlock = /** @class */ (function () {
  85547. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85548. this.entries = new Array();
  85549. this._boundingVectors = new Array();
  85550. this._capacity = capacity;
  85551. this._depth = depth;
  85552. this._maxDepth = maxDepth;
  85553. this._creationFunc = creationFunc;
  85554. this._minPoint = minPoint;
  85555. this._maxPoint = maxPoint;
  85556. this._boundingVectors.push(minPoint.clone());
  85557. this._boundingVectors.push(maxPoint.clone());
  85558. this._boundingVectors.push(minPoint.clone());
  85559. this._boundingVectors[2].x = maxPoint.x;
  85560. this._boundingVectors.push(minPoint.clone());
  85561. this._boundingVectors[3].y = maxPoint.y;
  85562. this._boundingVectors.push(minPoint.clone());
  85563. this._boundingVectors[4].z = maxPoint.z;
  85564. this._boundingVectors.push(maxPoint.clone());
  85565. this._boundingVectors[5].z = minPoint.z;
  85566. this._boundingVectors.push(maxPoint.clone());
  85567. this._boundingVectors[6].x = minPoint.x;
  85568. this._boundingVectors.push(maxPoint.clone());
  85569. this._boundingVectors[7].y = minPoint.y;
  85570. }
  85571. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85572. // Property
  85573. get: function () {
  85574. return this._capacity;
  85575. },
  85576. enumerable: true,
  85577. configurable: true
  85578. });
  85579. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85580. get: function () {
  85581. return this._minPoint;
  85582. },
  85583. enumerable: true,
  85584. configurable: true
  85585. });
  85586. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85587. get: function () {
  85588. return this._maxPoint;
  85589. },
  85590. enumerable: true,
  85591. configurable: true
  85592. });
  85593. // Methods
  85594. OctreeBlock.prototype.addEntry = function (entry) {
  85595. if (this.blocks) {
  85596. for (var index = 0; index < this.blocks.length; index++) {
  85597. var block = this.blocks[index];
  85598. block.addEntry(entry);
  85599. }
  85600. return;
  85601. }
  85602. this._creationFunc(entry, this);
  85603. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85604. this.createInnerBlocks();
  85605. }
  85606. };
  85607. OctreeBlock.prototype.addEntries = function (entries) {
  85608. for (var index = 0; index < entries.length; index++) {
  85609. var mesh = entries[index];
  85610. this.addEntry(mesh);
  85611. }
  85612. };
  85613. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85614. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85615. if (this.blocks) {
  85616. for (var index = 0; index < this.blocks.length; index++) {
  85617. var block = this.blocks[index];
  85618. block.select(frustumPlanes, selection, allowDuplicate);
  85619. }
  85620. return;
  85621. }
  85622. if (allowDuplicate) {
  85623. selection.concat(this.entries);
  85624. }
  85625. else {
  85626. selection.concatWithNoDuplicate(this.entries);
  85627. }
  85628. }
  85629. };
  85630. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  85631. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  85632. if (this.blocks) {
  85633. for (var index = 0; index < this.blocks.length; index++) {
  85634. var block = this.blocks[index];
  85635. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  85636. }
  85637. return;
  85638. }
  85639. if (allowDuplicate) {
  85640. selection.concat(this.entries);
  85641. }
  85642. else {
  85643. selection.concatWithNoDuplicate(this.entries);
  85644. }
  85645. }
  85646. };
  85647. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  85648. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  85649. if (this.blocks) {
  85650. for (var index = 0; index < this.blocks.length; index++) {
  85651. var block = this.blocks[index];
  85652. block.intersectsRay(ray, selection);
  85653. }
  85654. return;
  85655. }
  85656. selection.concatWithNoDuplicate(this.entries);
  85657. }
  85658. };
  85659. OctreeBlock.prototype.createInnerBlocks = function () {
  85660. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  85661. };
  85662. return OctreeBlock;
  85663. }());
  85664. BABYLON.OctreeBlock = OctreeBlock;
  85665. })(BABYLON || (BABYLON = {}));
  85666. //# sourceMappingURL=babylon.octreeBlock.js.map
  85667. var BABYLON;
  85668. (function (BABYLON) {
  85669. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  85670. __extends(VRDistortionCorrectionPostProcess, _super);
  85671. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  85672. var _this = _super.call(this, name, "vrDistortionCorrection", [
  85673. 'LensCenter',
  85674. 'Scale',
  85675. 'ScaleIn',
  85676. 'HmdWarpParam'
  85677. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  85678. _this._isRightEye = isRightEye;
  85679. _this._distortionFactors = vrMetrics.distortionK;
  85680. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  85681. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  85682. _this.adaptScaleToCurrentViewport = true;
  85683. _this.onSizeChangedObservable.add(function () {
  85684. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  85685. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  85686. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  85687. });
  85688. _this.onApplyObservable.add(function (effect) {
  85689. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  85690. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  85691. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  85692. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  85693. });
  85694. return _this;
  85695. }
  85696. return VRDistortionCorrectionPostProcess;
  85697. }(BABYLON.PostProcess));
  85698. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  85699. })(BABYLON || (BABYLON = {}));
  85700. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  85701. var BABYLON;
  85702. (function (BABYLON) {
  85703. var AnaglyphPostProcess = /** @class */ (function (_super) {
  85704. __extends(AnaglyphPostProcess, _super);
  85705. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  85706. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  85707. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85708. _this.onApplyObservable.add(function (effect) {
  85709. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  85710. });
  85711. return _this;
  85712. }
  85713. return AnaglyphPostProcess;
  85714. }(BABYLON.PostProcess));
  85715. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  85716. })(BABYLON || (BABYLON = {}));
  85717. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  85718. var BABYLON;
  85719. (function (BABYLON) {
  85720. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  85721. __extends(StereoscopicInterlacePostProcess, _super);
  85722. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  85723. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  85724. _this._passedProcess = rigCameras[0]._rigPostProcess;
  85725. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85726. _this.onSizeChangedObservable.add(function () {
  85727. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  85728. });
  85729. _this.onApplyObservable.add(function (effect) {
  85730. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  85731. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  85732. });
  85733. return _this;
  85734. }
  85735. return StereoscopicInterlacePostProcess;
  85736. }(BABYLON.PostProcess));
  85737. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  85738. })(BABYLON || (BABYLON = {}));
  85739. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  85740. var BABYLON;
  85741. (function (BABYLON) {
  85742. /**
  85743. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  85744. * Screen rotation is taken into account.
  85745. */
  85746. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  85747. function FreeCameraDeviceOrientationInput() {
  85748. var _this = this;
  85749. this._screenOrientationAngle = 0;
  85750. this._screenQuaternion = new BABYLON.Quaternion();
  85751. this._alpha = 0;
  85752. this._beta = 0;
  85753. this._gamma = 0;
  85754. this._orientationChanged = function () {
  85755. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  85756. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  85757. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  85758. };
  85759. this._deviceOrientation = function (evt) {
  85760. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  85761. _this._beta = evt.beta !== null ? evt.beta : 0;
  85762. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  85763. };
  85764. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  85765. this._orientationChanged();
  85766. }
  85767. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  85768. get: function () {
  85769. return this._camera;
  85770. },
  85771. set: function (camera) {
  85772. this._camera = camera;
  85773. if (this._camera != null && !this._camera.rotationQuaternion) {
  85774. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  85775. }
  85776. },
  85777. enumerable: true,
  85778. configurable: true
  85779. });
  85780. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85781. window.addEventListener("orientationchange", this._orientationChanged);
  85782. window.addEventListener("deviceorientation", this._deviceOrientation);
  85783. //In certain cases, the attach control is called AFTER orientation was changed,
  85784. //So this is needed.
  85785. this._orientationChanged();
  85786. };
  85787. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  85788. window.removeEventListener("orientationchange", this._orientationChanged);
  85789. window.removeEventListener("deviceorientation", this._deviceOrientation);
  85790. };
  85791. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  85792. //if no device orientation provided, don't update the rotation.
  85793. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  85794. if (!this._alpha)
  85795. return;
  85796. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  85797. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  85798. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  85799. //Mirror on XY Plane
  85800. this._camera.rotationQuaternion.z *= -1;
  85801. this._camera.rotationQuaternion.w *= -1;
  85802. };
  85803. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  85804. return "FreeCameraDeviceOrientationInput";
  85805. };
  85806. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  85807. return "deviceOrientation";
  85808. };
  85809. return FreeCameraDeviceOrientationInput;
  85810. }());
  85811. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  85812. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  85813. })(BABYLON || (BABYLON = {}));
  85814. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  85815. var BABYLON;
  85816. (function (BABYLON) {
  85817. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  85818. function ArcRotateCameraVRDeviceOrientationInput() {
  85819. this.alphaCorrection = 1;
  85820. this.betaCorrection = 1;
  85821. this.gammaCorrection = 1;
  85822. this._alpha = 0;
  85823. this._gamma = 0;
  85824. this._dirty = false;
  85825. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  85826. }
  85827. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  85828. this.camera.attachControl(element, noPreventDefault);
  85829. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  85830. };
  85831. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  85832. if (evt.alpha !== null) {
  85833. this._alpha = +evt.alpha | 0;
  85834. }
  85835. if (evt.gamma !== null) {
  85836. this._gamma = +evt.gamma | 0;
  85837. }
  85838. this._dirty = true;
  85839. };
  85840. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  85841. if (this._dirty) {
  85842. this._dirty = false;
  85843. if (this._gamma < 0) {
  85844. this._gamma = 180 + this._gamma;
  85845. }
  85846. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  85847. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  85848. }
  85849. };
  85850. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  85851. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  85852. };
  85853. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  85854. return "ArcRotateCameraVRDeviceOrientationInput";
  85855. };
  85856. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  85857. return "VRDeviceOrientation";
  85858. };
  85859. return ArcRotateCameraVRDeviceOrientationInput;
  85860. }());
  85861. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  85862. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  85863. })(BABYLON || (BABYLON = {}));
  85864. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  85865. var BABYLON;
  85866. (function (BABYLON) {
  85867. var VRCameraMetrics = /** @class */ (function () {
  85868. function VRCameraMetrics() {
  85869. this.compensateDistortion = true;
  85870. }
  85871. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  85872. get: function () {
  85873. return this.hResolution / (2 * this.vResolution);
  85874. },
  85875. enumerable: true,
  85876. configurable: true
  85877. });
  85878. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  85879. get: function () {
  85880. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  85881. },
  85882. enumerable: true,
  85883. configurable: true
  85884. });
  85885. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  85886. get: function () {
  85887. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85888. var h = (4 * meters) / this.hScreenSize;
  85889. return BABYLON.Matrix.Translation(h, 0, 0);
  85890. },
  85891. enumerable: true,
  85892. configurable: true
  85893. });
  85894. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  85895. get: function () {
  85896. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  85897. var h = (4 * meters) / this.hScreenSize;
  85898. return BABYLON.Matrix.Translation(-h, 0, 0);
  85899. },
  85900. enumerable: true,
  85901. configurable: true
  85902. });
  85903. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  85904. get: function () {
  85905. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  85906. },
  85907. enumerable: true,
  85908. configurable: true
  85909. });
  85910. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  85911. get: function () {
  85912. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  85913. },
  85914. enumerable: true,
  85915. configurable: true
  85916. });
  85917. VRCameraMetrics.GetDefault = function () {
  85918. var result = new VRCameraMetrics();
  85919. result.hResolution = 1280;
  85920. result.vResolution = 800;
  85921. result.hScreenSize = 0.149759993;
  85922. result.vScreenSize = 0.0935999975;
  85923. result.vScreenCenter = 0.0467999987;
  85924. result.eyeToScreenDistance = 0.0410000011;
  85925. result.lensSeparationDistance = 0.0635000020;
  85926. result.interpupillaryDistance = 0.0640000030;
  85927. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  85928. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  85929. result.postProcessScaleFactor = 1.714605507808412;
  85930. result.lensCenterOffset = 0.151976421;
  85931. return result;
  85932. };
  85933. return VRCameraMetrics;
  85934. }());
  85935. BABYLON.VRCameraMetrics = VRCameraMetrics;
  85936. })(BABYLON || (BABYLON = {}));
  85937. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  85938. var BABYLON;
  85939. (function (BABYLON) {
  85940. /**
  85941. * This represents a WebVR camera.
  85942. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  85943. * @example http://doc.babylonjs.com/how_to/webvr_camera
  85944. */
  85945. var WebVRFreeCamera = /** @class */ (function (_super) {
  85946. __extends(WebVRFreeCamera, _super);
  85947. /**
  85948. * Instantiates a WebVRFreeCamera.
  85949. * @param name The name of the WebVRFreeCamera
  85950. * @param position The starting anchor position for the camera
  85951. * @param scene The scene the camera belongs to
  85952. * @param webVROptions a set of customizable options for the webVRCamera
  85953. */
  85954. function WebVRFreeCamera(name, position, scene, webVROptions) {
  85955. if (webVROptions === void 0) { webVROptions = {}; }
  85956. var _this = _super.call(this, name, position, scene) || this;
  85957. _this.webVROptions = webVROptions;
  85958. /**
  85959. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  85960. */
  85961. _this._vrDevice = null;
  85962. /**
  85963. * The rawPose of the vrDevice.
  85964. */
  85965. _this.rawPose = null;
  85966. _this._specsVersion = "1.1";
  85967. _this._attached = false;
  85968. _this._descendants = [];
  85969. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  85970. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  85971. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  85972. _this._standingMatrix = null;
  85973. /**
  85974. * Represents device position in babylon space.
  85975. */
  85976. _this.devicePosition = BABYLON.Vector3.Zero();
  85977. /**
  85978. * Represents device rotation in babylon space.
  85979. */
  85980. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  85981. /**
  85982. * The scale of the device to be used when translating from device space to babylon space.
  85983. */
  85984. _this.deviceScaleFactor = 1;
  85985. _this._deviceToWorld = BABYLON.Matrix.Identity();
  85986. _this._worldToDevice = BABYLON.Matrix.Identity();
  85987. /**
  85988. * References to the webVR controllers for the vrDevice.
  85989. */
  85990. _this.controllers = [];
  85991. /**
  85992. * Emits an event when a controller is attached.
  85993. */
  85994. _this.onControllersAttachedObservable = new BABYLON.Observable();
  85995. /**
  85996. * Emits an event when a controller's mesh has been loaded;
  85997. */
  85998. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  85999. /**
  86000. * If the rig cameras be used as parent instead of this camera.
  86001. */
  86002. _this.rigParenting = true;
  86003. _this._defaultHeight = undefined;
  86004. _this._workingVector = BABYLON.Vector3.Zero();
  86005. _this._oneVector = BABYLON.Vector3.One();
  86006. _this._workingMatrix = BABYLON.Matrix.Identity();
  86007. _this._cache.position = BABYLON.Vector3.Zero();
  86008. if (webVROptions.defaultHeight) {
  86009. _this._defaultHeight = webVROptions.defaultHeight;
  86010. _this.position.y = _this._defaultHeight;
  86011. }
  86012. _this.minZ = 0.1;
  86013. //legacy support - the compensation boolean was removed.
  86014. if (arguments.length === 5) {
  86015. _this.webVROptions = arguments[4];
  86016. }
  86017. // default webVR options
  86018. if (_this.webVROptions.trackPosition == undefined) {
  86019. _this.webVROptions.trackPosition = true;
  86020. }
  86021. if (_this.webVROptions.controllerMeshes == undefined) {
  86022. _this.webVROptions.controllerMeshes = true;
  86023. }
  86024. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86025. _this.webVROptions.defaultLightingOnControllers = true;
  86026. }
  86027. _this.rotationQuaternion = new BABYLON.Quaternion();
  86028. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86029. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86030. }
  86031. //enable VR
  86032. var engine = _this.getEngine();
  86033. _this._onVREnabled = function (success) { if (success) {
  86034. _this.initControllers();
  86035. } };
  86036. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86037. engine.initWebVR().add(function (event) {
  86038. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86039. return;
  86040. }
  86041. _this._vrDevice = event.vrDisplay;
  86042. //reset the rig parameters.
  86043. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86044. if (_this._attached) {
  86045. _this.getEngine().enableVR();
  86046. }
  86047. });
  86048. if (typeof (VRFrameData) !== "undefined")
  86049. _this._frameData = new VRFrameData();
  86050. /**
  86051. * The idea behind the following lines:
  86052. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86053. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86054. * the second will not show it correctly.
  86055. *
  86056. * To solve this - each object that has the camera as parent will be added to a protected array.
  86057. * When the rig camera renders, it will take this array and set all of those to be its children.
  86058. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86059. * Amazing!
  86060. */
  86061. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86062. if (camera.parent === _this && _this.rigParenting) {
  86063. _this._descendants = _this.getDescendants(true, function (n) {
  86064. // don't take the cameras or the controllers!
  86065. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86066. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86067. return !isController && !isRigCamera;
  86068. });
  86069. _this._descendants.forEach(function (node) {
  86070. node.parent = camera;
  86071. });
  86072. }
  86073. });
  86074. scene.onAfterCameraRenderObservable.add(function (camera) {
  86075. if (camera.parent === _this && _this.rigParenting) {
  86076. _this._descendants.forEach(function (node) {
  86077. node.parent = _this;
  86078. });
  86079. }
  86080. });
  86081. return _this;
  86082. }
  86083. /**
  86084. * Gets the device distance from the ground in meters.
  86085. * @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.
  86086. */
  86087. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86088. if (this._standingMatrix) {
  86089. // Add standing matrix offset to get real offset from ground in room
  86090. this._standingMatrix.getTranslationToRef(this._workingVector);
  86091. return this._deviceRoomPosition.y + this._workingVector.y;
  86092. }
  86093. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86094. return this._defaultHeight || 0;
  86095. };
  86096. /**
  86097. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86098. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86099. */
  86100. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86101. var _this = this;
  86102. if (callback === void 0) { callback = function (bool) { }; }
  86103. // Use standing matrix if available
  86104. this.getEngine().initWebVRAsync().then(function (result) {
  86105. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86106. callback(false);
  86107. }
  86108. else {
  86109. _this._standingMatrix = new BABYLON.Matrix();
  86110. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86111. if (!_this.getScene().useRightHandedSystem) {
  86112. [2, 6, 8, 9, 14].forEach(function (num) {
  86113. if (_this._standingMatrix) {
  86114. _this._standingMatrix.m[num] *= -1;
  86115. }
  86116. });
  86117. }
  86118. callback(true);
  86119. }
  86120. });
  86121. };
  86122. /**
  86123. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86124. * @returns A promise with a boolean set to if the standing matrix is supported.
  86125. */
  86126. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86127. var _this = this;
  86128. return new Promise(function (res, rej) {
  86129. _this.useStandingMatrix(function (supported) {
  86130. res(supported);
  86131. });
  86132. });
  86133. };
  86134. /**
  86135. * Disposes the camera
  86136. */
  86137. WebVRFreeCamera.prototype.dispose = function () {
  86138. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86139. _super.prototype.dispose.call(this);
  86140. };
  86141. /**
  86142. * Gets a vrController by name.
  86143. * @param name The name of the controller to retreive
  86144. * @returns the controller matching the name specified or null if not found
  86145. */
  86146. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86147. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86148. var gp = _a[_i];
  86149. if (gp.hand === name) {
  86150. return gp;
  86151. }
  86152. }
  86153. return null;
  86154. };
  86155. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86156. /**
  86157. * The controller corrisponding to the users left hand.
  86158. */
  86159. get: function () {
  86160. if (!this._leftController) {
  86161. this._leftController = this.getControllerByName("left");
  86162. }
  86163. return this._leftController;
  86164. },
  86165. enumerable: true,
  86166. configurable: true
  86167. });
  86168. ;
  86169. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86170. /**
  86171. * The controller corrisponding to the users right hand.
  86172. */
  86173. get: function () {
  86174. if (!this._rightController) {
  86175. this._rightController = this.getControllerByName("right");
  86176. }
  86177. return this._rightController;
  86178. },
  86179. enumerable: true,
  86180. configurable: true
  86181. });
  86182. ;
  86183. /**
  86184. * Casts a ray forward from the vrCamera's gaze.
  86185. * @param length Length of the ray (default: 100)
  86186. * @returns the ray corrisponding to the gaze
  86187. */
  86188. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86189. if (length === void 0) { length = 100; }
  86190. if (this.leftCamera) {
  86191. // Use left eye to avoid computation to compute center on every call
  86192. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86193. }
  86194. else {
  86195. return _super.prototype.getForwardRay.call(this, length);
  86196. }
  86197. };
  86198. /**
  86199. * Updates the camera based on device's frame data
  86200. */
  86201. WebVRFreeCamera.prototype._checkInputs = function () {
  86202. if (this._vrDevice && this._vrDevice.isPresenting) {
  86203. this._vrDevice.getFrameData(this._frameData);
  86204. this.updateFromDevice(this._frameData.pose);
  86205. }
  86206. _super.prototype._checkInputs.call(this);
  86207. };
  86208. /**
  86209. * Updates the poseControlled values based on the input device pose.
  86210. * @param poseData Pose coming from the device
  86211. */
  86212. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86213. if (poseData && poseData.orientation) {
  86214. this.rawPose = poseData;
  86215. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86216. if (this.getScene().useRightHandedSystem) {
  86217. this._deviceRoomRotationQuaternion.z *= -1;
  86218. this._deviceRoomRotationQuaternion.w *= -1;
  86219. }
  86220. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86221. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86222. if (this.getScene().useRightHandedSystem) {
  86223. this._deviceRoomPosition.z *= -1;
  86224. }
  86225. }
  86226. }
  86227. };
  86228. /**
  86229. * WebVR's attach control will start broadcasting frames to the device.
  86230. * Note that in certain browsers (chrome for example) this function must be called
  86231. * within a user-interaction callback. Example:
  86232. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86233. *
  86234. * @param element html element to attach the vrDevice to
  86235. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86236. */
  86237. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86238. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86239. this._attached = true;
  86240. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86241. if (this._vrDevice) {
  86242. this.getEngine().enableVR();
  86243. }
  86244. };
  86245. /**
  86246. * Detaches the camera from the html element and disables VR
  86247. *
  86248. * @param element html element to detach from
  86249. */
  86250. WebVRFreeCamera.prototype.detachControl = function (element) {
  86251. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86252. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86253. _super.prototype.detachControl.call(this, element);
  86254. this._attached = false;
  86255. this.getEngine().disableVR();
  86256. };
  86257. /**
  86258. * @returns the name of this class
  86259. */
  86260. WebVRFreeCamera.prototype.getClassName = function () {
  86261. return "WebVRFreeCamera";
  86262. };
  86263. /**
  86264. * Calls resetPose on the vrDisplay
  86265. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86266. */
  86267. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86268. //uses the vrDisplay's "resetPose()".
  86269. //pitch and roll won't be affected.
  86270. this._vrDevice.resetPose();
  86271. };
  86272. /**
  86273. * Updates the rig cameras (left and right eye)
  86274. */
  86275. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86276. var camLeft = this._rigCameras[0];
  86277. var camRight = this._rigCameras[1];
  86278. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86279. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86280. camLeft.position.copyFrom(this._deviceRoomPosition);
  86281. camRight.position.copyFrom(this._deviceRoomPosition);
  86282. };
  86283. /**
  86284. * Updates the cached values of the camera
  86285. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86286. */
  86287. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86288. var _this = this;
  86289. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86290. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86291. if (!this.updateCacheCalled) {
  86292. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86293. this.updateCacheCalled = true;
  86294. this.update();
  86295. }
  86296. // Set working vector to the device position in room space rotated by the new rotation
  86297. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86298. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86299. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86300. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86301. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86302. // Add translation from anchor position
  86303. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86304. this._workingVector.addInPlace(this.position);
  86305. this._workingVector.subtractInPlace(this._cache.position);
  86306. this._deviceToWorld.setTranslation(this._workingVector);
  86307. // Set an inverted matrix to be used when updating the camera
  86308. this._deviceToWorld.invertToRef(this._worldToDevice);
  86309. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86310. this.controllers.forEach(function (controller) {
  86311. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86312. controller.update();
  86313. });
  86314. }
  86315. if (!ignoreParentClass) {
  86316. _super.prototype._updateCache.call(this);
  86317. }
  86318. this.updateCacheCalled = false;
  86319. };
  86320. /**
  86321. * Updates the current device position and rotation in the babylon world
  86322. */
  86323. WebVRFreeCamera.prototype.update = function () {
  86324. // Get current device position in babylon world
  86325. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86326. // Get current device rotation in babylon world
  86327. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86328. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86329. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86330. _super.prototype.update.call(this);
  86331. };
  86332. /**
  86333. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86334. * @returns an identity matrix
  86335. */
  86336. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86337. return BABYLON.Matrix.Identity();
  86338. };
  86339. /**
  86340. * This function is called by the two RIG cameras.
  86341. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86342. */
  86343. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86344. var _this = this;
  86345. // Update the parent camera prior to using a child camera to avoid desynchronization
  86346. var parentCamera = this._cameraRigParams["parentCamera"];
  86347. parentCamera._updateCache();
  86348. //WebVR 1.1
  86349. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86350. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86351. if (!this.getScene().useRightHandedSystem) {
  86352. [2, 6, 8, 9, 14].forEach(function (num) {
  86353. _this._webvrViewMatrix.m[num] *= -1;
  86354. });
  86355. }
  86356. // update the camera rotation matrix
  86357. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86358. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86359. // Computing target and final matrix
  86360. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86361. // should the view matrix be updated with scale and position offset?
  86362. if (parentCamera.deviceScaleFactor !== 1) {
  86363. this._webvrViewMatrix.invert();
  86364. // scale the position, if set
  86365. if (parentCamera.deviceScaleFactor) {
  86366. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86367. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86368. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86369. }
  86370. this._webvrViewMatrix.invert();
  86371. }
  86372. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86373. return this._webvrViewMatrix;
  86374. };
  86375. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86376. var _this = this;
  86377. var parentCamera = this.parent;
  86378. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86379. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86380. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86381. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86382. //babylon compatible matrix
  86383. if (!this.getScene().useRightHandedSystem) {
  86384. [8, 9, 10, 11].forEach(function (num) {
  86385. _this._projectionMatrix.m[num] *= -1;
  86386. });
  86387. }
  86388. return this._projectionMatrix;
  86389. };
  86390. /**
  86391. * Initializes the controllers and their meshes
  86392. */
  86393. WebVRFreeCamera.prototype.initControllers = function () {
  86394. var _this = this;
  86395. this.controllers = [];
  86396. var manager = this.getScene().gamepadManager;
  86397. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86398. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86399. var webVrController = gamepad;
  86400. if (webVrController.defaultModel) {
  86401. webVrController.defaultModel.setEnabled(false);
  86402. }
  86403. if (webVrController.hand === "right") {
  86404. _this._rightController = null;
  86405. }
  86406. if (webVrController.hand === "left") {
  86407. _this._leftController = null;
  86408. }
  86409. var controllerIndex = _this.controllers.indexOf(webVrController);
  86410. if (controllerIndex !== -1) {
  86411. _this.controllers.splice(controllerIndex, 1);
  86412. }
  86413. }
  86414. });
  86415. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86416. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86417. var webVrController_1 = gamepad;
  86418. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86419. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86420. if (_this.webVROptions.controllerMeshes) {
  86421. if (webVrController_1.defaultModel) {
  86422. webVrController_1.defaultModel.setEnabled(true);
  86423. }
  86424. else {
  86425. // Load the meshes
  86426. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86427. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86428. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86429. if (_this.webVROptions.defaultLightingOnControllers) {
  86430. if (!_this._lightOnControllers) {
  86431. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86432. }
  86433. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86434. var children = mesh.getChildren();
  86435. if (children.length !== 0) {
  86436. children.forEach(function (mesh) {
  86437. light.includedOnlyMeshes.push(mesh);
  86438. activateLightOnSubMeshes_1(mesh, light);
  86439. });
  86440. }
  86441. };
  86442. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86443. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86444. }
  86445. });
  86446. }
  86447. }
  86448. webVrController_1.attachToPoseControlledCamera(_this);
  86449. // since this is async - sanity check. Is the controller already stored?
  86450. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86451. //add to the controllers array
  86452. _this.controllers.push(webVrController_1);
  86453. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86454. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86455. // So we're overriding setting left & right manually to be sure
  86456. var firstViveWandDetected = false;
  86457. for (var i = 0; i < _this.controllers.length; i++) {
  86458. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86459. if (!firstViveWandDetected) {
  86460. firstViveWandDetected = true;
  86461. _this.controllers[i].hand = "left";
  86462. }
  86463. else {
  86464. _this.controllers[i].hand = "right";
  86465. }
  86466. }
  86467. }
  86468. //did we find enough controllers? Great! let the developer know.
  86469. if (_this.controllers.length >= 2) {
  86470. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86471. }
  86472. }
  86473. }
  86474. });
  86475. };
  86476. return WebVRFreeCamera;
  86477. }(BABYLON.FreeCamera));
  86478. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86479. })(BABYLON || (BABYLON = {}));
  86480. //# sourceMappingURL=babylon.webVRCamera.js.map
  86481. var BABYLON;
  86482. (function (BABYLON) {
  86483. // We're mainly based on the logic defined into the FreeCamera code
  86484. /**
  86485. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86486. * being tilted forward or back and left or right.
  86487. */
  86488. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86489. __extends(DeviceOrientationCamera, _super);
  86490. /**
  86491. * Creates a new device orientation camera
  86492. * @param name The name of the camera
  86493. * @param position The start position camera
  86494. * @param scene The scene the camera belongs to
  86495. */
  86496. function DeviceOrientationCamera(name, position, scene) {
  86497. var _this = _super.call(this, name, position, scene) || this;
  86498. _this._quaternionCache = new BABYLON.Quaternion();
  86499. _this.inputs.addDeviceOrientation();
  86500. return _this;
  86501. }
  86502. /**
  86503. * Gets the current instance class name ("DeviceOrientationCamera").
  86504. * This helps avoiding instanceof at run time.
  86505. * @returns the class name
  86506. */
  86507. DeviceOrientationCamera.prototype.getClassName = function () {
  86508. return "DeviceOrientationCamera";
  86509. };
  86510. /**
  86511. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86512. */
  86513. DeviceOrientationCamera.prototype._checkInputs = function () {
  86514. _super.prototype._checkInputs.call(this);
  86515. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86516. if (this._initialQuaternion) {
  86517. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86518. }
  86519. };
  86520. /**
  86521. * Reset the camera to its default orientation on the specified axis only.
  86522. * @param axis The axis to reset
  86523. */
  86524. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86525. var _this = this;
  86526. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86527. //can only work if this camera has a rotation quaternion already.
  86528. if (!this.rotationQuaternion)
  86529. return;
  86530. if (!this._initialQuaternion) {
  86531. this._initialQuaternion = new BABYLON.Quaternion();
  86532. }
  86533. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86534. ['x', 'y', 'z'].forEach(function (axisName) {
  86535. if (!axis[axisName]) {
  86536. _this._initialQuaternion[axisName] = 0;
  86537. }
  86538. else {
  86539. _this._initialQuaternion[axisName] *= -1;
  86540. }
  86541. });
  86542. this._initialQuaternion.normalize();
  86543. //force rotation update
  86544. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86545. };
  86546. return DeviceOrientationCamera;
  86547. }(BABYLON.FreeCamera));
  86548. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86549. })(BABYLON || (BABYLON = {}));
  86550. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86551. var BABYLON;
  86552. (function (BABYLON) {
  86553. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86554. __extends(VRDeviceOrientationFreeCamera, _super);
  86555. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86556. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86557. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86558. var _this = _super.call(this, name, position, scene) || this;
  86559. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86560. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86561. return _this;
  86562. }
  86563. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86564. return "VRDeviceOrientationFreeCamera";
  86565. };
  86566. return VRDeviceOrientationFreeCamera;
  86567. }(BABYLON.DeviceOrientationCamera));
  86568. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86569. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86570. __extends(VRDeviceOrientationGamepadCamera, _super);
  86571. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86572. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86573. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86574. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86575. _this.inputs.addGamepad();
  86576. return _this;
  86577. }
  86578. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86579. return "VRDeviceOrientationGamepadCamera";
  86580. };
  86581. return VRDeviceOrientationGamepadCamera;
  86582. }(VRDeviceOrientationFreeCamera));
  86583. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86584. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86585. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86586. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86587. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86588. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86589. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86590. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86591. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86592. _this.inputs.addVRDeviceOrientation();
  86593. return _this;
  86594. }
  86595. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86596. return "VRDeviceOrientationArcRotateCamera";
  86597. };
  86598. return VRDeviceOrientationArcRotateCamera;
  86599. }(BABYLON.ArcRotateCamera));
  86600. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  86601. })(BABYLON || (BABYLON = {}));
  86602. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  86603. var BABYLON;
  86604. (function (BABYLON) {
  86605. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  86606. __extends(AnaglyphFreeCamera, _super);
  86607. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  86608. var _this = _super.call(this, name, position, scene) || this;
  86609. _this.interaxialDistance = interaxialDistance;
  86610. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86611. return _this;
  86612. }
  86613. AnaglyphFreeCamera.prototype.getClassName = function () {
  86614. return "AnaglyphFreeCamera";
  86615. };
  86616. return AnaglyphFreeCamera;
  86617. }(BABYLON.FreeCamera));
  86618. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  86619. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  86620. __extends(AnaglyphArcRotateCamera, _super);
  86621. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  86622. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86623. _this.interaxialDistance = interaxialDistance;
  86624. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86625. return _this;
  86626. }
  86627. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  86628. return "AnaglyphArcRotateCamera";
  86629. };
  86630. return AnaglyphArcRotateCamera;
  86631. }(BABYLON.ArcRotateCamera));
  86632. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  86633. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  86634. __extends(AnaglyphGamepadCamera, _super);
  86635. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  86636. var _this = _super.call(this, name, position, scene) || this;
  86637. _this.interaxialDistance = interaxialDistance;
  86638. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86639. return _this;
  86640. }
  86641. AnaglyphGamepadCamera.prototype.getClassName = function () {
  86642. return "AnaglyphGamepadCamera";
  86643. };
  86644. return AnaglyphGamepadCamera;
  86645. }(BABYLON.GamepadCamera));
  86646. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  86647. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  86648. __extends(AnaglyphUniversalCamera, _super);
  86649. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  86650. var _this = _super.call(this, name, position, scene) || this;
  86651. _this.interaxialDistance = interaxialDistance;
  86652. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86653. return _this;
  86654. }
  86655. AnaglyphUniversalCamera.prototype.getClassName = function () {
  86656. return "AnaglyphUniversalCamera";
  86657. };
  86658. return AnaglyphUniversalCamera;
  86659. }(BABYLON.UniversalCamera));
  86660. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  86661. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  86662. __extends(StereoscopicFreeCamera, _super);
  86663. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86664. var _this = _super.call(this, name, position, scene) || this;
  86665. _this.interaxialDistance = interaxialDistance;
  86666. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86667. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86668. return _this;
  86669. }
  86670. StereoscopicFreeCamera.prototype.getClassName = function () {
  86671. return "StereoscopicFreeCamera";
  86672. };
  86673. return StereoscopicFreeCamera;
  86674. }(BABYLON.FreeCamera));
  86675. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  86676. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  86677. __extends(StereoscopicArcRotateCamera, _super);
  86678. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  86679. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86680. _this.interaxialDistance = interaxialDistance;
  86681. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86682. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86683. return _this;
  86684. }
  86685. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  86686. return "StereoscopicArcRotateCamera";
  86687. };
  86688. return StereoscopicArcRotateCamera;
  86689. }(BABYLON.ArcRotateCamera));
  86690. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  86691. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  86692. __extends(StereoscopicGamepadCamera, _super);
  86693. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86694. var _this = _super.call(this, name, position, scene) || this;
  86695. _this.interaxialDistance = interaxialDistance;
  86696. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86697. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86698. return _this;
  86699. }
  86700. StereoscopicGamepadCamera.prototype.getClassName = function () {
  86701. return "StereoscopicGamepadCamera";
  86702. };
  86703. return StereoscopicGamepadCamera;
  86704. }(BABYLON.GamepadCamera));
  86705. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  86706. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  86707. __extends(StereoscopicUniversalCamera, _super);
  86708. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  86709. var _this = _super.call(this, name, position, scene) || this;
  86710. _this.interaxialDistance = interaxialDistance;
  86711. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  86712. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  86713. return _this;
  86714. }
  86715. StereoscopicUniversalCamera.prototype.getClassName = function () {
  86716. return "StereoscopicUniversalCamera";
  86717. };
  86718. return StereoscopicUniversalCamera;
  86719. }(BABYLON.UniversalCamera));
  86720. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  86721. })(BABYLON || (BABYLON = {}));
  86722. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  86723. var BABYLON;
  86724. (function (BABYLON) {
  86725. var VRExperienceHelperGazer = /** @class */ (function () {
  86726. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  86727. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  86728. this.scene = scene;
  86729. this._pointerDownOnMeshAsked = false;
  86730. this._isActionableMesh = false;
  86731. this._teleportationRequestInitiated = false;
  86732. this._teleportationBackRequestInitiated = false;
  86733. this._dpadPressed = true;
  86734. this._activePointer = false;
  86735. this._id = VRExperienceHelperGazer._idCounter++;
  86736. // Gaze tracker
  86737. if (!gazeTrackerToClone) {
  86738. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  86739. this._gazeTracker.bakeCurrentTransformIntoVertices();
  86740. this._gazeTracker.isPickable = false;
  86741. this._gazeTracker.isVisible = false;
  86742. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  86743. targetMat.specularColor = BABYLON.Color3.Black();
  86744. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86745. targetMat.backFaceCulling = false;
  86746. this._gazeTracker.material = targetMat;
  86747. }
  86748. else {
  86749. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  86750. }
  86751. }
  86752. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  86753. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  86754. };
  86755. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  86756. this._pointerDownOnMeshAsked = true;
  86757. if (this._currentMeshSelected && this._currentHit) {
  86758. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  86759. }
  86760. };
  86761. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  86762. if (this._currentMeshSelected && this._currentHit) {
  86763. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  86764. }
  86765. this._pointerDownOnMeshAsked = false;
  86766. };
  86767. VRExperienceHelperGazer.prototype._activatePointer = function () {
  86768. this._activePointer = true;
  86769. };
  86770. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  86771. this._activePointer = false;
  86772. };
  86773. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  86774. };
  86775. VRExperienceHelperGazer.prototype.dispose = function () {
  86776. this._interactionsEnabled = false;
  86777. this._teleportationEnabled = false;
  86778. };
  86779. VRExperienceHelperGazer._idCounter = 0;
  86780. return VRExperienceHelperGazer;
  86781. }());
  86782. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  86783. __extends(VRExperienceHelperControllerGazer, _super);
  86784. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  86785. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  86786. _this.webVRController = webVRController;
  86787. // Laser pointer
  86788. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  86789. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  86790. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  86791. laserPointerMaterial.alpha = 0.6;
  86792. _this._laserPointer.material = laserPointerMaterial;
  86793. _this._laserPointer.rotation.x = Math.PI / 2;
  86794. _this._laserPointer.position.z = -0.5;
  86795. _this._laserPointer.isVisible = false;
  86796. if (!webVRController.mesh) {
  86797. // Create an empty mesh that is used prior to loading the high quality model
  86798. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  86799. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  86800. preloadPointerPose.rotation.x = -0.7;
  86801. preloadMesh.addChild(preloadPointerPose);
  86802. webVRController.attachToMesh(preloadMesh);
  86803. }
  86804. _this._setLaserPointerParent(webVRController.mesh);
  86805. return _this;
  86806. }
  86807. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  86808. return this.webVRController.getForwardRay(length);
  86809. };
  86810. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  86811. _super.prototype._activatePointer.call(this);
  86812. this._laserPointer.isVisible = true;
  86813. };
  86814. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  86815. _super.prototype._deactivatePointer.call(this);
  86816. this._laserPointer.isVisible = false;
  86817. };
  86818. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  86819. this._laserPointer.material.emissiveColor = color;
  86820. };
  86821. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  86822. var makeNotPick = function (root) {
  86823. root.name += " laserPointer";
  86824. root.getChildMeshes().forEach(function (c) {
  86825. makeNotPick(c);
  86826. });
  86827. };
  86828. makeNotPick(mesh);
  86829. var childMeshes = mesh.getChildMeshes();
  86830. this.webVRController._pointingPoseNode = null;
  86831. for (var i = 0; i < childMeshes.length; i++) {
  86832. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  86833. mesh = childMeshes[i];
  86834. this.webVRController._pointingPoseNode = mesh;
  86835. break;
  86836. }
  86837. }
  86838. this._laserPointer.parent = mesh;
  86839. };
  86840. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  86841. this._laserPointer.scaling.y = distance;
  86842. this._laserPointer.position.z = -distance / 2;
  86843. };
  86844. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  86845. _super.prototype.dispose.call(this);
  86846. this._laserPointer.dispose();
  86847. };
  86848. return VRExperienceHelperControllerGazer;
  86849. }(VRExperienceHelperGazer));
  86850. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  86851. __extends(VRExperienceHelperCameraGazer, _super);
  86852. function VRExperienceHelperCameraGazer(getCamera, scene) {
  86853. var _this = _super.call(this, scene) || this;
  86854. _this.getCamera = getCamera;
  86855. return _this;
  86856. }
  86857. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  86858. var camera = this.getCamera();
  86859. if (camera) {
  86860. return camera.getForwardRay(length);
  86861. }
  86862. else {
  86863. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  86864. }
  86865. };
  86866. return VRExperienceHelperCameraGazer;
  86867. }(VRExperienceHelperGazer));
  86868. /**
  86869. * Helps to quickly add VR support to an existing scene.
  86870. * See http://doc.babylonjs.com/how_to/webvr_helper
  86871. */
  86872. var VRExperienceHelper = /** @class */ (function () {
  86873. /**
  86874. * Instantiates a VRExperienceHelper.
  86875. * Helps to quickly add VR support to an existing scene.
  86876. * @param scene The scene the VRExperienceHelper belongs to.
  86877. * @param webVROptions Options to modify the vr experience helper's behavior.
  86878. */
  86879. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  86880. if (webVROptions === void 0) { webVROptions = {}; }
  86881. var _this = this;
  86882. this.webVROptions = webVROptions;
  86883. // Can the system support WebVR, even if a headset isn't plugged in?
  86884. this._webVRsupported = false;
  86885. // If WebVR is supported, is a headset plugged in and are we ready to present?
  86886. this._webVRready = false;
  86887. // Are we waiting for the requestPresent callback to complete?
  86888. this._webVRrequesting = false;
  86889. // Are we presenting to the headset right now?
  86890. this._webVRpresenting = false;
  86891. // Are we presenting in the fullscreen fallback?
  86892. this._fullscreenVRpresenting = false;
  86893. /**
  86894. * Observable raised when entering VR.
  86895. */
  86896. this.onEnteringVRObservable = new BABYLON.Observable();
  86897. /**
  86898. * Observable raised when exiting VR.
  86899. */
  86900. this.onExitingVRObservable = new BABYLON.Observable();
  86901. /**
  86902. * Observable raised when controller mesh is loaded.
  86903. */
  86904. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86905. this._useCustomVRButton = false;
  86906. this._teleportationRequested = false;
  86907. this._teleportActive = false;
  86908. this._floorMeshesCollection = [];
  86909. this._rotationAllowed = true;
  86910. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  86911. this._rotationRightAsked = false;
  86912. this._rotationLeftAsked = false;
  86913. this._isDefaultTeleportationTarget = true;
  86914. this._teleportationFillColor = "#444444";
  86915. this._teleportationBorderColor = "#FFFFFF";
  86916. this._rotationAngle = 0;
  86917. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  86918. this._padSensibilityUp = 0.65;
  86919. this._padSensibilityDown = 0.35;
  86920. this.leftController = null;
  86921. this.rightController = null;
  86922. /**
  86923. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  86924. */
  86925. this.onNewMeshSelected = new BABYLON.Observable();
  86926. /**
  86927. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  86928. */
  86929. this.onNewMeshPicked = new BABYLON.Observable();
  86930. /**
  86931. * Observable raised before camera teleportation
  86932. */
  86933. this.onBeforeCameraTeleport = new BABYLON.Observable();
  86934. /**
  86935. * Observable raised after camera teleportation
  86936. */
  86937. this.onAfterCameraTeleport = new BABYLON.Observable();
  86938. /**
  86939. * Observable raised when current selected mesh gets unselected
  86940. */
  86941. this.onSelectedMeshUnselected = new BABYLON.Observable();
  86942. /**
  86943. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  86944. */
  86945. this.teleportationEnabled = true;
  86946. this._teleportationInitialized = false;
  86947. this._interactionsEnabled = false;
  86948. this._interactionsRequested = false;
  86949. this._displayGaze = true;
  86950. this._displayLaserPointer = true;
  86951. this._onResize = function () {
  86952. _this.moveButtonToBottomRight();
  86953. if (_this._fullscreenVRpresenting && _this._webVRready) {
  86954. _this.exitVR();
  86955. }
  86956. };
  86957. this._onFullscreenChange = function () {
  86958. if (document.fullscreen !== undefined) {
  86959. _this._fullscreenVRpresenting = document.fullscreen;
  86960. }
  86961. else if (document.mozFullScreen !== undefined) {
  86962. _this._fullscreenVRpresenting = document.mozFullScreen;
  86963. }
  86964. else if (document.webkitIsFullScreen !== undefined) {
  86965. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  86966. }
  86967. else if (document.msIsFullScreen !== undefined) {
  86968. _this._fullscreenVRpresenting = document.msIsFullScreen;
  86969. }
  86970. if (!_this._fullscreenVRpresenting && _this._canvas) {
  86971. _this.exitVR();
  86972. if (!_this._useCustomVRButton) {
  86973. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  86974. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  86975. }
  86976. }
  86977. };
  86978. this.beforeRender = function () {
  86979. if (_this.leftController && _this.leftController._activePointer) {
  86980. _this._castRayAndSelectObject(_this.leftController);
  86981. }
  86982. if (_this.rightController && _this.rightController._activePointer) {
  86983. _this._castRayAndSelectObject(_this.rightController);
  86984. }
  86985. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  86986. _this._castRayAndSelectObject(_this._cameraGazer);
  86987. }
  86988. else {
  86989. _this._cameraGazer._gazeTracker.isVisible = false;
  86990. }
  86991. };
  86992. this._onNewGamepadConnected = function (gamepad) {
  86993. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  86994. if (gamepad.leftStick) {
  86995. gamepad.onleftstickchanged(function (stickValues) {
  86996. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  86997. // Listening to classic/xbox gamepad only if no VR controller is active
  86998. if ((!_this.leftController && !_this.rightController) ||
  86999. ((_this.leftController && !_this.leftController._activePointer) &&
  87000. (_this.rightController && !_this.rightController._activePointer))) {
  87001. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87002. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87003. }
  87004. }
  87005. });
  87006. }
  87007. if (gamepad.rightStick) {
  87008. gamepad.onrightstickchanged(function (stickValues) {
  87009. if (_this._teleportationInitialized) {
  87010. _this._checkRotate(stickValues, _this._cameraGazer);
  87011. }
  87012. });
  87013. }
  87014. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87015. gamepad.onbuttondown(function (buttonPressed) {
  87016. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87017. _this._cameraGazer._selectionPointerDown();
  87018. }
  87019. });
  87020. gamepad.onbuttonup(function (buttonPressed) {
  87021. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87022. _this._cameraGazer._selectionPointerUp();
  87023. }
  87024. });
  87025. }
  87026. }
  87027. else {
  87028. var webVRController = gamepad;
  87029. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87030. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87031. _this.rightController = controller;
  87032. }
  87033. else {
  87034. _this.leftController = controller;
  87035. }
  87036. _this._tryEnableInteractionOnController(controller);
  87037. }
  87038. };
  87039. // 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
  87040. this._tryEnableInteractionOnController = function (controller) {
  87041. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87042. _this._enableInteractionOnController(controller);
  87043. }
  87044. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87045. _this._enableTeleportationOnController(controller);
  87046. }
  87047. };
  87048. this._onNewGamepadDisconnected = function (gamepad) {
  87049. if (gamepad instanceof BABYLON.WebVRController) {
  87050. if (gamepad.hand === "left" && _this.leftController != null) {
  87051. _this.leftController.dispose();
  87052. _this.leftController = null;
  87053. }
  87054. if (gamepad.hand === "right" && _this.rightController != null) {
  87055. _this.rightController.dispose();
  87056. _this.rightController = null;
  87057. }
  87058. }
  87059. };
  87060. this._workingVector = BABYLON.Vector3.Zero();
  87061. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87062. this._workingMatrix = BABYLON.Matrix.Identity();
  87063. this._scene = scene;
  87064. this._canvas = scene.getEngine().getRenderingCanvas();
  87065. // Parse options
  87066. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87067. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87068. }
  87069. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87070. webVROptions.createDeviceOrientationCamera = true;
  87071. }
  87072. if (webVROptions.defaultHeight === undefined) {
  87073. webVROptions.defaultHeight = 1.7;
  87074. }
  87075. if (webVROptions.useCustomVRButton) {
  87076. this._useCustomVRButton = true;
  87077. if (webVROptions.customVRButton) {
  87078. this._btnVR = webVROptions.customVRButton;
  87079. }
  87080. }
  87081. if (webVROptions.rayLength) {
  87082. this._rayLength = webVROptions.rayLength;
  87083. }
  87084. this._defaultHeight = webVROptions.defaultHeight;
  87085. if (webVROptions.positionScale) {
  87086. this._rayLength *= webVROptions.positionScale;
  87087. this._defaultHeight *= webVROptions.positionScale;
  87088. }
  87089. // Set position
  87090. if (this._scene.activeCamera) {
  87091. this._position = this._scene.activeCamera.position.clone();
  87092. }
  87093. else {
  87094. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87095. }
  87096. // Set non-vr camera
  87097. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87098. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87099. // Copy data from existing camera
  87100. if (this._scene.activeCamera) {
  87101. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87102. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87103. // Set rotation from previous camera
  87104. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87105. var targetCamera = this._scene.activeCamera;
  87106. if (targetCamera.rotationQuaternion) {
  87107. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87108. }
  87109. else {
  87110. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87111. }
  87112. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87113. }
  87114. }
  87115. this._scene.activeCamera = this._deviceOrientationCamera;
  87116. if (this._canvas) {
  87117. this._scene.activeCamera.attachControl(this._canvas);
  87118. }
  87119. }
  87120. else {
  87121. this._existingCamera = this._scene.activeCamera;
  87122. }
  87123. // Create VR cameras
  87124. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87125. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87126. }
  87127. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87128. this._webVRCamera.useStandingMatrix();
  87129. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87130. // Create default button
  87131. if (!this._useCustomVRButton) {
  87132. this._btnVR = document.createElement("BUTTON");
  87133. this._btnVR.className = "babylonVRicon";
  87134. this._btnVR.id = "babylonVRiconbtn";
  87135. this._btnVR.title = "Click to switch to VR";
  87136. 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) }";
  87137. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87138. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87139. // css += ".babylonVRicon.vrdisplaysupported { }";
  87140. // css += ".babylonVRicon.vrdisplayready { }";
  87141. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87142. var style = document.createElement('style');
  87143. style.appendChild(document.createTextNode(css));
  87144. document.getElementsByTagName('head')[0].appendChild(style);
  87145. this.moveButtonToBottomRight();
  87146. }
  87147. // VR button click event
  87148. if (this._btnVR) {
  87149. this._btnVR.addEventListener("click", function () {
  87150. if (!_this.isInVRMode) {
  87151. _this.enterVR();
  87152. }
  87153. else {
  87154. _this.exitVR();
  87155. }
  87156. });
  87157. }
  87158. // Window events
  87159. window.addEventListener("resize", this._onResize);
  87160. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87161. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87162. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87163. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87164. // Display vr button when headset is connected
  87165. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87166. this.displayVRButton();
  87167. }
  87168. else {
  87169. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87170. if (e.vrDisplay) {
  87171. _this.displayVRButton();
  87172. }
  87173. });
  87174. }
  87175. // Exiting VR mode using 'ESC' key on desktop
  87176. this._onKeyDown = function (event) {
  87177. if (event.keyCode === 27 && _this.isInVRMode) {
  87178. _this.exitVR();
  87179. }
  87180. };
  87181. document.addEventListener("keydown", this._onKeyDown);
  87182. // Exiting VR mode double tapping the touch screen
  87183. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87184. if (_this.isInVRMode) {
  87185. _this.exitVR();
  87186. if (_this._fullscreenVRpresenting) {
  87187. _this._scene.getEngine().switchFullscreen(true);
  87188. }
  87189. }
  87190. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87191. // Listen for WebVR display changes
  87192. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87193. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87194. this._onVRRequestPresentStart = function () {
  87195. _this._webVRrequesting = true;
  87196. _this.updateButtonVisibility();
  87197. };
  87198. this._onVRRequestPresentComplete = function (success) {
  87199. _this._webVRrequesting = false;
  87200. _this.updateButtonVisibility();
  87201. };
  87202. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87203. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87204. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87205. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87206. scene.onDisposeObservable.add(function () {
  87207. _this.dispose();
  87208. });
  87209. // Gamepad connection events
  87210. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87211. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87212. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87213. this.updateButtonVisibility();
  87214. //create easing functions
  87215. this._circleEase = new BABYLON.CircleEase();
  87216. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87217. }
  87218. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87219. /** Return this.onEnteringVRObservable
  87220. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87221. */
  87222. get: function () {
  87223. return this.onEnteringVRObservable;
  87224. },
  87225. enumerable: true,
  87226. configurable: true
  87227. });
  87228. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87229. /** Return this.onExitingVRObservable
  87230. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87231. */
  87232. get: function () {
  87233. return this.onExitingVRObservable;
  87234. },
  87235. enumerable: true,
  87236. configurable: true
  87237. });
  87238. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87239. /** Return this.onControllerMeshLoadedObservable
  87240. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87241. */
  87242. get: function () {
  87243. return this.onControllerMeshLoadedObservable;
  87244. },
  87245. enumerable: true,
  87246. configurable: true
  87247. });
  87248. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87249. /**
  87250. * The mesh used to display where the user is going to teleport.
  87251. */
  87252. get: function () {
  87253. return this._teleportationTarget;
  87254. },
  87255. /**
  87256. * Sets the mesh to be used to display where the user is going to teleport.
  87257. */
  87258. set: function (value) {
  87259. if (value) {
  87260. value.name = "teleportationTarget";
  87261. this._isDefaultTeleportationTarget = false;
  87262. this._teleportationTarget = value;
  87263. }
  87264. },
  87265. enumerable: true,
  87266. configurable: true
  87267. });
  87268. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87269. /**
  87270. * The mesh used to display where the user is selecting,
  87271. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87272. * See http://doc.babylonjs.com/resources/baking_transformations
  87273. */
  87274. get: function () {
  87275. return this._cameraGazer._gazeTracker;
  87276. },
  87277. set: function (value) {
  87278. if (value) {
  87279. this._cameraGazer._gazeTracker = value;
  87280. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87281. this._cameraGazer._gazeTracker.isPickable = false;
  87282. this._cameraGazer._gazeTracker.isVisible = false;
  87283. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87284. if (this.leftController) {
  87285. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87286. }
  87287. if (this.rightController) {
  87288. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87289. }
  87290. }
  87291. },
  87292. enumerable: true,
  87293. configurable: true
  87294. });
  87295. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87296. /**
  87297. * If the ray of the gaze should be displayed.
  87298. */
  87299. get: function () {
  87300. return this._displayGaze;
  87301. },
  87302. /**
  87303. * Sets if the ray of the gaze should be displayed.
  87304. */
  87305. set: function (value) {
  87306. this._displayGaze = value;
  87307. if (!value) {
  87308. this._cameraGazer._gazeTracker.isVisible = false;
  87309. if (this.leftController) {
  87310. this.leftController._gazeTracker.isVisible = false;
  87311. }
  87312. if (this.rightController) {
  87313. this.rightController._gazeTracker.isVisible = false;
  87314. }
  87315. }
  87316. },
  87317. enumerable: true,
  87318. configurable: true
  87319. });
  87320. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87321. /**
  87322. * If the ray of the LaserPointer should be displayed.
  87323. */
  87324. get: function () {
  87325. return this._displayLaserPointer;
  87326. },
  87327. /**
  87328. * Sets if the ray of the LaserPointer should be displayed.
  87329. */
  87330. set: function (value) {
  87331. this._displayLaserPointer = value;
  87332. if (!value) {
  87333. if (this.rightController) {
  87334. this.rightController._deactivatePointer();
  87335. this.rightController._gazeTracker.isVisible = false;
  87336. }
  87337. if (this.leftController) {
  87338. this.leftController._deactivatePointer();
  87339. this.leftController._gazeTracker.isVisible = false;
  87340. }
  87341. }
  87342. else {
  87343. if (this.rightController) {
  87344. this.rightController._activatePointer();
  87345. }
  87346. else if (this.leftController) {
  87347. this.leftController._activatePointer();
  87348. }
  87349. }
  87350. },
  87351. enumerable: true,
  87352. configurable: true
  87353. });
  87354. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87355. /**
  87356. * The deviceOrientationCamera used as the camera when not in VR.
  87357. */
  87358. get: function () {
  87359. return this._deviceOrientationCamera;
  87360. },
  87361. enumerable: true,
  87362. configurable: true
  87363. });
  87364. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87365. /**
  87366. * Based on the current WebVR support, returns the current VR camera used.
  87367. */
  87368. get: function () {
  87369. if (this._webVRready) {
  87370. return this._webVRCamera;
  87371. }
  87372. else {
  87373. return this._scene.activeCamera;
  87374. }
  87375. },
  87376. enumerable: true,
  87377. configurable: true
  87378. });
  87379. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87380. /**
  87381. * The webVRCamera which is used when in VR.
  87382. */
  87383. get: function () {
  87384. return this._webVRCamera;
  87385. },
  87386. enumerable: true,
  87387. configurable: true
  87388. });
  87389. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87390. /**
  87391. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87392. */
  87393. get: function () {
  87394. return this._vrDeviceOrientationCamera;
  87395. },
  87396. enumerable: true,
  87397. configurable: true
  87398. });
  87399. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87400. get: function () {
  87401. var result = this._cameraGazer._teleportationRequestInitiated
  87402. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87403. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87404. return result;
  87405. },
  87406. enumerable: true,
  87407. configurable: true
  87408. });
  87409. // Raised when one of the controller has loaded successfully its associated default mesh
  87410. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87411. if (this.leftController && this.leftController.webVRController == webVRController) {
  87412. if (webVRController.mesh) {
  87413. this.leftController._setLaserPointerParent(webVRController.mesh);
  87414. }
  87415. }
  87416. if (this.rightController && this.rightController.webVRController == webVRController) {
  87417. if (webVRController.mesh) {
  87418. this.rightController._setLaserPointerParent(webVRController.mesh);
  87419. }
  87420. }
  87421. try {
  87422. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87423. }
  87424. catch (err) {
  87425. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87426. }
  87427. };
  87428. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87429. /**
  87430. * Gets a value indicating if we are currently in VR mode.
  87431. */
  87432. get: function () {
  87433. return this._webVRpresenting || this._fullscreenVRpresenting;
  87434. },
  87435. enumerable: true,
  87436. configurable: true
  87437. });
  87438. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87439. var vrDisplay = this._scene.getEngine().getVRDevice();
  87440. if (vrDisplay) {
  87441. var wasPresenting = this._webVRpresenting;
  87442. // A VR display is connected
  87443. this._webVRpresenting = vrDisplay.isPresenting;
  87444. if (wasPresenting && !this._webVRpresenting)
  87445. this.exitVR();
  87446. }
  87447. else {
  87448. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87449. }
  87450. this.updateButtonVisibility();
  87451. };
  87452. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87453. this._webVRsupported = eventArgs.vrSupported;
  87454. this._webVRready = !!eventArgs.vrDisplay;
  87455. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87456. this.updateButtonVisibility();
  87457. };
  87458. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87459. if (this._canvas && !this._useCustomVRButton) {
  87460. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87461. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87462. }
  87463. };
  87464. VRExperienceHelper.prototype.displayVRButton = function () {
  87465. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87466. document.body.appendChild(this._btnVR);
  87467. this._btnVRDisplayed = true;
  87468. }
  87469. };
  87470. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  87471. if (!this._btnVR || this._useCustomVRButton) {
  87472. return;
  87473. }
  87474. this._btnVR.className = "babylonVRicon";
  87475. if (this.isInVRMode) {
  87476. this._btnVR.className += " vrdisplaypresenting";
  87477. }
  87478. else {
  87479. if (this._webVRready)
  87480. this._btnVR.className += " vrdisplayready";
  87481. if (this._webVRsupported)
  87482. this._btnVR.className += " vrdisplaysupported";
  87483. if (this._webVRrequesting)
  87484. this._btnVR.className += " vrdisplayrequesting";
  87485. }
  87486. };
  87487. /**
  87488. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  87489. * Otherwise, will use the fullscreen API.
  87490. */
  87491. VRExperienceHelper.prototype.enterVR = function () {
  87492. if (this.onEnteringVRObservable) {
  87493. try {
  87494. this.onEnteringVRObservable.notifyObservers(this);
  87495. }
  87496. catch (err) {
  87497. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  87498. }
  87499. }
  87500. if (this._scene.activeCamera) {
  87501. this._position = this._scene.activeCamera.position.clone();
  87502. // make sure that we return to the last active camera
  87503. this._existingCamera = this._scene.activeCamera;
  87504. }
  87505. if (this._webVRrequesting)
  87506. return;
  87507. // If WebVR is supported and a headset is connected
  87508. if (this._webVRready) {
  87509. if (!this._webVRpresenting) {
  87510. this._webVRCamera.position = this._position;
  87511. this._scene.activeCamera = this._webVRCamera;
  87512. }
  87513. }
  87514. else if (this._vrDeviceOrientationCamera) {
  87515. this._vrDeviceOrientationCamera.position = this._position;
  87516. if (this._scene.activeCamera) {
  87517. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87518. }
  87519. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  87520. this._scene.getEngine().switchFullscreen(true);
  87521. this.updateButtonVisibility();
  87522. }
  87523. if (this._scene.activeCamera && this._canvas) {
  87524. this._scene.activeCamera.attachControl(this._canvas);
  87525. }
  87526. if (this._interactionsEnabled) {
  87527. this._scene.registerBeforeRender(this.beforeRender);
  87528. }
  87529. };
  87530. /**
  87531. * Attempt to exit VR, or fullscreen.
  87532. */
  87533. VRExperienceHelper.prototype.exitVR = function () {
  87534. if (this.onExitingVRObservable) {
  87535. try {
  87536. this.onExitingVRObservable.notifyObservers(this);
  87537. }
  87538. catch (err) {
  87539. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  87540. }
  87541. }
  87542. if (this._webVRpresenting) {
  87543. this._scene.getEngine().disableVR();
  87544. }
  87545. if (this._scene.activeCamera) {
  87546. this._position = this._scene.activeCamera.position.clone();
  87547. }
  87548. if (this._deviceOrientationCamera) {
  87549. this._deviceOrientationCamera.position = this._position;
  87550. this._scene.activeCamera = this._deviceOrientationCamera;
  87551. if (this._canvas) {
  87552. this._scene.activeCamera.attachControl(this._canvas);
  87553. }
  87554. }
  87555. else if (this._existingCamera) {
  87556. this._existingCamera.position = this._position;
  87557. this._scene.activeCamera = this._existingCamera;
  87558. }
  87559. this.updateButtonVisibility();
  87560. if (this._interactionsEnabled) {
  87561. this._scene.unregisterBeforeRender(this.beforeRender);
  87562. }
  87563. // resize to update width and height when exiting vr exits fullscreen
  87564. this._scene.getEngine().resize();
  87565. };
  87566. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  87567. /**
  87568. * The position of the vr experience helper.
  87569. */
  87570. get: function () {
  87571. return this._position;
  87572. },
  87573. /**
  87574. * Sets the position of the vr experience helper.
  87575. */
  87576. set: function (value) {
  87577. this._position = value;
  87578. if (this._scene.activeCamera) {
  87579. this._scene.activeCamera.position = value;
  87580. }
  87581. },
  87582. enumerable: true,
  87583. configurable: true
  87584. });
  87585. /**
  87586. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  87587. */
  87588. VRExperienceHelper.prototype.enableInteractions = function () {
  87589. var _this = this;
  87590. if (!this._interactionsEnabled) {
  87591. this._interactionsRequested = true;
  87592. if (this.leftController) {
  87593. this._enableInteractionOnController(this.leftController);
  87594. }
  87595. if (this.rightController) {
  87596. this._enableInteractionOnController(this.rightController);
  87597. }
  87598. this.raySelectionPredicate = function (mesh) {
  87599. return mesh.isVisible;
  87600. };
  87601. this.meshSelectionPredicate = function (mesh) {
  87602. return true;
  87603. };
  87604. this._raySelectionPredicate = function (mesh) {
  87605. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  87606. && mesh.name.indexOf("teleportationTarget") === -1
  87607. && mesh.name.indexOf("torusTeleportation") === -1
  87608. && mesh.name.indexOf("laserPointer") === -1)) {
  87609. return _this.raySelectionPredicate(mesh);
  87610. }
  87611. return false;
  87612. };
  87613. this._interactionsEnabled = true;
  87614. }
  87615. };
  87616. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  87617. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  87618. if (this._floorMeshesCollection[i].id === mesh.id) {
  87619. return true;
  87620. }
  87621. }
  87622. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  87623. return true;
  87624. }
  87625. return false;
  87626. };
  87627. /**
  87628. * Adds a floor mesh to be used for teleportation.
  87629. * @param floorMesh the mesh to be used for teleportation.
  87630. */
  87631. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  87632. if (!this._floorMeshesCollection) {
  87633. return;
  87634. }
  87635. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  87636. return;
  87637. }
  87638. this._floorMeshesCollection.push(floorMesh);
  87639. };
  87640. /**
  87641. * Removes a floor mesh from being used for teleportation.
  87642. * @param floorMesh the mesh to be removed.
  87643. */
  87644. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  87645. if (!this._floorMeshesCollection) {
  87646. return;
  87647. }
  87648. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  87649. if (meshIndex !== -1) {
  87650. this._floorMeshesCollection.splice(meshIndex, 1);
  87651. }
  87652. };
  87653. /**
  87654. * Enables interactions and teleportation using the VR controllers and gaze.
  87655. * @param vrTeleportationOptions options to modify teleportation behavior.
  87656. */
  87657. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  87658. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  87659. if (!this._teleportationInitialized) {
  87660. this._teleportationRequested = true;
  87661. this.enableInteractions();
  87662. if (vrTeleportationOptions.floorMeshName) {
  87663. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  87664. }
  87665. if (vrTeleportationOptions.floorMeshes) {
  87666. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  87667. }
  87668. if (this.leftController != null) {
  87669. this._enableTeleportationOnController(this.leftController);
  87670. }
  87671. if (this.rightController != null) {
  87672. this._enableTeleportationOnController(this.rightController);
  87673. }
  87674. // Creates an image processing post process for the vignette not relying
  87675. // on the main scene configuration for image processing to reduce setup and spaces
  87676. // (gamma/linear) conflicts.
  87677. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  87678. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87679. imageProcessingConfiguration.vignetteEnabled = true;
  87680. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  87681. this._webVRCamera.detachPostProcess(this._postProcessMove);
  87682. this._teleportationInitialized = true;
  87683. if (this._isDefaultTeleportationTarget) {
  87684. this._createTeleportationCircles();
  87685. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  87686. }
  87687. }
  87688. };
  87689. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  87690. var _this = this;
  87691. var controllerMesh = controller.webVRController.mesh;
  87692. if (controllerMesh) {
  87693. controller._interactionsEnabled = true;
  87694. controller._activatePointer();
  87695. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  87696. // Enabling / disabling laserPointer
  87697. if (_this._displayLaserPointer && stateObject.value === 1) {
  87698. if (controller._activePointer) {
  87699. controller._deactivatePointer();
  87700. }
  87701. else {
  87702. controller._activatePointer();
  87703. }
  87704. if (_this.displayGaze) {
  87705. controller._gazeTracker.isVisible = controller._activePointer;
  87706. }
  87707. }
  87708. });
  87709. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  87710. if (!controller._pointerDownOnMeshAsked) {
  87711. if (stateObject.value > _this._padSensibilityUp) {
  87712. controller._selectionPointerDown();
  87713. }
  87714. }
  87715. else if (stateObject.value < _this._padSensibilityDown) {
  87716. controller._selectionPointerUp();
  87717. }
  87718. });
  87719. }
  87720. };
  87721. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  87722. // Dont teleport if another gaze already requested teleportation
  87723. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  87724. return;
  87725. }
  87726. if (!gazer._teleportationRequestInitiated) {
  87727. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  87728. gazer._activatePointer();
  87729. gazer._teleportationRequestInitiated = true;
  87730. }
  87731. }
  87732. else {
  87733. // Listening to the proper controller values changes to confirm teleportation
  87734. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  87735. if (this._teleportActive) {
  87736. this._teleportCamera(this._haloCenter);
  87737. }
  87738. gazer._teleportationRequestInitiated = false;
  87739. }
  87740. }
  87741. };
  87742. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  87743. // Only rotate when user is not currently selecting a teleportation location
  87744. if (gazer._teleportationRequestInitiated) {
  87745. return;
  87746. }
  87747. if (!this._rotationLeftAsked) {
  87748. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  87749. this._rotationLeftAsked = true;
  87750. if (this._rotationAllowed) {
  87751. this._rotateCamera(false);
  87752. }
  87753. }
  87754. }
  87755. else {
  87756. if (stateObject.x > -this._padSensibilityDown) {
  87757. this._rotationLeftAsked = false;
  87758. }
  87759. }
  87760. if (!this._rotationRightAsked) {
  87761. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  87762. this._rotationRightAsked = true;
  87763. if (this._rotationAllowed) {
  87764. this._rotateCamera(true);
  87765. }
  87766. }
  87767. }
  87768. else {
  87769. if (stateObject.x < this._padSensibilityDown) {
  87770. this._rotationRightAsked = false;
  87771. }
  87772. }
  87773. };
  87774. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  87775. // Only teleport backwards when user is not currently selecting a teleportation location
  87776. if (gazer._teleportationRequestInitiated) {
  87777. return;
  87778. }
  87779. // Teleport backwards
  87780. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  87781. if (!gazer._teleportationBackRequestInitiated) {
  87782. if (!this.currentVRCamera) {
  87783. return;
  87784. }
  87785. // Get rotation and position of the current camera
  87786. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  87787. var position = this.currentVRCamera.position;
  87788. // If the camera has device position, use that instead
  87789. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  87790. rotation = this.currentVRCamera.deviceRotationQuaternion;
  87791. position = this.currentVRCamera.devicePosition;
  87792. }
  87793. // Get matrix with only the y rotation of the device rotation
  87794. rotation.toEulerAnglesToRef(this._workingVector);
  87795. this._workingVector.z = 0;
  87796. this._workingVector.x = 0;
  87797. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  87798. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  87799. // Rotate backwards ray by device rotation to cast at the ground behind the user
  87800. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  87801. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  87802. var ray = new BABYLON.Ray(position, this._workingVector);
  87803. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  87804. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  87805. this._teleportCamera(hit.pickedPoint);
  87806. }
  87807. gazer._teleportationBackRequestInitiated = true;
  87808. }
  87809. }
  87810. else {
  87811. gazer._teleportationBackRequestInitiated = false;
  87812. }
  87813. };
  87814. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  87815. var _this = this;
  87816. var controllerMesh = controller.webVRController.mesh;
  87817. if (controllerMesh) {
  87818. if (!controller._interactionsEnabled) {
  87819. this._enableInteractionOnController(controller);
  87820. }
  87821. controller._interactionsEnabled = true;
  87822. controller._teleportationEnabled = true;
  87823. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87824. controller._dpadPressed = false;
  87825. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  87826. controller._dpadPressed = stateObject.pressed;
  87827. if (!controller._dpadPressed) {
  87828. _this._rotationLeftAsked = false;
  87829. _this._rotationRightAsked = false;
  87830. controller._teleportationBackRequestInitiated = false;
  87831. }
  87832. });
  87833. }
  87834. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  87835. if (_this.teleportationEnabled) {
  87836. _this._checkTeleportBackwards(stateObject, controller);
  87837. _this._checkTeleportWithRay(stateObject, controller);
  87838. }
  87839. _this._checkRotate(stateObject, controller);
  87840. });
  87841. }
  87842. };
  87843. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  87844. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  87845. this._teleportationTarget.isPickable = false;
  87846. var length = 512;
  87847. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  87848. dynamicTexture.hasAlpha = true;
  87849. var context = dynamicTexture.getContext();
  87850. var centerX = length / 2;
  87851. var centerY = length / 2;
  87852. var radius = 200;
  87853. context.beginPath();
  87854. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  87855. context.fillStyle = this._teleportationFillColor;
  87856. context.fill();
  87857. context.lineWidth = 10;
  87858. context.strokeStyle = this._teleportationBorderColor;
  87859. context.stroke();
  87860. context.closePath();
  87861. dynamicTexture.update();
  87862. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  87863. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  87864. this._teleportationTarget.material = teleportationCircleMaterial;
  87865. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  87866. torus.isPickable = false;
  87867. torus.parent = this._teleportationTarget;
  87868. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  87869. var keys = [];
  87870. keys.push({
  87871. frame: 0,
  87872. value: 0
  87873. });
  87874. keys.push({
  87875. frame: 30,
  87876. value: 0.4
  87877. });
  87878. keys.push({
  87879. frame: 60,
  87880. value: 0
  87881. });
  87882. animationInnerCircle.setKeys(keys);
  87883. var easingFunction = new BABYLON.SineEase();
  87884. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87885. animationInnerCircle.setEasingFunction(easingFunction);
  87886. torus.animations = [];
  87887. torus.animations.push(animationInnerCircle);
  87888. this._scene.beginAnimation(torus, 0, 60, true);
  87889. this._hideTeleportationTarget();
  87890. };
  87891. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  87892. this._teleportActive = true;
  87893. if (this._teleportationInitialized) {
  87894. this._teleportationTarget.isVisible = true;
  87895. if (this._isDefaultTeleportationTarget) {
  87896. this._teleportationTarget.getChildren()[0].isVisible = true;
  87897. }
  87898. }
  87899. };
  87900. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  87901. this._teleportActive = false;
  87902. if (this._teleportationInitialized) {
  87903. this._teleportationTarget.isVisible = false;
  87904. if (this._isDefaultTeleportationTarget) {
  87905. this._teleportationTarget.getChildren()[0].isVisible = false;
  87906. }
  87907. }
  87908. };
  87909. VRExperienceHelper.prototype._rotateCamera = function (right) {
  87910. var _this = this;
  87911. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87912. return;
  87913. }
  87914. if (right) {
  87915. this._rotationAngle++;
  87916. }
  87917. else {
  87918. this._rotationAngle--;
  87919. }
  87920. this.currentVRCamera.animations = [];
  87921. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  87922. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87923. var animationRotationKeys = [];
  87924. animationRotationKeys.push({
  87925. frame: 0,
  87926. value: this.currentVRCamera.rotationQuaternion
  87927. });
  87928. animationRotationKeys.push({
  87929. frame: 6,
  87930. value: target
  87931. });
  87932. animationRotation.setKeys(animationRotationKeys);
  87933. animationRotation.setEasingFunction(this._circleEase);
  87934. this.currentVRCamera.animations.push(animationRotation);
  87935. this._postProcessMove.animations = [];
  87936. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87937. var vignetteWeightKeys = [];
  87938. vignetteWeightKeys.push({
  87939. frame: 0,
  87940. value: 0
  87941. });
  87942. vignetteWeightKeys.push({
  87943. frame: 3,
  87944. value: 4
  87945. });
  87946. vignetteWeightKeys.push({
  87947. frame: 6,
  87948. value: 0
  87949. });
  87950. animationPP.setKeys(vignetteWeightKeys);
  87951. animationPP.setEasingFunction(this._circleEase);
  87952. this._postProcessMove.animations.push(animationPP);
  87953. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  87954. var vignetteStretchKeys = [];
  87955. vignetteStretchKeys.push({
  87956. frame: 0,
  87957. value: 0
  87958. });
  87959. vignetteStretchKeys.push({
  87960. frame: 3,
  87961. value: 10
  87962. });
  87963. vignetteStretchKeys.push({
  87964. frame: 6,
  87965. value: 0
  87966. });
  87967. animationPP2.setKeys(vignetteStretchKeys);
  87968. animationPP2.setEasingFunction(this._circleEase);
  87969. this._postProcessMove.animations.push(animationPP2);
  87970. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  87971. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  87972. this._postProcessMove.samples = 4;
  87973. this._webVRCamera.attachPostProcess(this._postProcessMove);
  87974. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  87975. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  87976. });
  87977. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  87978. };
  87979. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  87980. if (hit.pickedPoint) {
  87981. if (gazer._teleportationRequestInitiated) {
  87982. this._displayTeleportationTarget();
  87983. this._haloCenter.copyFrom(hit.pickedPoint);
  87984. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  87985. }
  87986. var pickNormal = hit.getNormal(true, false);
  87987. if (pickNormal) {
  87988. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  87989. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  87990. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  87991. }
  87992. this._teleportationTarget.position.y += 0.1;
  87993. }
  87994. };
  87995. VRExperienceHelper.prototype._teleportCamera = function (location) {
  87996. var _this = this;
  87997. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  87998. return;
  87999. }
  88000. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88001. // offset of the headset from the anchor.
  88002. if (this.webVRCamera.leftCamera) {
  88003. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88004. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88005. location.subtractToRef(this._workingVector, this._workingVector);
  88006. }
  88007. else {
  88008. this._workingVector.copyFrom(location);
  88009. }
  88010. // Add height to account for user's height offset
  88011. if (this.isInVRMode) {
  88012. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88013. }
  88014. else {
  88015. this._workingVector.y += this._defaultHeight;
  88016. }
  88017. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88018. // Create animation from the camera's position to the new location
  88019. this.currentVRCamera.animations = [];
  88020. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88021. var animationCameraTeleportationKeys = [{
  88022. frame: 0,
  88023. value: this.currentVRCamera.position
  88024. },
  88025. {
  88026. frame: 11,
  88027. value: this._workingVector
  88028. }
  88029. ];
  88030. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88031. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88032. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88033. this._postProcessMove.animations = [];
  88034. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88035. var vignetteWeightKeys = [];
  88036. vignetteWeightKeys.push({
  88037. frame: 0,
  88038. value: 0
  88039. });
  88040. vignetteWeightKeys.push({
  88041. frame: 5,
  88042. value: 8
  88043. });
  88044. vignetteWeightKeys.push({
  88045. frame: 11,
  88046. value: 0
  88047. });
  88048. animationPP.setKeys(vignetteWeightKeys);
  88049. this._postProcessMove.animations.push(animationPP);
  88050. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88051. var vignetteStretchKeys = [];
  88052. vignetteStretchKeys.push({
  88053. frame: 0,
  88054. value: 0
  88055. });
  88056. vignetteStretchKeys.push({
  88057. frame: 5,
  88058. value: 10
  88059. });
  88060. vignetteStretchKeys.push({
  88061. frame: 11,
  88062. value: 0
  88063. });
  88064. animationPP2.setKeys(vignetteStretchKeys);
  88065. this._postProcessMove.animations.push(animationPP2);
  88066. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88067. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88068. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88069. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88070. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88071. });
  88072. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88073. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88074. });
  88075. this._hideTeleportationTarget();
  88076. };
  88077. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88078. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88079. return;
  88080. }
  88081. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  88082. // Moving the gazeTracker on the mesh face targetted
  88083. if (hit && hit.pickedPoint) {
  88084. if (this._displayGaze) {
  88085. var multiplier = 1;
  88086. gazer._gazeTracker.isVisible = true;
  88087. if (gazer._isActionableMesh) {
  88088. multiplier = 3;
  88089. }
  88090. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88091. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88092. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88093. var pickNormal = hit.getNormal();
  88094. // To avoid z-fighting
  88095. var deltaFighting = 0.002;
  88096. if (pickNormal) {
  88097. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88098. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88099. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88100. }
  88101. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88102. if (gazer._gazeTracker.position.x < 0) {
  88103. gazer._gazeTracker.position.x += deltaFighting;
  88104. }
  88105. else {
  88106. gazer._gazeTracker.position.x -= deltaFighting;
  88107. }
  88108. if (gazer._gazeTracker.position.y < 0) {
  88109. gazer._gazeTracker.position.y += deltaFighting;
  88110. }
  88111. else {
  88112. gazer._gazeTracker.position.y -= deltaFighting;
  88113. }
  88114. if (gazer._gazeTracker.position.z < 0) {
  88115. gazer._gazeTracker.position.z += deltaFighting;
  88116. }
  88117. else {
  88118. gazer._gazeTracker.position.z -= deltaFighting;
  88119. }
  88120. }
  88121. // Changing the size of the laser pointer based on the distance from the targetted point
  88122. gazer._updatePointerDistance(hit.distance);
  88123. }
  88124. else {
  88125. gazer._gazeTracker.isVisible = false;
  88126. }
  88127. if (hit && hit.pickedMesh) {
  88128. gazer._currentHit = hit;
  88129. if (gazer._pointerDownOnMeshAsked) {
  88130. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88131. }
  88132. // The object selected is the floor, we're in a teleportation scenario
  88133. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88134. // Moving the teleportation area to this targetted point
  88135. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88136. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88137. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88138. }
  88139. gazer._currentMeshSelected = null;
  88140. if (gazer._teleportationRequestInitiated) {
  88141. this._moveTeleportationSelectorTo(hit, gazer);
  88142. }
  88143. return;
  88144. }
  88145. // If not, we're in a selection scenario
  88146. //this._teleportationAllowed = false;
  88147. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88148. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88149. this.onNewMeshPicked.notifyObservers(hit);
  88150. gazer._currentMeshSelected = hit.pickedMesh;
  88151. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88152. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88153. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88154. gazer._isActionableMesh = true;
  88155. }
  88156. else {
  88157. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88158. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88159. gazer._isActionableMesh = false;
  88160. }
  88161. try {
  88162. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88163. }
  88164. catch (err) {
  88165. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88166. }
  88167. }
  88168. else {
  88169. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88170. gazer._currentMeshSelected = null;
  88171. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88172. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88173. }
  88174. }
  88175. }
  88176. else {
  88177. gazer._currentHit = null;
  88178. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88179. gazer._currentMeshSelected = null;
  88180. //this._teleportationAllowed = false;
  88181. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88182. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88183. }
  88184. };
  88185. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88186. if (mesh) {
  88187. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88188. }
  88189. };
  88190. /**
  88191. * Sets the color of the laser ray from the vr controllers.
  88192. * @param color new color for the ray.
  88193. */
  88194. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88195. if (this.leftController) {
  88196. this.leftController._setLaserPointerColor(color);
  88197. }
  88198. if (this.rightController) {
  88199. this.rightController._setLaserPointerColor(color);
  88200. }
  88201. };
  88202. /**
  88203. * Sets the color of the ray from the vr headsets gaze.
  88204. * @param color new color for the ray.
  88205. */
  88206. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88207. if (!this._cameraGazer._gazeTracker.material) {
  88208. return;
  88209. }
  88210. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88211. if (this.leftController) {
  88212. this.leftController._gazeTracker.material.emissiveColor = color;
  88213. }
  88214. if (this.rightController) {
  88215. this.rightController._gazeTracker.material.emissiveColor = color;
  88216. }
  88217. };
  88218. /**
  88219. * Exits VR and disposes of the vr experience helper
  88220. */
  88221. VRExperienceHelper.prototype.dispose = function () {
  88222. if (this.isInVRMode) {
  88223. this.exitVR();
  88224. }
  88225. if (this._postProcessMove) {
  88226. this._postProcessMove.dispose();
  88227. }
  88228. if (this._webVRCamera) {
  88229. this._webVRCamera.dispose();
  88230. }
  88231. if (this._vrDeviceOrientationCamera) {
  88232. this._vrDeviceOrientationCamera.dispose();
  88233. }
  88234. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88235. document.body.removeChild(this._btnVR);
  88236. }
  88237. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88238. this._deviceOrientationCamera.dispose();
  88239. }
  88240. if (this._cameraGazer) {
  88241. this._cameraGazer.dispose();
  88242. }
  88243. if (this.leftController) {
  88244. this.leftController.dispose();
  88245. }
  88246. if (this.rightController) {
  88247. this.rightController.dispose();
  88248. }
  88249. if (this._teleportationTarget) {
  88250. this._teleportationTarget.dispose();
  88251. }
  88252. this._floorMeshesCollection = [];
  88253. document.removeEventListener("keydown", this._onKeyDown);
  88254. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88255. window.removeEventListener("resize", this._onResize);
  88256. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88257. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88258. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88259. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88260. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88261. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88262. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88263. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88264. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88265. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88266. this._scene.unregisterBeforeRender(this.beforeRender);
  88267. };
  88268. /**
  88269. * Gets the name of the VRExperienceHelper class
  88270. * @returns "VRExperienceHelper"
  88271. */
  88272. VRExperienceHelper.prototype.getClassName = function () {
  88273. return "VRExperienceHelper";
  88274. };
  88275. return VRExperienceHelper;
  88276. }());
  88277. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88278. })(BABYLON || (BABYLON = {}));
  88279. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88280. // Mainly based on these 2 articles :
  88281. // 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
  88282. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88283. var BABYLON;
  88284. (function (BABYLON) {
  88285. /**
  88286. * Defines the potential axis of a Joystick
  88287. */
  88288. var JoystickAxis;
  88289. (function (JoystickAxis) {
  88290. /** X axis */
  88291. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88292. /** Y axis */
  88293. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88294. /** Z axis */
  88295. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88296. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88297. /**
  88298. * Class used to define virtual joystick (used in touch mode)
  88299. */
  88300. var VirtualJoystick = /** @class */ (function () {
  88301. /**
  88302. * Creates a new virtual joystick
  88303. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88304. */
  88305. function VirtualJoystick(leftJoystick) {
  88306. var _this = this;
  88307. if (leftJoystick) {
  88308. this._leftJoystick = true;
  88309. }
  88310. else {
  88311. this._leftJoystick = false;
  88312. }
  88313. VirtualJoystick._globalJoystickIndex++;
  88314. // By default left & right arrow keys are moving the X
  88315. // and up & down keys are moving the Y
  88316. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88317. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88318. this.reverseLeftRight = false;
  88319. this.reverseUpDown = false;
  88320. // collections of pointers
  88321. this._touches = new BABYLON.StringDictionary();
  88322. this.deltaPosition = BABYLON.Vector3.Zero();
  88323. this._joystickSensibility = 25;
  88324. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88325. this._onResize = function (evt) {
  88326. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88327. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88328. if (VirtualJoystick.vjCanvas) {
  88329. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88330. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88331. }
  88332. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88333. };
  88334. // injecting a canvas element on top of the canvas 3D game
  88335. if (!VirtualJoystick.vjCanvas) {
  88336. window.addEventListener("resize", this._onResize, false);
  88337. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88338. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88339. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88340. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88341. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88342. VirtualJoystick.vjCanvas.style.width = "100%";
  88343. VirtualJoystick.vjCanvas.style.height = "100%";
  88344. VirtualJoystick.vjCanvas.style.position = "absolute";
  88345. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88346. VirtualJoystick.vjCanvas.style.top = "0px";
  88347. VirtualJoystick.vjCanvas.style.left = "0px";
  88348. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88349. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88350. // Support for jQuery PEP polyfill
  88351. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88352. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88353. if (!context) {
  88354. throw new Error("Unable to create canvas for virtual joystick");
  88355. }
  88356. VirtualJoystick.vjCanvasContext = context;
  88357. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88358. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88359. document.body.appendChild(VirtualJoystick.vjCanvas);
  88360. }
  88361. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88362. this.pressed = false;
  88363. // default joystick color
  88364. this._joystickColor = "cyan";
  88365. this._joystickPointerID = -1;
  88366. // current joystick position
  88367. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88368. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88369. // origin joystick position
  88370. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88371. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88372. this._onPointerDownHandlerRef = function (evt) {
  88373. _this._onPointerDown(evt);
  88374. };
  88375. this._onPointerMoveHandlerRef = function (evt) {
  88376. _this._onPointerMove(evt);
  88377. };
  88378. this._onPointerUpHandlerRef = function (evt) {
  88379. _this._onPointerUp(evt);
  88380. };
  88381. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88382. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88383. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88384. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88385. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88386. evt.preventDefault(); // Disables system menu
  88387. }, false);
  88388. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88389. }
  88390. /**
  88391. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88392. * @param newJoystickSensibility defines the new sensibility
  88393. */
  88394. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88395. this._joystickSensibility = newJoystickSensibility;
  88396. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88397. };
  88398. VirtualJoystick.prototype._onPointerDown = function (e) {
  88399. var positionOnScreenCondition;
  88400. e.preventDefault();
  88401. if (this._leftJoystick === true) {
  88402. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88403. }
  88404. else {
  88405. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88406. }
  88407. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88408. // First contact will be dedicated to the virtual joystick
  88409. this._joystickPointerID = e.pointerId;
  88410. this._joystickPointerStartPos.x = e.clientX;
  88411. this._joystickPointerStartPos.y = e.clientY;
  88412. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88413. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88414. this._deltaJoystickVector.x = 0;
  88415. this._deltaJoystickVector.y = 0;
  88416. this.pressed = true;
  88417. this._touches.add(e.pointerId.toString(), e);
  88418. }
  88419. else {
  88420. // You can only trigger the action buttons with a joystick declared
  88421. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88422. this._action();
  88423. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88424. }
  88425. }
  88426. };
  88427. VirtualJoystick.prototype._onPointerMove = function (e) {
  88428. // If the current pointer is the one associated to the joystick (first touch contact)
  88429. if (this._joystickPointerID == e.pointerId) {
  88430. this._joystickPointerPos.x = e.clientX;
  88431. this._joystickPointerPos.y = e.clientY;
  88432. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88433. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88434. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88435. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88436. switch (this._axisTargetedByLeftAndRight) {
  88437. case JoystickAxis.X:
  88438. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88439. break;
  88440. case JoystickAxis.Y:
  88441. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88442. break;
  88443. case JoystickAxis.Z:
  88444. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88445. break;
  88446. }
  88447. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88448. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88449. switch (this._axisTargetedByUpAndDown) {
  88450. case JoystickAxis.X:
  88451. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88452. break;
  88453. case JoystickAxis.Y:
  88454. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88455. break;
  88456. case JoystickAxis.Z:
  88457. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  88458. break;
  88459. }
  88460. }
  88461. else {
  88462. var data = this._touches.get(e.pointerId.toString());
  88463. if (data) {
  88464. data.x = e.clientX;
  88465. data.y = e.clientY;
  88466. }
  88467. }
  88468. };
  88469. VirtualJoystick.prototype._onPointerUp = function (e) {
  88470. if (this._joystickPointerID == e.pointerId) {
  88471. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  88472. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  88473. this._joystickPointerID = -1;
  88474. this.pressed = false;
  88475. }
  88476. else {
  88477. var touch = this._touches.get(e.pointerId.toString());
  88478. if (touch) {
  88479. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88480. }
  88481. }
  88482. this._deltaJoystickVector.x = 0;
  88483. this._deltaJoystickVector.y = 0;
  88484. this._touches.remove(e.pointerId.toString());
  88485. };
  88486. /**
  88487. * Change the color of the virtual joystick
  88488. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  88489. */
  88490. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  88491. this._joystickColor = newColor;
  88492. };
  88493. /**
  88494. * Defines a callback to call when the joystick is touched
  88495. * @param action defines the callback
  88496. */
  88497. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  88498. this._action = action;
  88499. };
  88500. /**
  88501. * Defines which axis you'd like to control for left & right
  88502. * @param axis defines the axis to use
  88503. */
  88504. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  88505. switch (axis) {
  88506. case JoystickAxis.X:
  88507. case JoystickAxis.Y:
  88508. case JoystickAxis.Z:
  88509. this._axisTargetedByLeftAndRight = axis;
  88510. break;
  88511. default:
  88512. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88513. break;
  88514. }
  88515. };
  88516. /**
  88517. * Defines which axis you'd like to control for up & down
  88518. * @param axis defines the axis to use
  88519. */
  88520. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  88521. switch (axis) {
  88522. case JoystickAxis.X:
  88523. case JoystickAxis.Y:
  88524. case JoystickAxis.Z:
  88525. this._axisTargetedByUpAndDown = axis;
  88526. break;
  88527. default:
  88528. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88529. break;
  88530. }
  88531. };
  88532. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  88533. var _this = this;
  88534. if (this.pressed) {
  88535. this._touches.forEach(function (key, touch) {
  88536. if (touch.pointerId === _this._joystickPointerID) {
  88537. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  88538. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  88539. VirtualJoystick.vjCanvasContext.beginPath();
  88540. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88541. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88542. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  88543. VirtualJoystick.vjCanvasContext.stroke();
  88544. VirtualJoystick.vjCanvasContext.closePath();
  88545. VirtualJoystick.vjCanvasContext.beginPath();
  88546. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88547. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88548. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  88549. VirtualJoystick.vjCanvasContext.stroke();
  88550. VirtualJoystick.vjCanvasContext.closePath();
  88551. VirtualJoystick.vjCanvasContext.beginPath();
  88552. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  88553. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  88554. VirtualJoystick.vjCanvasContext.stroke();
  88555. VirtualJoystick.vjCanvasContext.closePath();
  88556. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  88557. }
  88558. else {
  88559. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88560. VirtualJoystick.vjCanvasContext.beginPath();
  88561. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  88562. VirtualJoystick.vjCanvasContext.beginPath();
  88563. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  88564. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  88565. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  88566. VirtualJoystick.vjCanvasContext.stroke();
  88567. VirtualJoystick.vjCanvasContext.closePath();
  88568. touch.prevX = touch.x;
  88569. touch.prevY = touch.y;
  88570. }
  88571. ;
  88572. });
  88573. }
  88574. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88575. };
  88576. /**
  88577. * Release internal HTML canvas
  88578. */
  88579. VirtualJoystick.prototype.releaseCanvas = function () {
  88580. if (VirtualJoystick.vjCanvas) {
  88581. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  88582. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  88583. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  88584. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  88585. window.removeEventListener("resize", this._onResize);
  88586. document.body.removeChild(VirtualJoystick.vjCanvas);
  88587. VirtualJoystick.vjCanvas = null;
  88588. }
  88589. };
  88590. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  88591. VirtualJoystick._globalJoystickIndex = 0;
  88592. return VirtualJoystick;
  88593. }());
  88594. BABYLON.VirtualJoystick = VirtualJoystick;
  88595. })(BABYLON || (BABYLON = {}));
  88596. //# sourceMappingURL=babylon.virtualJoystick.js.map
  88597. var BABYLON;
  88598. (function (BABYLON) {
  88599. // We're mainly based on the logic defined into the FreeCamera code
  88600. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  88601. __extends(VirtualJoysticksCamera, _super);
  88602. function VirtualJoysticksCamera(name, position, scene) {
  88603. var _this = _super.call(this, name, position, scene) || this;
  88604. _this.inputs.addVirtualJoystick();
  88605. return _this;
  88606. }
  88607. VirtualJoysticksCamera.prototype.getClassName = function () {
  88608. return "VirtualJoysticksCamera";
  88609. };
  88610. return VirtualJoysticksCamera;
  88611. }(BABYLON.FreeCamera));
  88612. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  88613. })(BABYLON || (BABYLON = {}));
  88614. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  88615. var BABYLON;
  88616. (function (BABYLON) {
  88617. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  88618. function FreeCameraVirtualJoystickInput() {
  88619. }
  88620. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  88621. return this._leftjoystick;
  88622. };
  88623. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  88624. return this._rightjoystick;
  88625. };
  88626. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  88627. if (this._leftjoystick) {
  88628. var camera = this.camera;
  88629. var speed = camera._computeLocalCameraSpeed() * 50;
  88630. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  88631. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  88632. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  88633. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  88634. if (!this._leftjoystick.pressed) {
  88635. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  88636. }
  88637. if (!this._rightjoystick.pressed) {
  88638. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  88639. }
  88640. }
  88641. };
  88642. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  88643. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  88644. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  88645. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  88646. this._leftjoystick.setJoystickSensibility(0.15);
  88647. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  88648. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  88649. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  88650. this._rightjoystick.reverseUpDown = true;
  88651. this._rightjoystick.setJoystickSensibility(0.05);
  88652. this._rightjoystick.setJoystickColor("yellow");
  88653. };
  88654. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  88655. this._leftjoystick.releaseCanvas();
  88656. this._rightjoystick.releaseCanvas();
  88657. };
  88658. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  88659. return "FreeCameraVirtualJoystickInput";
  88660. };
  88661. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  88662. return "virtualJoystick";
  88663. };
  88664. return FreeCameraVirtualJoystickInput;
  88665. }());
  88666. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  88667. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  88668. })(BABYLON || (BABYLON = {}));
  88669. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  88670. var BABYLON;
  88671. (function (BABYLON) {
  88672. var SimplificationSettings = /** @class */ (function () {
  88673. function SimplificationSettings(quality, distance, optimizeMesh) {
  88674. this.quality = quality;
  88675. this.distance = distance;
  88676. this.optimizeMesh = optimizeMesh;
  88677. }
  88678. return SimplificationSettings;
  88679. }());
  88680. BABYLON.SimplificationSettings = SimplificationSettings;
  88681. var SimplificationQueue = /** @class */ (function () {
  88682. function SimplificationQueue() {
  88683. this.running = false;
  88684. this._simplificationArray = [];
  88685. }
  88686. SimplificationQueue.prototype.addTask = function (task) {
  88687. this._simplificationArray.push(task);
  88688. };
  88689. SimplificationQueue.prototype.executeNext = function () {
  88690. var task = this._simplificationArray.pop();
  88691. if (task) {
  88692. this.running = true;
  88693. this.runSimplification(task);
  88694. }
  88695. else {
  88696. this.running = false;
  88697. }
  88698. };
  88699. SimplificationQueue.prototype.runSimplification = function (task) {
  88700. var _this = this;
  88701. if (task.parallelProcessing) {
  88702. //parallel simplifier
  88703. task.settings.forEach(function (setting) {
  88704. var simplifier = _this.getSimplifier(task);
  88705. simplifier.simplify(setting, function (newMesh) {
  88706. task.mesh.addLODLevel(setting.distance, newMesh);
  88707. newMesh.isVisible = true;
  88708. //check if it is the last
  88709. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  88710. //all done, run the success callback.
  88711. task.successCallback();
  88712. }
  88713. _this.executeNext();
  88714. });
  88715. });
  88716. }
  88717. else {
  88718. //single simplifier.
  88719. var simplifier = this.getSimplifier(task);
  88720. var runDecimation = function (setting, callback) {
  88721. simplifier.simplify(setting, function (newMesh) {
  88722. task.mesh.addLODLevel(setting.distance, newMesh);
  88723. newMesh.isVisible = true;
  88724. //run the next quality level
  88725. callback();
  88726. });
  88727. };
  88728. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  88729. runDecimation(task.settings[loop.index], function () {
  88730. loop.executeNext();
  88731. });
  88732. }, function () {
  88733. //execution ended, run the success callback.
  88734. if (task.successCallback) {
  88735. task.successCallback();
  88736. }
  88737. _this.executeNext();
  88738. });
  88739. }
  88740. };
  88741. SimplificationQueue.prototype.getSimplifier = function (task) {
  88742. switch (task.simplificationType) {
  88743. case SimplificationType.QUADRATIC:
  88744. default:
  88745. return new QuadraticErrorSimplification(task.mesh);
  88746. }
  88747. };
  88748. return SimplificationQueue;
  88749. }());
  88750. BABYLON.SimplificationQueue = SimplificationQueue;
  88751. /**
  88752. * The implemented types of simplification
  88753. * At the moment only Quadratic Error Decimation is implemented
  88754. */
  88755. var SimplificationType;
  88756. (function (SimplificationType) {
  88757. /** Quadratic error decimation */
  88758. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  88759. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  88760. var DecimationTriangle = /** @class */ (function () {
  88761. function DecimationTriangle(vertices) {
  88762. this.vertices = vertices;
  88763. this.error = new Array(4);
  88764. this.deleted = false;
  88765. this.isDirty = false;
  88766. this.deletePending = false;
  88767. this.borderFactor = 0;
  88768. }
  88769. return DecimationTriangle;
  88770. }());
  88771. BABYLON.DecimationTriangle = DecimationTriangle;
  88772. var DecimationVertex = /** @class */ (function () {
  88773. function DecimationVertex(position, id) {
  88774. this.position = position;
  88775. this.id = id;
  88776. this.isBorder = true;
  88777. this.q = new QuadraticMatrix();
  88778. this.triangleCount = 0;
  88779. this.triangleStart = 0;
  88780. this.originalOffsets = [];
  88781. }
  88782. DecimationVertex.prototype.updatePosition = function (newPosition) {
  88783. this.position.copyFrom(newPosition);
  88784. };
  88785. return DecimationVertex;
  88786. }());
  88787. BABYLON.DecimationVertex = DecimationVertex;
  88788. var QuadraticMatrix = /** @class */ (function () {
  88789. function QuadraticMatrix(data) {
  88790. this.data = new Array(10);
  88791. for (var i = 0; i < 10; ++i) {
  88792. if (data && data[i]) {
  88793. this.data[i] = data[i];
  88794. }
  88795. else {
  88796. this.data[i] = 0;
  88797. }
  88798. }
  88799. }
  88800. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  88801. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  88802. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  88803. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  88804. return det;
  88805. };
  88806. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  88807. for (var i = 0; i < 10; ++i) {
  88808. this.data[i] += matrix.data[i];
  88809. }
  88810. };
  88811. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  88812. for (var i = 0; i < 10; ++i) {
  88813. this.data[i] += data[i];
  88814. }
  88815. };
  88816. QuadraticMatrix.prototype.add = function (matrix) {
  88817. var m = new QuadraticMatrix();
  88818. for (var i = 0; i < 10; ++i) {
  88819. m.data[i] = this.data[i] + matrix.data[i];
  88820. }
  88821. return m;
  88822. };
  88823. QuadraticMatrix.FromData = function (a, b, c, d) {
  88824. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  88825. };
  88826. //returning an array to avoid garbage collection
  88827. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  88828. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  88829. };
  88830. return QuadraticMatrix;
  88831. }());
  88832. BABYLON.QuadraticMatrix = QuadraticMatrix;
  88833. var Reference = /** @class */ (function () {
  88834. function Reference(vertexId, triangleId) {
  88835. this.vertexId = vertexId;
  88836. this.triangleId = triangleId;
  88837. }
  88838. return Reference;
  88839. }());
  88840. BABYLON.Reference = Reference;
  88841. /**
  88842. * An implementation of the Quadratic Error simplification algorithm.
  88843. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  88844. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  88845. * @author RaananW
  88846. */
  88847. var QuadraticErrorSimplification = /** @class */ (function () {
  88848. function QuadraticErrorSimplification(_mesh) {
  88849. this._mesh = _mesh;
  88850. this.syncIterations = 5000;
  88851. this.aggressiveness = 7;
  88852. this.decimationIterations = 100;
  88853. this.boundingBoxEpsilon = BABYLON.Epsilon;
  88854. }
  88855. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  88856. var _this = this;
  88857. this.initDecimatedMesh();
  88858. //iterating through the submeshes array, one after the other.
  88859. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  88860. _this.initWithMesh(loop.index, function () {
  88861. _this.runDecimation(settings, loop.index, function () {
  88862. loop.executeNext();
  88863. });
  88864. }, settings.optimizeMesh);
  88865. }, function () {
  88866. setTimeout(function () {
  88867. successCallback(_this._reconstructedMesh);
  88868. }, 0);
  88869. });
  88870. };
  88871. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  88872. var _this = this;
  88873. var targetCount = ~~(this.triangles.length * settings.quality);
  88874. var deletedTriangles = 0;
  88875. var triangleCount = this.triangles.length;
  88876. var iterationFunction = function (iteration, callback) {
  88877. setTimeout(function () {
  88878. if (iteration % 5 === 0) {
  88879. _this.updateMesh(iteration === 0);
  88880. }
  88881. for (var i = 0; i < _this.triangles.length; ++i) {
  88882. _this.triangles[i].isDirty = false;
  88883. }
  88884. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  88885. var trianglesIterator = function (i) {
  88886. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  88887. var t = _this.triangles[tIdx];
  88888. if (!t)
  88889. return;
  88890. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  88891. return;
  88892. }
  88893. for (var j = 0; j < 3; ++j) {
  88894. if (t.error[j] < threshold) {
  88895. var deleted0 = [];
  88896. var deleted1 = [];
  88897. var v0 = t.vertices[j];
  88898. var v1 = t.vertices[(j + 1) % 3];
  88899. if (v0.isBorder || v1.isBorder)
  88900. continue;
  88901. var p = BABYLON.Vector3.Zero();
  88902. var n = BABYLON.Vector3.Zero();
  88903. var uv = BABYLON.Vector2.Zero();
  88904. var color = new BABYLON.Color4(0, 0, 0, 1);
  88905. _this.calculateError(v0, v1, p, n, uv, color);
  88906. var delTr = new Array();
  88907. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  88908. continue;
  88909. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  88910. continue;
  88911. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  88912. continue;
  88913. var uniqueArray = new Array();
  88914. delTr.forEach(function (deletedT) {
  88915. if (uniqueArray.indexOf(deletedT) === -1) {
  88916. deletedT.deletePending = true;
  88917. uniqueArray.push(deletedT);
  88918. }
  88919. });
  88920. if (uniqueArray.length % 2 !== 0) {
  88921. continue;
  88922. }
  88923. v0.q = v1.q.add(v0.q);
  88924. v0.updatePosition(p);
  88925. var tStart = _this.references.length;
  88926. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  88927. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  88928. var tCount = _this.references.length - tStart;
  88929. if (tCount <= v0.triangleCount) {
  88930. if (tCount) {
  88931. for (var c = 0; c < tCount; c++) {
  88932. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  88933. }
  88934. }
  88935. }
  88936. else {
  88937. v0.triangleStart = tStart;
  88938. }
  88939. v0.triangleCount = tCount;
  88940. break;
  88941. }
  88942. }
  88943. };
  88944. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  88945. }, 0);
  88946. };
  88947. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  88948. if (triangleCount - deletedTriangles <= targetCount)
  88949. loop.breakLoop();
  88950. else {
  88951. iterationFunction(loop.index, function () {
  88952. loop.executeNext();
  88953. });
  88954. }
  88955. }, function () {
  88956. setTimeout(function () {
  88957. //reconstruct this part of the mesh
  88958. _this.reconstructMesh(submeshIndex);
  88959. successCallback();
  88960. }, 0);
  88961. });
  88962. };
  88963. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  88964. var _this = this;
  88965. this.vertices = [];
  88966. this.triangles = [];
  88967. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  88968. var indices = this._mesh.getIndices();
  88969. var submesh = this._mesh.subMeshes[submeshIndex];
  88970. var findInVertices = function (positionToSearch) {
  88971. if (optimizeMesh) {
  88972. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  88973. if (_this.vertices[ii].position.equals(positionToSearch)) {
  88974. return _this.vertices[ii];
  88975. }
  88976. }
  88977. }
  88978. return null;
  88979. };
  88980. var vertexReferences = [];
  88981. var vertexInit = function (i) {
  88982. if (!positionData) {
  88983. return;
  88984. }
  88985. var offset = i + submesh.verticesStart;
  88986. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  88987. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  88988. vertex.originalOffsets.push(offset);
  88989. if (vertex.id === _this.vertices.length) {
  88990. _this.vertices.push(vertex);
  88991. }
  88992. vertexReferences.push(vertex.id);
  88993. };
  88994. //var totalVertices = mesh.getTotalVertices();
  88995. var totalVertices = submesh.verticesCount;
  88996. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  88997. var indicesInit = function (i) {
  88998. if (!indices) {
  88999. return;
  89000. }
  89001. var offset = (submesh.indexStart / 3) + i;
  89002. var pos = (offset * 3);
  89003. var i0 = indices[pos + 0];
  89004. var i1 = indices[pos + 1];
  89005. var i2 = indices[pos + 2];
  89006. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89007. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89008. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89009. var triangle = new DecimationTriangle([v0, v1, v2]);
  89010. triangle.originalOffset = pos;
  89011. _this.triangles.push(triangle);
  89012. };
  89013. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89014. _this.init(callback);
  89015. });
  89016. });
  89017. };
  89018. QuadraticErrorSimplification.prototype.init = function (callback) {
  89019. var _this = this;
  89020. var triangleInit1 = function (i) {
  89021. var t = _this.triangles[i];
  89022. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89023. for (var j = 0; j < 3; j++) {
  89024. 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))));
  89025. }
  89026. };
  89027. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89028. var triangleInit2 = function (i) {
  89029. var t = _this.triangles[i];
  89030. for (var j = 0; j < 3; ++j) {
  89031. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89032. }
  89033. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89034. };
  89035. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89036. callback();
  89037. });
  89038. });
  89039. };
  89040. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89041. var newTriangles = [];
  89042. var i;
  89043. for (i = 0; i < this.vertices.length; ++i) {
  89044. this.vertices[i].triangleCount = 0;
  89045. }
  89046. var t;
  89047. var j;
  89048. for (i = 0; i < this.triangles.length; ++i) {
  89049. if (!this.triangles[i].deleted) {
  89050. t = this.triangles[i];
  89051. for (j = 0; j < 3; ++j) {
  89052. t.vertices[j].triangleCount = 1;
  89053. }
  89054. newTriangles.push(t);
  89055. }
  89056. }
  89057. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89058. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89059. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89060. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89061. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89062. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89063. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89064. var vertexCount = 0;
  89065. for (i = 0; i < this.vertices.length; ++i) {
  89066. var vertex = this.vertices[i];
  89067. vertex.id = vertexCount;
  89068. if (vertex.triangleCount) {
  89069. vertex.originalOffsets.forEach(function (originalOffset) {
  89070. if (!normalData) {
  89071. return;
  89072. }
  89073. newPositionData.push(vertex.position.x);
  89074. newPositionData.push(vertex.position.y);
  89075. newPositionData.push(vertex.position.z);
  89076. newNormalData.push(normalData[originalOffset * 3]);
  89077. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89078. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89079. if (uvs && uvs.length) {
  89080. newUVsData.push(uvs[(originalOffset * 2)]);
  89081. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89082. }
  89083. else if (colorsData && colorsData.length) {
  89084. newColorsData.push(colorsData[(originalOffset * 4)]);
  89085. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89086. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89087. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89088. }
  89089. ++vertexCount;
  89090. });
  89091. }
  89092. }
  89093. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89094. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89095. var submeshesArray = this._reconstructedMesh.subMeshes;
  89096. this._reconstructedMesh.subMeshes = [];
  89097. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89098. var originalIndices = this._mesh.getIndices();
  89099. for (i = 0; i < newTriangles.length; ++i) {
  89100. t = newTriangles[i]; //now get the new referencing point for each vertex
  89101. [0, 1, 2].forEach(function (idx) {
  89102. var id = originalIndices[t.originalOffset + idx];
  89103. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89104. if (offset < 0)
  89105. offset = 0;
  89106. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89107. });
  89108. }
  89109. //overwriting the old vertex buffers and indices.
  89110. this._reconstructedMesh.setIndices(newIndicesArray);
  89111. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89112. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89113. if (newUVsData.length > 0)
  89114. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89115. if (newColorsData.length > 0)
  89116. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89117. //create submesh
  89118. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89119. if (submeshIndex > 0) {
  89120. this._reconstructedMesh.subMeshes = [];
  89121. submeshesArray.forEach(function (submesh) {
  89122. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89123. });
  89124. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89125. }
  89126. };
  89127. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89128. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89129. this._reconstructedMesh.material = this._mesh.material;
  89130. this._reconstructedMesh.parent = this._mesh.parent;
  89131. this._reconstructedMesh.isVisible = false;
  89132. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89133. };
  89134. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89135. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89136. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89137. if (t.deleted)
  89138. continue;
  89139. var s = this.references[vertex1.triangleStart + i].vertexId;
  89140. var v1 = t.vertices[(s + 1) % 3];
  89141. var v2 = t.vertices[(s + 2) % 3];
  89142. if ((v1 === vertex2 || v2 === vertex2)) {
  89143. deletedArray[i] = true;
  89144. delTr.push(t);
  89145. continue;
  89146. }
  89147. var d1 = v1.position.subtract(point);
  89148. d1 = d1.normalize();
  89149. var d2 = v2.position.subtract(point);
  89150. d2 = d2.normalize();
  89151. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89152. return true;
  89153. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89154. deletedArray[i] = false;
  89155. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89156. return true;
  89157. }
  89158. return false;
  89159. };
  89160. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89161. var newDeleted = deletedTriangles;
  89162. for (var i = 0; i < vertex.triangleCount; ++i) {
  89163. var ref = this.references[vertex.triangleStart + i];
  89164. var t = this.triangles[ref.triangleId];
  89165. if (t.deleted)
  89166. continue;
  89167. if (deletedArray[i] && t.deletePending) {
  89168. t.deleted = true;
  89169. newDeleted++;
  89170. continue;
  89171. }
  89172. t.vertices[ref.vertexId] = origVertex;
  89173. t.isDirty = true;
  89174. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89175. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89176. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89177. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89178. this.references.push(ref);
  89179. }
  89180. return newDeleted;
  89181. };
  89182. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89183. for (var i = 0; i < this.vertices.length; ++i) {
  89184. var vCount = [];
  89185. var vId = [];
  89186. var v = this.vertices[i];
  89187. var j;
  89188. for (j = 0; j < v.triangleCount; ++j) {
  89189. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89190. for (var ii = 0; ii < 3; ii++) {
  89191. var ofs = 0;
  89192. var vv = triangle.vertices[ii];
  89193. while (ofs < vCount.length) {
  89194. if (vId[ofs] === vv.id)
  89195. break;
  89196. ++ofs;
  89197. }
  89198. if (ofs === vCount.length) {
  89199. vCount.push(1);
  89200. vId.push(vv.id);
  89201. }
  89202. else {
  89203. vCount[ofs]++;
  89204. }
  89205. }
  89206. }
  89207. for (j = 0; j < vCount.length; ++j) {
  89208. if (vCount[j] === 1) {
  89209. this.vertices[vId[j]].isBorder = true;
  89210. }
  89211. else {
  89212. this.vertices[vId[j]].isBorder = false;
  89213. }
  89214. }
  89215. }
  89216. };
  89217. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89218. if (identifyBorders === void 0) { identifyBorders = false; }
  89219. var i;
  89220. if (!identifyBorders) {
  89221. var newTrianglesVector = [];
  89222. for (i = 0; i < this.triangles.length; ++i) {
  89223. if (!this.triangles[i].deleted) {
  89224. newTrianglesVector.push(this.triangles[i]);
  89225. }
  89226. }
  89227. this.triangles = newTrianglesVector;
  89228. }
  89229. for (i = 0; i < this.vertices.length; ++i) {
  89230. this.vertices[i].triangleCount = 0;
  89231. this.vertices[i].triangleStart = 0;
  89232. }
  89233. var t;
  89234. var j;
  89235. var v;
  89236. for (i = 0; i < this.triangles.length; ++i) {
  89237. t = this.triangles[i];
  89238. for (j = 0; j < 3; ++j) {
  89239. v = t.vertices[j];
  89240. v.triangleCount++;
  89241. }
  89242. }
  89243. var tStart = 0;
  89244. for (i = 0; i < this.vertices.length; ++i) {
  89245. this.vertices[i].triangleStart = tStart;
  89246. tStart += this.vertices[i].triangleCount;
  89247. this.vertices[i].triangleCount = 0;
  89248. }
  89249. var newReferences = new Array(this.triangles.length * 3);
  89250. for (i = 0; i < this.triangles.length; ++i) {
  89251. t = this.triangles[i];
  89252. for (j = 0; j < 3; ++j) {
  89253. v = t.vertices[j];
  89254. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89255. v.triangleCount++;
  89256. }
  89257. }
  89258. this.references = newReferences;
  89259. if (identifyBorders) {
  89260. this.identifyBorder();
  89261. }
  89262. };
  89263. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89264. var x = point.x;
  89265. var y = point.y;
  89266. var z = point.z;
  89267. 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
  89268. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89269. };
  89270. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89271. var q = vertex1.q.add(vertex2.q);
  89272. var border = vertex1.isBorder && vertex2.isBorder;
  89273. var error = 0;
  89274. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89275. if (qDet !== 0 && !border) {
  89276. if (!pointResult) {
  89277. pointResult = BABYLON.Vector3.Zero();
  89278. }
  89279. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89280. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89281. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89282. error = this.vertexError(q, pointResult);
  89283. }
  89284. else {
  89285. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89286. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89287. var error1 = this.vertexError(q, vertex1.position);
  89288. var error2 = this.vertexError(q, vertex2.position);
  89289. var error3 = this.vertexError(q, p3);
  89290. error = Math.min(error1, error2, error3);
  89291. if (error === error1) {
  89292. if (pointResult) {
  89293. pointResult.copyFrom(vertex1.position);
  89294. }
  89295. }
  89296. else if (error === error2) {
  89297. if (pointResult) {
  89298. pointResult.copyFrom(vertex2.position);
  89299. }
  89300. }
  89301. else {
  89302. if (pointResult) {
  89303. pointResult.copyFrom(p3);
  89304. }
  89305. }
  89306. }
  89307. return error;
  89308. };
  89309. return QuadraticErrorSimplification;
  89310. }());
  89311. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89312. })(BABYLON || (BABYLON = {}));
  89313. //# sourceMappingURL=babylon.meshSimplification.js.map
  89314. var BABYLON;
  89315. (function (BABYLON) {
  89316. var MeshLODLevel = /** @class */ (function () {
  89317. function MeshLODLevel(distance, mesh) {
  89318. this.distance = distance;
  89319. this.mesh = mesh;
  89320. }
  89321. return MeshLODLevel;
  89322. }());
  89323. BABYLON.MeshLODLevel = MeshLODLevel;
  89324. })(BABYLON || (BABYLON = {}));
  89325. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89326. var BABYLON;
  89327. (function (BABYLON) {
  89328. /**
  89329. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89330. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89331. */
  89332. var SceneOptimization = /** @class */ (function () {
  89333. /**
  89334. * Creates the SceneOptimization object
  89335. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89336. * @param desc defines the description associated with the optimization
  89337. */
  89338. function SceneOptimization(
  89339. /**
  89340. * Defines the priority of this optimization (0 by default which means first in the list)
  89341. */
  89342. priority) {
  89343. if (priority === void 0) { priority = 0; }
  89344. this.priority = priority;
  89345. }
  89346. /**
  89347. * Gets a string describing the action executed by the current optimization
  89348. * @returns description string
  89349. */
  89350. SceneOptimization.prototype.getDescription = function () {
  89351. return "";
  89352. };
  89353. /**
  89354. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89355. * @param scene defines the current scene where to apply this optimization
  89356. * @param optimizer defines the current optimizer
  89357. * @returns true if everything that can be done was applied
  89358. */
  89359. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89360. return true;
  89361. };
  89362. ;
  89363. return SceneOptimization;
  89364. }());
  89365. BABYLON.SceneOptimization = SceneOptimization;
  89366. /**
  89367. * Defines an optimization used to reduce the size of render target textures
  89368. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89369. */
  89370. var TextureOptimization = /** @class */ (function (_super) {
  89371. __extends(TextureOptimization, _super);
  89372. /**
  89373. * Creates the TextureOptimization object
  89374. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89375. * @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
  89376. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89377. */
  89378. function TextureOptimization(
  89379. /**
  89380. * Defines the priority of this optimization (0 by default which means first in the list)
  89381. */
  89382. priority,
  89383. /**
  89384. * 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
  89385. */
  89386. maximumSize,
  89387. /**
  89388. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89389. */
  89390. step) {
  89391. if (priority === void 0) { priority = 0; }
  89392. if (maximumSize === void 0) { maximumSize = 1024; }
  89393. if (step === void 0) { step = 0.5; }
  89394. var _this = _super.call(this, priority) || this;
  89395. _this.priority = priority;
  89396. _this.maximumSize = maximumSize;
  89397. _this.step = step;
  89398. return _this;
  89399. }
  89400. /**
  89401. * Gets a string describing the action executed by the current optimization
  89402. * @returns description string
  89403. */
  89404. TextureOptimization.prototype.getDescription = function () {
  89405. return "Reducing render target texture size to " + this.maximumSize;
  89406. };
  89407. /**
  89408. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89409. * @param scene defines the current scene where to apply this optimization
  89410. * @param optimizer defines the current optimizer
  89411. * @returns true if everything that can be done was applied
  89412. */
  89413. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89414. var allDone = true;
  89415. for (var index = 0; index < scene.textures.length; index++) {
  89416. var texture = scene.textures[index];
  89417. if (!texture.canRescale || texture.getContext) {
  89418. continue;
  89419. }
  89420. var currentSize = texture.getSize();
  89421. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89422. if (maxDimension > this.maximumSize) {
  89423. texture.scale(this.step);
  89424. allDone = false;
  89425. }
  89426. }
  89427. return allDone;
  89428. };
  89429. return TextureOptimization;
  89430. }(SceneOptimization));
  89431. BABYLON.TextureOptimization = TextureOptimization;
  89432. /**
  89433. * Defines an optimization used to increase or decrease the rendering resolution
  89434. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89435. */
  89436. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89437. __extends(HardwareScalingOptimization, _super);
  89438. /**
  89439. * Creates the HardwareScalingOptimization object
  89440. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89441. * @param maximumScale defines the maximum scale to use (2 by default)
  89442. * @param step defines the step to use between two passes (0.5 by default)
  89443. */
  89444. function HardwareScalingOptimization(
  89445. /**
  89446. * Defines the priority of this optimization (0 by default which means first in the list)
  89447. */
  89448. priority,
  89449. /**
  89450. * Defines the maximum scale to use (2 by default)
  89451. */
  89452. maximumScale,
  89453. /**
  89454. * Defines the step to use between two passes (0.5 by default)
  89455. */
  89456. step) {
  89457. if (priority === void 0) { priority = 0; }
  89458. if (maximumScale === void 0) { maximumScale = 2; }
  89459. if (step === void 0) { step = 0.25; }
  89460. var _this = _super.call(this, priority) || this;
  89461. _this.priority = priority;
  89462. _this.maximumScale = maximumScale;
  89463. _this.step = step;
  89464. _this._currentScale = -1;
  89465. _this._directionOffset = 1;
  89466. return _this;
  89467. }
  89468. /**
  89469. * Gets a string describing the action executed by the current optimization
  89470. * @return description string
  89471. */
  89472. HardwareScalingOptimization.prototype.getDescription = function () {
  89473. return "Setting hardware scaling level to " + this._currentScale;
  89474. };
  89475. /**
  89476. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89477. * @param scene defines the current scene where to apply this optimization
  89478. * @param optimizer defines the current optimizer
  89479. * @returns true if everything that can be done was applied
  89480. */
  89481. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  89482. if (this._currentScale === -1) {
  89483. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  89484. if (this._currentScale > this.maximumScale) {
  89485. this._directionOffset = -1;
  89486. }
  89487. }
  89488. this._currentScale += this._directionOffset * this.step;
  89489. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  89490. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  89491. };
  89492. ;
  89493. return HardwareScalingOptimization;
  89494. }(SceneOptimization));
  89495. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  89496. /**
  89497. * Defines an optimization used to remove shadows
  89498. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89499. */
  89500. var ShadowsOptimization = /** @class */ (function (_super) {
  89501. __extends(ShadowsOptimization, _super);
  89502. function ShadowsOptimization() {
  89503. return _super !== null && _super.apply(this, arguments) || this;
  89504. }
  89505. /**
  89506. * Gets a string describing the action executed by the current optimization
  89507. * @return description string
  89508. */
  89509. ShadowsOptimization.prototype.getDescription = function () {
  89510. return "Turning shadows on/off";
  89511. };
  89512. /**
  89513. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89514. * @param scene defines the current scene where to apply this optimization
  89515. * @param optimizer defines the current optimizer
  89516. * @returns true if everything that can be done was applied
  89517. */
  89518. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  89519. scene.shadowsEnabled = optimizer.isInImprovementMode;
  89520. return true;
  89521. };
  89522. ;
  89523. return ShadowsOptimization;
  89524. }(SceneOptimization));
  89525. BABYLON.ShadowsOptimization = ShadowsOptimization;
  89526. /**
  89527. * Defines an optimization used to turn post-processes off
  89528. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89529. */
  89530. var PostProcessesOptimization = /** @class */ (function (_super) {
  89531. __extends(PostProcessesOptimization, _super);
  89532. function PostProcessesOptimization() {
  89533. return _super !== null && _super.apply(this, arguments) || this;
  89534. }
  89535. /**
  89536. * Gets a string describing the action executed by the current optimization
  89537. * @return description string
  89538. */
  89539. PostProcessesOptimization.prototype.getDescription = function () {
  89540. return "Turning post-processes on/off";
  89541. };
  89542. /**
  89543. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89544. * @param scene defines the current scene where to apply this optimization
  89545. * @param optimizer defines the current optimizer
  89546. * @returns true if everything that can be done was applied
  89547. */
  89548. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  89549. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  89550. return true;
  89551. };
  89552. ;
  89553. return PostProcessesOptimization;
  89554. }(SceneOptimization));
  89555. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  89556. /**
  89557. * Defines an optimization used to turn lens flares off
  89558. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89559. */
  89560. var LensFlaresOptimization = /** @class */ (function (_super) {
  89561. __extends(LensFlaresOptimization, _super);
  89562. function LensFlaresOptimization() {
  89563. return _super !== null && _super.apply(this, arguments) || this;
  89564. }
  89565. /**
  89566. * Gets a string describing the action executed by the current optimization
  89567. * @return description string
  89568. */
  89569. LensFlaresOptimization.prototype.getDescription = function () {
  89570. return "Turning lens flares on/off";
  89571. };
  89572. /**
  89573. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89574. * @param scene defines the current scene where to apply this optimization
  89575. * @param optimizer defines the current optimizer
  89576. * @returns true if everything that can be done was applied
  89577. */
  89578. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  89579. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  89580. return true;
  89581. };
  89582. ;
  89583. return LensFlaresOptimization;
  89584. }(SceneOptimization));
  89585. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  89586. /**
  89587. * Defines an optimization based on user defined callback.
  89588. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89589. */
  89590. var CustomOptimization = /** @class */ (function (_super) {
  89591. __extends(CustomOptimization, _super);
  89592. function CustomOptimization() {
  89593. return _super !== null && _super.apply(this, arguments) || this;
  89594. }
  89595. /**
  89596. * Gets a string describing the action executed by the current optimization
  89597. * @returns description string
  89598. */
  89599. CustomOptimization.prototype.getDescription = function () {
  89600. if (this.onGetDescription) {
  89601. return this.onGetDescription();
  89602. }
  89603. return "Running user defined callback";
  89604. };
  89605. /**
  89606. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89607. * @param scene defines the current scene where to apply this optimization
  89608. * @param optimizer defines the current optimizer
  89609. * @returns true if everything that can be done was applied
  89610. */
  89611. CustomOptimization.prototype.apply = function (scene, optimizer) {
  89612. if (this.onApply) {
  89613. return this.onApply(scene, optimizer);
  89614. }
  89615. return true;
  89616. };
  89617. ;
  89618. return CustomOptimization;
  89619. }(SceneOptimization));
  89620. BABYLON.CustomOptimization = CustomOptimization;
  89621. /**
  89622. * Defines an optimization used to turn particles off
  89623. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89624. */
  89625. var ParticlesOptimization = /** @class */ (function (_super) {
  89626. __extends(ParticlesOptimization, _super);
  89627. function ParticlesOptimization() {
  89628. return _super !== null && _super.apply(this, arguments) || this;
  89629. }
  89630. /**
  89631. * Gets a string describing the action executed by the current optimization
  89632. * @return description string
  89633. */
  89634. ParticlesOptimization.prototype.getDescription = function () {
  89635. return "Turning particles on/off";
  89636. };
  89637. /**
  89638. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89639. * @param scene defines the current scene where to apply this optimization
  89640. * @param optimizer defines the current optimizer
  89641. * @returns true if everything that can be done was applied
  89642. */
  89643. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  89644. scene.particlesEnabled = optimizer.isInImprovementMode;
  89645. return true;
  89646. };
  89647. ;
  89648. return ParticlesOptimization;
  89649. }(SceneOptimization));
  89650. BABYLON.ParticlesOptimization = ParticlesOptimization;
  89651. /**
  89652. * Defines an optimization used to turn render targets off
  89653. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89654. */
  89655. var RenderTargetsOptimization = /** @class */ (function (_super) {
  89656. __extends(RenderTargetsOptimization, _super);
  89657. function RenderTargetsOptimization() {
  89658. return _super !== null && _super.apply(this, arguments) || this;
  89659. }
  89660. /**
  89661. * Gets a string describing the action executed by the current optimization
  89662. * @return description string
  89663. */
  89664. RenderTargetsOptimization.prototype.getDescription = function () {
  89665. return "Turning render targets off";
  89666. };
  89667. /**
  89668. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89669. * @param scene defines the current scene where to apply this optimization
  89670. * @param optimizer defines the current optimizer
  89671. * @returns true if everything that can be done was applied
  89672. */
  89673. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  89674. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  89675. return true;
  89676. };
  89677. ;
  89678. return RenderTargetsOptimization;
  89679. }(SceneOptimization));
  89680. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  89681. /**
  89682. * Defines an optimization used to merge meshes with compatible materials
  89683. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89684. */
  89685. var MergeMeshesOptimization = /** @class */ (function (_super) {
  89686. __extends(MergeMeshesOptimization, _super);
  89687. function MergeMeshesOptimization() {
  89688. var _this = _super !== null && _super.apply(this, arguments) || this;
  89689. _this._canBeMerged = function (abstractMesh) {
  89690. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  89691. return false;
  89692. }
  89693. var mesh = abstractMesh;
  89694. if (!mesh.isVisible || !mesh.isEnabled()) {
  89695. return false;
  89696. }
  89697. if (mesh.instances.length > 0) {
  89698. return false;
  89699. }
  89700. if (mesh.skeleton || mesh.hasLODLevels) {
  89701. return false;
  89702. }
  89703. if (mesh.parent) {
  89704. return false;
  89705. }
  89706. return true;
  89707. };
  89708. return _this;
  89709. }
  89710. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  89711. /**
  89712. * Gets or sets a boolean which defines if optimization octree has to be updated
  89713. */
  89714. get: function () {
  89715. return MergeMeshesOptimization._UpdateSelectionTree;
  89716. },
  89717. /**
  89718. * Gets or sets a boolean which defines if optimization octree has to be updated
  89719. */
  89720. set: function (value) {
  89721. MergeMeshesOptimization._UpdateSelectionTree = value;
  89722. },
  89723. enumerable: true,
  89724. configurable: true
  89725. });
  89726. /**
  89727. * Gets a string describing the action executed by the current optimization
  89728. * @return description string
  89729. */
  89730. MergeMeshesOptimization.prototype.getDescription = function () {
  89731. return "Merging similar meshes together";
  89732. };
  89733. /**
  89734. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89735. * @param scene defines the current scene where to apply this optimization
  89736. * @param optimizer defines the current optimizer
  89737. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  89738. * @returns true if everything that can be done was applied
  89739. */
  89740. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  89741. var globalPool = scene.meshes.slice(0);
  89742. var globalLength = globalPool.length;
  89743. for (var index = 0; index < globalLength; index++) {
  89744. var currentPool = new Array();
  89745. var current = globalPool[index];
  89746. // Checks
  89747. if (!this._canBeMerged(current)) {
  89748. continue;
  89749. }
  89750. currentPool.push(current);
  89751. // Find compatible meshes
  89752. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  89753. var otherMesh = globalPool[subIndex];
  89754. if (!this._canBeMerged(otherMesh)) {
  89755. continue;
  89756. }
  89757. if (otherMesh.material !== current.material) {
  89758. continue;
  89759. }
  89760. if (otherMesh.checkCollisions !== current.checkCollisions) {
  89761. continue;
  89762. }
  89763. currentPool.push(otherMesh);
  89764. globalLength--;
  89765. globalPool.splice(subIndex, 1);
  89766. subIndex--;
  89767. }
  89768. if (currentPool.length < 2) {
  89769. continue;
  89770. }
  89771. // Merge meshes
  89772. BABYLON.Mesh.MergeMeshes(currentPool);
  89773. }
  89774. if (updateSelectionTree != undefined) {
  89775. if (updateSelectionTree) {
  89776. scene.createOrUpdateSelectionOctree();
  89777. }
  89778. }
  89779. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  89780. scene.createOrUpdateSelectionOctree();
  89781. }
  89782. return true;
  89783. };
  89784. ;
  89785. MergeMeshesOptimization._UpdateSelectionTree = false;
  89786. return MergeMeshesOptimization;
  89787. }(SceneOptimization));
  89788. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  89789. /**
  89790. * Defines a list of options used by SceneOptimizer
  89791. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89792. */
  89793. var SceneOptimizerOptions = /** @class */ (function () {
  89794. /**
  89795. * Creates a new list of options used by SceneOptimizer
  89796. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  89797. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  89798. */
  89799. function SceneOptimizerOptions(
  89800. /**
  89801. * Defines the target frame rate to reach (60 by default)
  89802. */
  89803. targetFrameRate,
  89804. /**
  89805. * Defines the interval between two checkes (2000ms by default)
  89806. */
  89807. trackerDuration) {
  89808. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  89809. if (trackerDuration === void 0) { trackerDuration = 2000; }
  89810. this.targetFrameRate = targetFrameRate;
  89811. this.trackerDuration = trackerDuration;
  89812. /**
  89813. * Gets the list of optimizations to apply
  89814. */
  89815. this.optimizations = new Array();
  89816. }
  89817. /**
  89818. * Add a new optimization
  89819. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  89820. * @returns the current SceneOptimizerOptions
  89821. */
  89822. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  89823. this.optimizations.push(optimization);
  89824. return this;
  89825. };
  89826. /**
  89827. * Add a new custom optimization
  89828. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  89829. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  89830. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89831. * @returns the current SceneOptimizerOptions
  89832. */
  89833. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  89834. if (priority === void 0) { priority = 0; }
  89835. var optimization = new CustomOptimization(priority);
  89836. optimization.onApply = onApply;
  89837. optimization.onGetDescription = onGetDescription;
  89838. this.optimizations.push(optimization);
  89839. return this;
  89840. };
  89841. /**
  89842. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  89843. * @param targetFrameRate defines the target frame rate (60 by default)
  89844. * @returns a SceneOptimizerOptions object
  89845. */
  89846. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  89847. var result = new SceneOptimizerOptions(targetFrameRate);
  89848. var priority = 0;
  89849. result.addOptimization(new MergeMeshesOptimization(priority));
  89850. result.addOptimization(new ShadowsOptimization(priority));
  89851. result.addOptimization(new LensFlaresOptimization(priority));
  89852. // Next priority
  89853. priority++;
  89854. result.addOptimization(new PostProcessesOptimization(priority));
  89855. result.addOptimization(new ParticlesOptimization(priority));
  89856. // Next priority
  89857. priority++;
  89858. result.addOptimization(new TextureOptimization(priority, 1024));
  89859. return result;
  89860. };
  89861. /**
  89862. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  89863. * @param targetFrameRate defines the target frame rate (60 by default)
  89864. * @returns a SceneOptimizerOptions object
  89865. */
  89866. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  89867. var result = new SceneOptimizerOptions(targetFrameRate);
  89868. var priority = 0;
  89869. result.addOptimization(new MergeMeshesOptimization(priority));
  89870. result.addOptimization(new ShadowsOptimization(priority));
  89871. result.addOptimization(new LensFlaresOptimization(priority));
  89872. // Next priority
  89873. priority++;
  89874. result.addOptimization(new PostProcessesOptimization(priority));
  89875. result.addOptimization(new ParticlesOptimization(priority));
  89876. // Next priority
  89877. priority++;
  89878. result.addOptimization(new TextureOptimization(priority, 512));
  89879. // Next priority
  89880. priority++;
  89881. result.addOptimization(new RenderTargetsOptimization(priority));
  89882. // Next priority
  89883. priority++;
  89884. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  89885. return result;
  89886. };
  89887. /**
  89888. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  89889. * @param targetFrameRate defines the target frame rate (60 by default)
  89890. * @returns a SceneOptimizerOptions object
  89891. */
  89892. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  89893. var result = new SceneOptimizerOptions(targetFrameRate);
  89894. var priority = 0;
  89895. result.addOptimization(new MergeMeshesOptimization(priority));
  89896. result.addOptimization(new ShadowsOptimization(priority));
  89897. result.addOptimization(new LensFlaresOptimization(priority));
  89898. // Next priority
  89899. priority++;
  89900. result.addOptimization(new PostProcessesOptimization(priority));
  89901. result.addOptimization(new ParticlesOptimization(priority));
  89902. // Next priority
  89903. priority++;
  89904. result.addOptimization(new TextureOptimization(priority, 256));
  89905. // Next priority
  89906. priority++;
  89907. result.addOptimization(new RenderTargetsOptimization(priority));
  89908. // Next priority
  89909. priority++;
  89910. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  89911. return result;
  89912. };
  89913. return SceneOptimizerOptions;
  89914. }());
  89915. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  89916. /**
  89917. * Class used to run optimizations in order to reach a target frame rate
  89918. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89919. */
  89920. var SceneOptimizer = /** @class */ (function () {
  89921. /**
  89922. * Creates a new SceneOptimizer
  89923. * @param scene defines the scene to work on
  89924. * @param options defines the options to use with the SceneOptimizer
  89925. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  89926. * @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)
  89927. */
  89928. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  89929. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  89930. if (improvementMode === void 0) { improvementMode = false; }
  89931. var _this = this;
  89932. this._isRunning = false;
  89933. this._currentPriorityLevel = 0;
  89934. this._targetFrameRate = 60;
  89935. this._trackerDuration = 2000;
  89936. this._currentFrameRate = 0;
  89937. this._improvementMode = false;
  89938. /**
  89939. * Defines an observable called when the optimizer reaches the target frame rate
  89940. */
  89941. this.onSuccessObservable = new BABYLON.Observable();
  89942. /**
  89943. * Defines an observable called when the optimizer enables an optimization
  89944. */
  89945. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  89946. /**
  89947. * Defines an observable called when the optimizer is not able to reach the target frame rate
  89948. */
  89949. this.onFailureObservable = new BABYLON.Observable();
  89950. if (!options) {
  89951. this._options = new SceneOptimizerOptions();
  89952. }
  89953. else {
  89954. this._options = options;
  89955. }
  89956. if (this._options.targetFrameRate) {
  89957. this._targetFrameRate = this._options.targetFrameRate;
  89958. }
  89959. if (this._options.trackerDuration) {
  89960. this._trackerDuration = this._options.trackerDuration;
  89961. }
  89962. if (autoGeneratePriorities) {
  89963. var priority = 0;
  89964. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  89965. var optim = _a[_i];
  89966. optim.priority = priority++;
  89967. }
  89968. }
  89969. this._improvementMode = improvementMode;
  89970. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  89971. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  89972. _this._sceneDisposeObserver = null;
  89973. _this.dispose();
  89974. });
  89975. }
  89976. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  89977. /**
  89978. * Gets a boolean indicating if the optimizer is in improvement mode
  89979. */
  89980. get: function () {
  89981. return this._improvementMode;
  89982. },
  89983. enumerable: true,
  89984. configurable: true
  89985. });
  89986. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  89987. /**
  89988. * Gets the current priority level (0 at start)
  89989. */
  89990. get: function () {
  89991. return this._currentPriorityLevel;
  89992. },
  89993. enumerable: true,
  89994. configurable: true
  89995. });
  89996. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  89997. /**
  89998. * Gets the current frame rate checked by the SceneOptimizer
  89999. */
  90000. get: function () {
  90001. return this._currentFrameRate;
  90002. },
  90003. enumerable: true,
  90004. configurable: true
  90005. });
  90006. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90007. /**
  90008. * Gets or sets the current target frame rate (60 by default)
  90009. */
  90010. get: function () {
  90011. return this._targetFrameRate;
  90012. },
  90013. /**
  90014. * Gets or sets the current target frame rate (60 by default)
  90015. */
  90016. set: function (value) {
  90017. this._targetFrameRate = value;
  90018. },
  90019. enumerable: true,
  90020. configurable: true
  90021. });
  90022. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90023. /**
  90024. * Gets or sets the current interval between two checks (every 2000ms by default)
  90025. */
  90026. get: function () {
  90027. return this._trackerDuration;
  90028. },
  90029. /**
  90030. * Gets or sets the current interval between two checks (every 2000ms by default)
  90031. */
  90032. set: function (value) {
  90033. this._trackerDuration = value;
  90034. },
  90035. enumerable: true,
  90036. configurable: true
  90037. });
  90038. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90039. /**
  90040. * Gets the list of active optimizations
  90041. */
  90042. get: function () {
  90043. return this._options.optimizations;
  90044. },
  90045. enumerable: true,
  90046. configurable: true
  90047. });
  90048. /**
  90049. * Stops the current optimizer
  90050. */
  90051. SceneOptimizer.prototype.stop = function () {
  90052. this._isRunning = false;
  90053. };
  90054. /**
  90055. * Reset the optimizer to initial step (current priority level = 0)
  90056. */
  90057. SceneOptimizer.prototype.reset = function () {
  90058. this._currentPriorityLevel = 0;
  90059. };
  90060. /**
  90061. * Start the optimizer. By default it will try to reach a specific framerate
  90062. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90063. */
  90064. SceneOptimizer.prototype.start = function () {
  90065. var _this = this;
  90066. if (this._isRunning) {
  90067. return;
  90068. }
  90069. this._isRunning = true;
  90070. // Let's wait for the scene to be ready before running our check
  90071. this._scene.executeWhenReady(function () {
  90072. setTimeout(function () {
  90073. _this._checkCurrentState();
  90074. }, _this._trackerDuration);
  90075. });
  90076. };
  90077. SceneOptimizer.prototype._checkCurrentState = function () {
  90078. var _this = this;
  90079. if (!this._isRunning) {
  90080. return;
  90081. }
  90082. var scene = this._scene;
  90083. var options = this._options;
  90084. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90085. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90086. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90087. this._isRunning = false;
  90088. this.onSuccessObservable.notifyObservers(this);
  90089. return;
  90090. }
  90091. // Apply current level of optimizations
  90092. var allDone = true;
  90093. var noOptimizationApplied = true;
  90094. for (var index = 0; index < options.optimizations.length; index++) {
  90095. var optimization = options.optimizations[index];
  90096. if (optimization.priority === this._currentPriorityLevel) {
  90097. noOptimizationApplied = false;
  90098. allDone = allDone && optimization.apply(scene, this);
  90099. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90100. }
  90101. }
  90102. // If no optimization was applied, this is a failure :(
  90103. if (noOptimizationApplied) {
  90104. this._isRunning = false;
  90105. this.onFailureObservable.notifyObservers(this);
  90106. return;
  90107. }
  90108. // If all optimizations were done, move to next level
  90109. if (allDone) {
  90110. this._currentPriorityLevel++;
  90111. }
  90112. // Let's the system running for a specific amount of time before checking FPS
  90113. scene.executeWhenReady(function () {
  90114. setTimeout(function () {
  90115. _this._checkCurrentState();
  90116. }, _this._trackerDuration);
  90117. });
  90118. };
  90119. /**
  90120. * Release all resources
  90121. */
  90122. SceneOptimizer.prototype.dispose = function () {
  90123. this.stop();
  90124. this.onSuccessObservable.clear();
  90125. this.onFailureObservable.clear();
  90126. this.onNewOptimizationAppliedObservable.clear();
  90127. if (this._sceneDisposeObserver) {
  90128. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90129. }
  90130. };
  90131. /**
  90132. * Helper function to create a SceneOptimizer with one single line of code
  90133. * @param scene defines the scene to work on
  90134. * @param options defines the options to use with the SceneOptimizer
  90135. * @param onSuccess defines a callback to call on success
  90136. * @param onFailure defines a callback to call on failure
  90137. * @returns the new SceneOptimizer object
  90138. */
  90139. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90140. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90141. if (onSuccess) {
  90142. optimizer.onSuccessObservable.add(function () {
  90143. onSuccess();
  90144. });
  90145. }
  90146. if (onFailure) {
  90147. optimizer.onFailureObservable.add(function () {
  90148. onFailure();
  90149. });
  90150. }
  90151. optimizer.start();
  90152. return optimizer;
  90153. };
  90154. return SceneOptimizer;
  90155. }());
  90156. BABYLON.SceneOptimizer = SceneOptimizer;
  90157. })(BABYLON || (BABYLON = {}));
  90158. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90159. var BABYLON;
  90160. (function (BABYLON) {
  90161. var OutlineRenderer = /** @class */ (function () {
  90162. function OutlineRenderer(scene) {
  90163. this.zOffset = 1;
  90164. this._scene = scene;
  90165. }
  90166. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90167. var _this = this;
  90168. if (useOverlay === void 0) { useOverlay = false; }
  90169. var scene = this._scene;
  90170. var engine = this._scene.getEngine();
  90171. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90172. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90173. return;
  90174. }
  90175. var mesh = subMesh.getRenderingMesh();
  90176. var material = subMesh.getMaterial();
  90177. if (!material || !scene.activeCamera) {
  90178. return;
  90179. }
  90180. engine.enableEffect(this._effect);
  90181. // Logarithmic depth
  90182. if (material.useLogarithmicDepth) {
  90183. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90184. }
  90185. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90186. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90187. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90188. // Bones
  90189. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90190. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90191. }
  90192. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90193. // Alpha test
  90194. if (material && material.needAlphaTesting()) {
  90195. var alphaTexture = material.getAlphaTestTexture();
  90196. if (alphaTexture) {
  90197. this._effect.setTexture("diffuseSampler", alphaTexture);
  90198. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90199. }
  90200. }
  90201. engine.setZOffset(-this.zOffset);
  90202. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90203. engine.setZOffset(0);
  90204. };
  90205. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90206. var defines = [];
  90207. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90208. var mesh = subMesh.getMesh();
  90209. var material = subMesh.getMaterial();
  90210. if (material) {
  90211. // Alpha test
  90212. if (material.needAlphaTesting()) {
  90213. defines.push("#define ALPHATEST");
  90214. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90215. attribs.push(BABYLON.VertexBuffer.UVKind);
  90216. defines.push("#define UV1");
  90217. }
  90218. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90219. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90220. defines.push("#define UV2");
  90221. }
  90222. }
  90223. //Logarithmic depth
  90224. if (material.useLogarithmicDepth) {
  90225. defines.push("#define LOGARITHMICDEPTH");
  90226. }
  90227. }
  90228. // Bones
  90229. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90230. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90231. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90232. if (mesh.numBoneInfluencers > 4) {
  90233. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90234. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90235. }
  90236. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90237. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90238. }
  90239. else {
  90240. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90241. }
  90242. // Instances
  90243. if (useInstances) {
  90244. defines.push("#define INSTANCES");
  90245. attribs.push("world0");
  90246. attribs.push("world1");
  90247. attribs.push("world2");
  90248. attribs.push("world3");
  90249. }
  90250. // Get correct effect
  90251. var join = defines.join("\n");
  90252. if (this._cachedDefines !== join) {
  90253. this._cachedDefines = join;
  90254. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90255. }
  90256. return this._effect.isReady();
  90257. };
  90258. return OutlineRenderer;
  90259. }());
  90260. BABYLON.OutlineRenderer = OutlineRenderer;
  90261. })(BABYLON || (BABYLON = {}));
  90262. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90263. var BABYLON;
  90264. (function (BABYLON) {
  90265. var FaceAdjacencies = /** @class */ (function () {
  90266. function FaceAdjacencies() {
  90267. this.edges = new Array();
  90268. this.edgesConnectedCount = 0;
  90269. }
  90270. return FaceAdjacencies;
  90271. }());
  90272. var EdgesRenderer = /** @class */ (function () {
  90273. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90274. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90275. if (epsilon === void 0) { epsilon = 0.95; }
  90276. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90277. this.edgesWidthScalerForOrthographic = 1000.0;
  90278. this.edgesWidthScalerForPerspective = 50.0;
  90279. this._linesPositions = new Array();
  90280. this._linesNormals = new Array();
  90281. this._linesIndices = new Array();
  90282. this._buffers = {};
  90283. this._checkVerticesInsteadOfIndices = false;
  90284. this._source = source;
  90285. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90286. this._epsilon = epsilon;
  90287. this._prepareRessources();
  90288. this._generateEdgesLines();
  90289. }
  90290. EdgesRenderer.prototype._prepareRessources = function () {
  90291. if (this._lineShader) {
  90292. return;
  90293. }
  90294. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90295. attributes: ["position", "normal"],
  90296. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90297. });
  90298. this._lineShader.disableDepthWrite = true;
  90299. this._lineShader.backFaceCulling = false;
  90300. };
  90301. EdgesRenderer.prototype._rebuild = function () {
  90302. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90303. if (buffer) {
  90304. buffer._rebuild();
  90305. }
  90306. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90307. if (buffer) {
  90308. buffer._rebuild();
  90309. }
  90310. var scene = this._source.getScene();
  90311. var engine = scene.getEngine();
  90312. this._ib = engine.createIndexBuffer(this._linesIndices);
  90313. };
  90314. EdgesRenderer.prototype.dispose = function () {
  90315. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90316. if (buffer) {
  90317. buffer.dispose();
  90318. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90319. }
  90320. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90321. if (buffer) {
  90322. buffer.dispose();
  90323. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90324. }
  90325. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90326. this._lineShader.dispose();
  90327. };
  90328. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90329. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90330. return 0;
  90331. }
  90332. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90333. return 1;
  90334. }
  90335. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90336. return 2;
  90337. }
  90338. return -1;
  90339. };
  90340. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90341. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90342. return 0;
  90343. }
  90344. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90345. return 1;
  90346. }
  90347. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90348. return 2;
  90349. }
  90350. return -1;
  90351. };
  90352. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90353. var needToCreateLine;
  90354. if (edge === undefined) {
  90355. needToCreateLine = true;
  90356. }
  90357. else {
  90358. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90359. needToCreateLine = dotProduct < this._epsilon;
  90360. }
  90361. if (needToCreateLine) {
  90362. var offset = this._linesPositions.length / 3;
  90363. var normal = p0.subtract(p1);
  90364. normal.normalize();
  90365. // Positions
  90366. this._linesPositions.push(p0.x);
  90367. this._linesPositions.push(p0.y);
  90368. this._linesPositions.push(p0.z);
  90369. this._linesPositions.push(p0.x);
  90370. this._linesPositions.push(p0.y);
  90371. this._linesPositions.push(p0.z);
  90372. this._linesPositions.push(p1.x);
  90373. this._linesPositions.push(p1.y);
  90374. this._linesPositions.push(p1.z);
  90375. this._linesPositions.push(p1.x);
  90376. this._linesPositions.push(p1.y);
  90377. this._linesPositions.push(p1.z);
  90378. // Normals
  90379. this._linesNormals.push(p1.x);
  90380. this._linesNormals.push(p1.y);
  90381. this._linesNormals.push(p1.z);
  90382. this._linesNormals.push(-1);
  90383. this._linesNormals.push(p1.x);
  90384. this._linesNormals.push(p1.y);
  90385. this._linesNormals.push(p1.z);
  90386. this._linesNormals.push(1);
  90387. this._linesNormals.push(p0.x);
  90388. this._linesNormals.push(p0.y);
  90389. this._linesNormals.push(p0.z);
  90390. this._linesNormals.push(-1);
  90391. this._linesNormals.push(p0.x);
  90392. this._linesNormals.push(p0.y);
  90393. this._linesNormals.push(p0.z);
  90394. this._linesNormals.push(1);
  90395. // Indices
  90396. this._linesIndices.push(offset);
  90397. this._linesIndices.push(offset + 1);
  90398. this._linesIndices.push(offset + 2);
  90399. this._linesIndices.push(offset);
  90400. this._linesIndices.push(offset + 2);
  90401. this._linesIndices.push(offset + 3);
  90402. }
  90403. };
  90404. EdgesRenderer.prototype._generateEdgesLines = function () {
  90405. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90406. var indices = this._source.getIndices();
  90407. if (!indices || !positions) {
  90408. return;
  90409. }
  90410. // First let's find adjacencies
  90411. var adjacencies = new Array();
  90412. var faceNormals = new Array();
  90413. var index;
  90414. var faceAdjacencies;
  90415. // Prepare faces
  90416. for (index = 0; index < indices.length; index += 3) {
  90417. faceAdjacencies = new FaceAdjacencies();
  90418. var p0Index = indices[index];
  90419. var p1Index = indices[index + 1];
  90420. var p2Index = indices[index + 2];
  90421. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90422. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90423. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90424. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90425. faceNormal.normalize();
  90426. faceNormals.push(faceNormal);
  90427. adjacencies.push(faceAdjacencies);
  90428. }
  90429. // Scan
  90430. for (index = 0; index < adjacencies.length; index++) {
  90431. faceAdjacencies = adjacencies[index];
  90432. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90433. var otherFaceAdjacencies = adjacencies[otherIndex];
  90434. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90435. break;
  90436. }
  90437. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90438. continue;
  90439. }
  90440. var otherP0 = indices[otherIndex * 3];
  90441. var otherP1 = indices[otherIndex * 3 + 1];
  90442. var otherP2 = indices[otherIndex * 3 + 2];
  90443. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90444. var otherEdgeIndex = 0;
  90445. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90446. continue;
  90447. }
  90448. switch (edgeIndex) {
  90449. case 0:
  90450. if (this._checkVerticesInsteadOfIndices) {
  90451. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90452. }
  90453. else {
  90454. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90455. }
  90456. break;
  90457. case 1:
  90458. if (this._checkVerticesInsteadOfIndices) {
  90459. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90460. }
  90461. else {
  90462. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  90463. }
  90464. break;
  90465. case 2:
  90466. if (this._checkVerticesInsteadOfIndices) {
  90467. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90468. }
  90469. else {
  90470. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  90471. }
  90472. break;
  90473. }
  90474. if (otherEdgeIndex === -1) {
  90475. continue;
  90476. }
  90477. faceAdjacencies.edges[edgeIndex] = otherIndex;
  90478. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  90479. faceAdjacencies.edgesConnectedCount++;
  90480. otherFaceAdjacencies.edgesConnectedCount++;
  90481. if (faceAdjacencies.edgesConnectedCount === 3) {
  90482. break;
  90483. }
  90484. }
  90485. }
  90486. }
  90487. // Create lines
  90488. for (index = 0; index < adjacencies.length; index++) {
  90489. // 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
  90490. var current = adjacencies[index];
  90491. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  90492. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  90493. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  90494. }
  90495. // Merge into a single mesh
  90496. var engine = this._source.getScene().getEngine();
  90497. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  90498. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  90499. this._ib = engine.createIndexBuffer(this._linesIndices);
  90500. this._indicesCount = this._linesIndices.length;
  90501. };
  90502. EdgesRenderer.prototype.render = function () {
  90503. var scene = this._source.getScene();
  90504. if (!this._lineShader.isReady() || !scene.activeCamera) {
  90505. return;
  90506. }
  90507. var engine = scene.getEngine();
  90508. this._lineShader._preBind();
  90509. // VBOs
  90510. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  90511. scene.resetCachedMaterial();
  90512. this._lineShader.setColor4("color", this._source.edgesColor);
  90513. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  90514. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  90515. }
  90516. else {
  90517. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  90518. }
  90519. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  90520. this._lineShader.bind(this._source.getWorldMatrix());
  90521. // Draw order
  90522. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  90523. this._lineShader.unbind();
  90524. engine.setDepthWrite(true);
  90525. };
  90526. return EdgesRenderer;
  90527. }());
  90528. BABYLON.EdgesRenderer = EdgesRenderer;
  90529. })(BABYLON || (BABYLON = {}));
  90530. //# sourceMappingURL=babylon.edgesRenderer.js.map
  90531. var __assign = (this && this.__assign) || Object.assign || function(t) {
  90532. for (var s, i = 1, n = arguments.length; i < n; i++) {
  90533. s = arguments[i];
  90534. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  90535. t[p] = s[p];
  90536. }
  90537. return t;
  90538. };
  90539. var BABYLON;
  90540. (function (BABYLON) {
  90541. /**
  90542. * The effect layer Helps adding post process effect blended with the main pass.
  90543. *
  90544. * This can be for instance use to generate glow or higlight effects on the scene.
  90545. *
  90546. * The effect layer class can not be used directly and is intented to inherited from to be
  90547. * customized per effects.
  90548. */
  90549. var EffectLayer = /** @class */ (function () {
  90550. /**
  90551. * Instantiates a new effect Layer and references it in the scene.
  90552. * @param name The name of the layer
  90553. * @param scene The scene to use the layer in
  90554. */
  90555. function EffectLayer(
  90556. /** The Friendly of the effect in the scene */
  90557. name, scene) {
  90558. this._vertexBuffers = {};
  90559. this._maxSize = 0;
  90560. this._mainTextureDesiredSize = { width: 0, height: 0 };
  90561. this._shouldRender = true;
  90562. this._postProcesses = [];
  90563. this._textures = [];
  90564. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  90565. /**
  90566. * The clear color of the texture used to generate the glow map.
  90567. */
  90568. this.neutralColor = new BABYLON.Color4();
  90569. /**
  90570. * Specifies wether the highlight layer is enabled or not.
  90571. */
  90572. this.isEnabled = true;
  90573. /**
  90574. * An event triggered when the effect layer has been disposed.
  90575. */
  90576. this.onDisposeObservable = new BABYLON.Observable();
  90577. /**
  90578. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  90579. */
  90580. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  90581. /**
  90582. * An event triggered when the generated texture is being merged in the scene.
  90583. */
  90584. this.onBeforeComposeObservable = new BABYLON.Observable();
  90585. /**
  90586. * An event triggered when the generated texture has been merged in the scene.
  90587. */
  90588. this.onAfterComposeObservable = new BABYLON.Observable();
  90589. /**
  90590. * An event triggered when the efffect layer changes its size.
  90591. */
  90592. this.onSizeChangedObservable = new BABYLON.Observable();
  90593. this.name = name;
  90594. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90595. this._engine = scene.getEngine();
  90596. this._maxSize = this._engine.getCaps().maxTextureSize;
  90597. this._scene.effectLayers.push(this);
  90598. // Generate Buffers
  90599. this._generateIndexBuffer();
  90600. this._genrateVertexBuffer();
  90601. }
  90602. Object.defineProperty(EffectLayer.prototype, "camera", {
  90603. /**
  90604. * Gets the camera attached to the layer.
  90605. */
  90606. get: function () {
  90607. return this._effectLayerOptions.camera;
  90608. },
  90609. enumerable: true,
  90610. configurable: true
  90611. });
  90612. /**
  90613. * Initializes the effect layer with the required options.
  90614. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  90615. */
  90616. EffectLayer.prototype._init = function (options) {
  90617. // Adapt options
  90618. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  90619. this._setMainTextureSize();
  90620. this._createMainTexture();
  90621. this._createTextureAndPostProcesses();
  90622. this._mergeEffect = this._createMergeEffect();
  90623. };
  90624. /**
  90625. * Generates the index buffer of the full screen quad blending to the main canvas.
  90626. */
  90627. EffectLayer.prototype._generateIndexBuffer = function () {
  90628. // Indices
  90629. var indices = [];
  90630. indices.push(0);
  90631. indices.push(1);
  90632. indices.push(2);
  90633. indices.push(0);
  90634. indices.push(2);
  90635. indices.push(3);
  90636. this._indexBuffer = this._engine.createIndexBuffer(indices);
  90637. };
  90638. /**
  90639. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  90640. */
  90641. EffectLayer.prototype._genrateVertexBuffer = function () {
  90642. // VBO
  90643. var vertices = [];
  90644. vertices.push(1, 1);
  90645. vertices.push(-1, 1);
  90646. vertices.push(-1, -1);
  90647. vertices.push(1, -1);
  90648. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  90649. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  90650. };
  90651. /**
  90652. * Sets the main texture desired size which is the closest power of two
  90653. * of the engine canvas size.
  90654. */
  90655. EffectLayer.prototype._setMainTextureSize = function () {
  90656. if (this._effectLayerOptions.mainTextureFixedSize) {
  90657. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  90658. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  90659. }
  90660. else {
  90661. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  90662. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  90663. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  90664. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  90665. }
  90666. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  90667. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  90668. };
  90669. /**
  90670. * Creates the main texture for the effect layer.
  90671. */
  90672. EffectLayer.prototype._createMainTexture = function () {
  90673. var _this = this;
  90674. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  90675. width: this._mainTextureDesiredSize.width,
  90676. height: this._mainTextureDesiredSize.height
  90677. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  90678. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  90679. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90680. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  90681. this._mainTexture.anisotropicFilteringLevel = 1;
  90682. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  90683. this._mainTexture.renderParticles = false;
  90684. this._mainTexture.renderList = null;
  90685. this._mainTexture.ignoreCameraViewport = true;
  90686. // Custom render function
  90687. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  90688. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  90689. var index;
  90690. var engine = _this._scene.getEngine();
  90691. if (depthOnlySubMeshes.length) {
  90692. engine.setColorWrite(false);
  90693. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  90694. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  90695. }
  90696. engine.setColorWrite(true);
  90697. }
  90698. for (index = 0; index < opaqueSubMeshes.length; index++) {
  90699. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  90700. }
  90701. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  90702. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  90703. }
  90704. for (index = 0; index < transparentSubMeshes.length; index++) {
  90705. _this._renderSubMesh(transparentSubMeshes.data[index]);
  90706. }
  90707. };
  90708. this._mainTexture.onClearObservable.add(function (engine) {
  90709. engine.clear(_this.neutralColor, true, true, true);
  90710. });
  90711. };
  90712. /**
  90713. * Checks for the readiness of the element composing the layer.
  90714. * @param subMesh the mesh to check for
  90715. * @param useInstances specify wether or not to use instances to render the mesh
  90716. * @param emissiveTexture the associated emissive texture used to generate the glow
  90717. * @return true if ready otherwise, false
  90718. */
  90719. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  90720. var material = subMesh.getMaterial();
  90721. if (!material) {
  90722. return false;
  90723. }
  90724. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  90725. return false;
  90726. }
  90727. var defines = [];
  90728. var attribs = [BABYLON.VertexBuffer.PositionKind];
  90729. var mesh = subMesh.getMesh();
  90730. var uv1 = false;
  90731. var uv2 = false;
  90732. // Alpha test
  90733. if (material && material.needAlphaTesting()) {
  90734. var alphaTexture = material.getAlphaTestTexture();
  90735. if (alphaTexture) {
  90736. defines.push("#define ALPHATEST");
  90737. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90738. alphaTexture.coordinatesIndex === 1) {
  90739. defines.push("#define DIFFUSEUV2");
  90740. uv2 = true;
  90741. }
  90742. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90743. defines.push("#define DIFFUSEUV1");
  90744. uv1 = true;
  90745. }
  90746. }
  90747. }
  90748. // Emissive
  90749. if (emissiveTexture) {
  90750. defines.push("#define EMISSIVE");
  90751. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  90752. emissiveTexture.coordinatesIndex === 1) {
  90753. defines.push("#define EMISSIVEUV2");
  90754. uv2 = true;
  90755. }
  90756. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90757. defines.push("#define EMISSIVEUV1");
  90758. uv1 = true;
  90759. }
  90760. }
  90761. if (uv1) {
  90762. attribs.push(BABYLON.VertexBuffer.UVKind);
  90763. defines.push("#define UV1");
  90764. }
  90765. if (uv2) {
  90766. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90767. defines.push("#define UV2");
  90768. }
  90769. // Bones
  90770. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90771. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90772. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90773. if (mesh.numBoneInfluencers > 4) {
  90774. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90775. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90776. }
  90777. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90778. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  90779. }
  90780. else {
  90781. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90782. }
  90783. // Morph targets
  90784. var manager = mesh.morphTargetManager;
  90785. var morphInfluencers = 0;
  90786. if (manager) {
  90787. if (manager.numInfluencers > 0) {
  90788. defines.push("#define MORPHTARGETS");
  90789. morphInfluencers = manager.numInfluencers;
  90790. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  90791. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  90792. }
  90793. }
  90794. // Instances
  90795. if (useInstances) {
  90796. defines.push("#define INSTANCES");
  90797. attribs.push("world0");
  90798. attribs.push("world1");
  90799. attribs.push("world2");
  90800. attribs.push("world3");
  90801. }
  90802. // Get correct effect
  90803. var join = defines.join("\n");
  90804. if (this._cachedDefines !== join) {
  90805. this._cachedDefines = join;
  90806. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  90807. }
  90808. return this._effectLayerMapGenerationEffect.isReady();
  90809. };
  90810. /**
  90811. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  90812. */
  90813. EffectLayer.prototype.render = function () {
  90814. var currentEffect = this._mergeEffect;
  90815. // Check
  90816. if (!currentEffect.isReady())
  90817. return;
  90818. for (var i = 0; i < this._postProcesses.length; i++) {
  90819. if (!this._postProcesses[i].isReady()) {
  90820. return;
  90821. }
  90822. }
  90823. var engine = this._scene.getEngine();
  90824. this.onBeforeComposeObservable.notifyObservers(this);
  90825. // Render
  90826. engine.enableEffect(currentEffect);
  90827. engine.setState(false);
  90828. // VBOs
  90829. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  90830. // Cache
  90831. var previousAlphaMode = engine.getAlphaMode();
  90832. // Go Blend.
  90833. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  90834. // Blends the map on the main canvas.
  90835. this._internalRender(currentEffect);
  90836. // Restore Alpha
  90837. engine.setAlphaMode(previousAlphaMode);
  90838. this.onAfterComposeObservable.notifyObservers(this);
  90839. // Handle size changes.
  90840. var size = this._mainTexture.getSize();
  90841. this._setMainTextureSize();
  90842. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  90843. // Recreate RTT and post processes on size change.
  90844. this.onSizeChangedObservable.notifyObservers(this);
  90845. this._disposeTextureAndPostProcesses();
  90846. this._createMainTexture();
  90847. this._createTextureAndPostProcesses();
  90848. }
  90849. };
  90850. /**
  90851. * Determine if a given mesh will be used in the current effect.
  90852. * @param mesh mesh to test
  90853. * @returns true if the mesh will be used
  90854. */
  90855. EffectLayer.prototype.hasMesh = function (mesh) {
  90856. return true;
  90857. };
  90858. /**
  90859. * Returns true if the layer contains information to display, otherwise false.
  90860. * @returns true if the glow layer should be rendered
  90861. */
  90862. EffectLayer.prototype.shouldRender = function () {
  90863. return this.isEnabled && this._shouldRender;
  90864. };
  90865. /**
  90866. * Returns true if the mesh should render, otherwise false.
  90867. * @param mesh The mesh to render
  90868. * @returns true if it should render otherwise false
  90869. */
  90870. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  90871. return true;
  90872. };
  90873. /**
  90874. * Returns true if the mesh should render, otherwise false.
  90875. * @param mesh The mesh to render
  90876. * @returns true if it should render otherwise false
  90877. */
  90878. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  90879. return true;
  90880. };
  90881. /**
  90882. * Renders the submesh passed in parameter to the generation map.
  90883. */
  90884. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  90885. var _this = this;
  90886. if (!this.shouldRender()) {
  90887. return;
  90888. }
  90889. var material = subMesh.getMaterial();
  90890. var mesh = subMesh.getRenderingMesh();
  90891. var scene = this._scene;
  90892. var engine = scene.getEngine();
  90893. if (!material) {
  90894. return;
  90895. }
  90896. // Do not block in blend mode.
  90897. if (material.needAlphaBlendingForMesh(mesh)) {
  90898. return;
  90899. }
  90900. // Culling
  90901. engine.setState(material.backFaceCulling);
  90902. // Managing instances
  90903. var batch = mesh._getInstancesRenderList(subMesh._id);
  90904. if (batch.mustReturn) {
  90905. return;
  90906. }
  90907. // Early Exit per mesh
  90908. if (!this._shouldRenderMesh(mesh)) {
  90909. return;
  90910. }
  90911. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90912. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  90913. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  90914. engine.enableEffect(this._effectLayerMapGenerationEffect);
  90915. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  90916. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  90917. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  90918. // Alpha test
  90919. if (material && material.needAlphaTesting()) {
  90920. var alphaTexture = material.getAlphaTestTexture();
  90921. if (alphaTexture) {
  90922. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  90923. var textureMatrix = alphaTexture.getTextureMatrix();
  90924. if (textureMatrix) {
  90925. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  90926. }
  90927. }
  90928. }
  90929. // Glow emissive only
  90930. if (this._emissiveTextureAndColor.texture) {
  90931. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  90932. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  90933. }
  90934. // Bones
  90935. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90936. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90937. }
  90938. // Morph targets
  90939. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  90940. // Draw
  90941. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  90942. }
  90943. else {
  90944. // Need to reset refresh rate of the shadowMap
  90945. this._mainTexture.resetRefreshCounter();
  90946. }
  90947. };
  90948. /**
  90949. * Rebuild the required buffers.
  90950. * @ignore Internal use only.
  90951. */
  90952. EffectLayer.prototype._rebuild = function () {
  90953. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90954. if (vb) {
  90955. vb._rebuild();
  90956. }
  90957. this._generateIndexBuffer();
  90958. };
  90959. /**
  90960. * Dispose only the render target textures and post process.
  90961. */
  90962. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  90963. this._mainTexture.dispose();
  90964. for (var i = 0; i < this._postProcesses.length; i++) {
  90965. if (this._postProcesses[i]) {
  90966. this._postProcesses[i].dispose();
  90967. }
  90968. }
  90969. this._postProcesses = [];
  90970. for (var i = 0; i < this._textures.length; i++) {
  90971. if (this._textures[i]) {
  90972. this._textures[i].dispose();
  90973. }
  90974. }
  90975. this._textures = [];
  90976. };
  90977. /**
  90978. * Dispose the highlight layer and free resources.
  90979. */
  90980. EffectLayer.prototype.dispose = function () {
  90981. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  90982. if (vertexBuffer) {
  90983. vertexBuffer.dispose();
  90984. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  90985. }
  90986. if (this._indexBuffer) {
  90987. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  90988. this._indexBuffer = null;
  90989. }
  90990. // Clean textures and post processes
  90991. this._disposeTextureAndPostProcesses();
  90992. // Remove from scene
  90993. var index = this._scene.effectLayers.indexOf(this, 0);
  90994. if (index > -1) {
  90995. this._scene.effectLayers.splice(index, 1);
  90996. }
  90997. // Callback
  90998. this.onDisposeObservable.notifyObservers(this);
  90999. this.onDisposeObservable.clear();
  91000. this.onBeforeRenderMainTextureObservable.clear();
  91001. this.onBeforeComposeObservable.clear();
  91002. this.onAfterComposeObservable.clear();
  91003. this.onSizeChangedObservable.clear();
  91004. };
  91005. /**
  91006. * Gets the class name of the effect layer
  91007. * @returns the string with the class name of the effect layer
  91008. */
  91009. EffectLayer.prototype.getClassName = function () {
  91010. return "EffectLayer";
  91011. };
  91012. /**
  91013. * Creates an effect layer from parsed effect layer data
  91014. * @param parsedEffectLayer defines effect layer data
  91015. * @param scene defines the current scene
  91016. * @param rootUrl defines the root URL containing the effect layer information
  91017. * @returns a parsed effect Layer
  91018. */
  91019. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91020. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91021. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91022. };
  91023. __decorate([
  91024. BABYLON.serialize()
  91025. ], EffectLayer.prototype, "name", void 0);
  91026. __decorate([
  91027. BABYLON.serializeAsColor4()
  91028. ], EffectLayer.prototype, "neutralColor", void 0);
  91029. __decorate([
  91030. BABYLON.serialize()
  91031. ], EffectLayer.prototype, "isEnabled", void 0);
  91032. __decorate([
  91033. BABYLON.serializeAsCameraReference()
  91034. ], EffectLayer.prototype, "camera", null);
  91035. return EffectLayer;
  91036. }());
  91037. BABYLON.EffectLayer = EffectLayer;
  91038. })(BABYLON || (BABYLON = {}));
  91039. //# sourceMappingURL=babylon.effectLayer.js.map
  91040. var BABYLON;
  91041. (function (BABYLON) {
  91042. /**
  91043. * Special Glow Blur post process only blurring the alpha channel
  91044. * It enforces keeping the most luminous color in the color channel.
  91045. */
  91046. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91047. __extends(GlowBlurPostProcess, _super);
  91048. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91049. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91050. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91051. _this.direction = direction;
  91052. _this.kernel = kernel;
  91053. _this.onApplyObservable.add(function (effect) {
  91054. effect.setFloat2("screenSize", _this.width, _this.height);
  91055. effect.setVector2("direction", _this.direction);
  91056. effect.setFloat("blurWidth", _this.kernel);
  91057. });
  91058. return _this;
  91059. }
  91060. return GlowBlurPostProcess;
  91061. }(BABYLON.PostProcess));
  91062. /**
  91063. * The highlight layer Helps adding a glow effect around a mesh.
  91064. *
  91065. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91066. * glowy meshes to your scene.
  91067. *
  91068. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91069. */
  91070. var HighlightLayer = /** @class */ (function (_super) {
  91071. __extends(HighlightLayer, _super);
  91072. /**
  91073. * Instantiates a new highlight Layer and references it to the scene..
  91074. * @param name The name of the layer
  91075. * @param scene The scene to use the layer in
  91076. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91077. */
  91078. function HighlightLayer(name, scene, options) {
  91079. var _this = _super.call(this, name, scene) || this;
  91080. _this.name = name;
  91081. /**
  91082. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91083. */
  91084. _this.innerGlow = true;
  91085. /**
  91086. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91087. */
  91088. _this.outerGlow = true;
  91089. /**
  91090. * An event triggered when the highlight layer is being blurred.
  91091. */
  91092. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91093. /**
  91094. * An event triggered when the highlight layer has been blurred.
  91095. */
  91096. _this.onAfterBlurObservable = new BABYLON.Observable();
  91097. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91098. _this._meshes = {};
  91099. _this._excludedMeshes = {};
  91100. _this.neutralColor = HighlightLayer.NeutralColor;
  91101. // Warn on stencil
  91102. if (!_this._engine.isStencilEnable) {
  91103. 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 }");
  91104. }
  91105. // Adapt options
  91106. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91107. // Initialize the layer
  91108. _this._init({
  91109. alphaBlendingMode: _this._options.alphaBlendingMode,
  91110. camera: _this._options.camera,
  91111. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91112. mainTextureRatio: _this._options.mainTextureRatio
  91113. });
  91114. // Do not render as long as no meshes have been added
  91115. _this._shouldRender = false;
  91116. return _this;
  91117. }
  91118. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91119. /**
  91120. * Gets the horizontal size of the blur.
  91121. */
  91122. get: function () {
  91123. return this._horizontalBlurPostprocess.kernel;
  91124. },
  91125. /**
  91126. * Specifies the horizontal size of the blur.
  91127. */
  91128. set: function (value) {
  91129. this._horizontalBlurPostprocess.kernel = value;
  91130. },
  91131. enumerable: true,
  91132. configurable: true
  91133. });
  91134. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91135. /**
  91136. * Gets the vertical size of the blur.
  91137. */
  91138. get: function () {
  91139. return this._verticalBlurPostprocess.kernel;
  91140. },
  91141. /**
  91142. * Specifies the vertical size of the blur.
  91143. */
  91144. set: function (value) {
  91145. this._verticalBlurPostprocess.kernel = value;
  91146. },
  91147. enumerable: true,
  91148. configurable: true
  91149. });
  91150. /**
  91151. * Get the effect name of the layer.
  91152. * @return The effect name
  91153. */
  91154. HighlightLayer.prototype.getEffectName = function () {
  91155. return HighlightLayer.EffectName;
  91156. };
  91157. /**
  91158. * Create the merge effect. This is the shader use to blit the information back
  91159. * to the main canvas at the end of the scene rendering.
  91160. */
  91161. HighlightLayer.prototype._createMergeEffect = function () {
  91162. // Effect
  91163. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91164. };
  91165. /**
  91166. * Creates the render target textures and post processes used in the highlight layer.
  91167. */
  91168. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91169. var _this = this;
  91170. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91171. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91172. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91173. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91174. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91175. width: blurTextureWidth,
  91176. height: blurTextureHeight
  91177. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91178. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91179. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91180. this._blurTexture.anisotropicFilteringLevel = 16;
  91181. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91182. this._blurTexture.renderParticles = false;
  91183. this._blurTexture.ignoreCameraViewport = true;
  91184. this._textures = [this._blurTexture];
  91185. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91186. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91187. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91188. effect.setTexture("textureSampler", _this._mainTexture);
  91189. });
  91190. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91191. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91192. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91193. });
  91194. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91195. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91196. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91197. });
  91198. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91199. }
  91200. else {
  91201. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91202. width: blurTextureWidth,
  91203. height: blurTextureHeight
  91204. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91205. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91206. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91207. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91208. effect.setTexture("textureSampler", _this._mainTexture);
  91209. });
  91210. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91211. width: blurTextureWidth,
  91212. height: blurTextureHeight
  91213. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91214. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91215. }
  91216. this._mainTexture.onAfterUnbindObservable.add(function () {
  91217. _this.onBeforeBlurObservable.notifyObservers(_this);
  91218. var internalTexture = _this._blurTexture.getInternalTexture();
  91219. if (internalTexture) {
  91220. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91221. }
  91222. _this.onAfterBlurObservable.notifyObservers(_this);
  91223. });
  91224. // Prevent autoClear.
  91225. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91226. };
  91227. /**
  91228. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91229. */
  91230. HighlightLayer.prototype.needStencil = function () {
  91231. return true;
  91232. };
  91233. /**
  91234. * Checks for the readiness of the element composing the layer.
  91235. * @param subMesh the mesh to check for
  91236. * @param useInstances specify wether or not to use instances to render the mesh
  91237. * @param emissiveTexture the associated emissive texture used to generate the glow
  91238. * @return true if ready otherwise, false
  91239. */
  91240. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91241. var material = subMesh.getMaterial();
  91242. var mesh = subMesh.getRenderingMesh();
  91243. if (!material || !mesh || !this._meshes) {
  91244. return false;
  91245. }
  91246. var emissiveTexture = null;
  91247. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91248. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91249. emissiveTexture = material.emissiveTexture;
  91250. }
  91251. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91252. };
  91253. /**
  91254. * Implementation specific of rendering the generating effect on the main canvas.
  91255. * @param effect The effect used to render through
  91256. */
  91257. HighlightLayer.prototype._internalRender = function (effect) {
  91258. // Texture
  91259. effect.setTexture("textureSampler", this._blurTexture);
  91260. // Cache
  91261. var engine = this._engine;
  91262. var previousStencilBuffer = engine.getStencilBuffer();
  91263. var previousStencilFunction = engine.getStencilFunction();
  91264. var previousStencilMask = engine.getStencilMask();
  91265. var previousStencilOperationPass = engine.getStencilOperationPass();
  91266. var previousStencilOperationFail = engine.getStencilOperationFail();
  91267. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91268. var previousStencilReference = engine.getStencilFunctionReference();
  91269. // Stencil operations
  91270. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91271. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91272. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91273. // Draw order
  91274. engine.setStencilMask(0x00);
  91275. engine.setStencilBuffer(true);
  91276. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91277. // 2 passes inner outer
  91278. if (this.outerGlow) {
  91279. effect.setFloat("offset", 0);
  91280. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91281. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91282. }
  91283. if (this.innerGlow) {
  91284. effect.setFloat("offset", 1);
  91285. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91286. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91287. }
  91288. // Restore Cache
  91289. engine.setStencilFunction(previousStencilFunction);
  91290. engine.setStencilMask(previousStencilMask);
  91291. engine.setStencilBuffer(previousStencilBuffer);
  91292. engine.setStencilOperationPass(previousStencilOperationPass);
  91293. engine.setStencilOperationFail(previousStencilOperationFail);
  91294. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91295. engine.setStencilFunctionReference(previousStencilReference);
  91296. };
  91297. /**
  91298. * Returns true if the layer contains information to display, otherwise false.
  91299. */
  91300. HighlightLayer.prototype.shouldRender = function () {
  91301. if (_super.prototype.shouldRender.call(this)) {
  91302. return this._meshes ? true : false;
  91303. }
  91304. return false;
  91305. };
  91306. /**
  91307. * Returns true if the mesh should render, otherwise false.
  91308. * @param mesh The mesh to render
  91309. * @returns true if it should render otherwise false
  91310. */
  91311. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91312. // Excluded Mesh
  91313. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91314. return false;
  91315. }
  91316. ;
  91317. return true;
  91318. };
  91319. /**
  91320. * Sets the required values for both the emissive texture and and the main color.
  91321. */
  91322. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91323. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91324. if (highlightLayerMesh) {
  91325. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91326. }
  91327. else {
  91328. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91329. }
  91330. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91331. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91332. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91333. }
  91334. else {
  91335. this._emissiveTextureAndColor.texture = null;
  91336. }
  91337. };
  91338. /**
  91339. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91340. * @param mesh The mesh to exclude from the highlight layer
  91341. */
  91342. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91343. if (!this._excludedMeshes) {
  91344. return;
  91345. }
  91346. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91347. if (!meshExcluded) {
  91348. this._excludedMeshes[mesh.uniqueId] = {
  91349. mesh: mesh,
  91350. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91351. mesh.getEngine().setStencilBuffer(false);
  91352. }),
  91353. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91354. mesh.getEngine().setStencilBuffer(true);
  91355. }),
  91356. };
  91357. }
  91358. };
  91359. /**
  91360. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91361. * @param mesh The mesh to highlight
  91362. */
  91363. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91364. if (!this._excludedMeshes) {
  91365. return;
  91366. }
  91367. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91368. if (meshExcluded) {
  91369. if (meshExcluded.beforeRender) {
  91370. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91371. }
  91372. if (meshExcluded.afterRender) {
  91373. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91374. }
  91375. }
  91376. this._excludedMeshes[mesh.uniqueId] = null;
  91377. };
  91378. /**
  91379. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91380. * @param mesh mesh to test
  91381. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91382. */
  91383. HighlightLayer.prototype.hasMesh = function (mesh) {
  91384. if (!this._meshes) {
  91385. return false;
  91386. }
  91387. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91388. };
  91389. /**
  91390. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91391. * @param mesh The mesh to highlight
  91392. * @param color The color of the highlight
  91393. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91394. */
  91395. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91396. var _this = this;
  91397. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91398. if (!this._meshes) {
  91399. return;
  91400. }
  91401. var meshHighlight = this._meshes[mesh.uniqueId];
  91402. if (meshHighlight) {
  91403. meshHighlight.color = color;
  91404. }
  91405. else {
  91406. this._meshes[mesh.uniqueId] = {
  91407. mesh: mesh,
  91408. color: color,
  91409. // Lambda required for capture due to Observable this context
  91410. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91411. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91412. _this._defaultStencilReference(mesh);
  91413. }
  91414. else {
  91415. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91416. }
  91417. }),
  91418. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91419. glowEmissiveOnly: glowEmissiveOnly
  91420. };
  91421. }
  91422. this._shouldRender = true;
  91423. };
  91424. /**
  91425. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91426. * @param mesh The mesh to highlight
  91427. */
  91428. HighlightLayer.prototype.removeMesh = function (mesh) {
  91429. if (!this._meshes) {
  91430. return;
  91431. }
  91432. var meshHighlight = this._meshes[mesh.uniqueId];
  91433. if (meshHighlight) {
  91434. if (meshHighlight.observerHighlight) {
  91435. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91436. }
  91437. if (meshHighlight.observerDefault) {
  91438. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91439. }
  91440. delete this._meshes[mesh.uniqueId];
  91441. }
  91442. this._shouldRender = false;
  91443. for (var meshHighlightToCheck in this._meshes) {
  91444. if (this._meshes[meshHighlightToCheck]) {
  91445. this._shouldRender = true;
  91446. break;
  91447. }
  91448. }
  91449. };
  91450. /**
  91451. * Force the stencil to the normal expected value for none glowing parts
  91452. */
  91453. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91454. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91455. };
  91456. /**
  91457. * Free any resources and references associated to a mesh.
  91458. * Internal use
  91459. * @param mesh The mesh to free.
  91460. */
  91461. HighlightLayer.prototype._disposeMesh = function (mesh) {
  91462. this.removeMesh(mesh);
  91463. this.removeExcludedMesh(mesh);
  91464. };
  91465. /**
  91466. * Dispose the highlight layer and free resources.
  91467. */
  91468. HighlightLayer.prototype.dispose = function () {
  91469. if (this._meshes) {
  91470. // Clean mesh references
  91471. for (var id in this._meshes) {
  91472. var meshHighlight = this._meshes[id];
  91473. if (meshHighlight && meshHighlight.mesh) {
  91474. if (meshHighlight.observerHighlight) {
  91475. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91476. }
  91477. if (meshHighlight.observerDefault) {
  91478. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91479. }
  91480. }
  91481. }
  91482. this._meshes = null;
  91483. }
  91484. if (this._excludedMeshes) {
  91485. for (var id in this._excludedMeshes) {
  91486. var meshHighlight = this._excludedMeshes[id];
  91487. if (meshHighlight) {
  91488. if (meshHighlight.beforeRender) {
  91489. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  91490. }
  91491. if (meshHighlight.afterRender) {
  91492. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  91493. }
  91494. }
  91495. }
  91496. this._excludedMeshes = null;
  91497. }
  91498. _super.prototype.dispose.call(this);
  91499. };
  91500. /**
  91501. * Gets the class name of the effect layer
  91502. * @returns the string with the class name of the effect layer
  91503. */
  91504. HighlightLayer.prototype.getClassName = function () {
  91505. return "HighlightLayer";
  91506. };
  91507. /**
  91508. * Serializes this Highlight layer
  91509. * @returns a serialized Highlight layer object
  91510. */
  91511. HighlightLayer.prototype.serialize = function () {
  91512. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91513. serializationObject.customType = "BABYLON.HighlightLayer";
  91514. // Highlighted meshes
  91515. serializationObject.meshes = [];
  91516. if (this._meshes) {
  91517. for (var m in this._meshes) {
  91518. var mesh = this._meshes[m];
  91519. if (mesh) {
  91520. serializationObject.meshes.push({
  91521. glowEmissiveOnly: mesh.glowEmissiveOnly,
  91522. color: mesh.color.asArray(),
  91523. meshId: mesh.mesh.id
  91524. });
  91525. }
  91526. }
  91527. }
  91528. // Excluded meshes
  91529. serializationObject.excludedMeshes = [];
  91530. if (this._excludedMeshes) {
  91531. for (var e in this._excludedMeshes) {
  91532. var excludedMesh = this._excludedMeshes[e];
  91533. if (excludedMesh) {
  91534. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  91535. }
  91536. }
  91537. }
  91538. return serializationObject;
  91539. };
  91540. /**
  91541. * Creates a Highlight layer from parsed Highlight layer data
  91542. * @param parsedHightlightLayer defines the Highlight layer data
  91543. * @param scene defines the current scene
  91544. * @param rootUrl defines the root URL containing the Highlight layer information
  91545. * @returns a parsed Highlight layer
  91546. */
  91547. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  91548. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  91549. var index;
  91550. // Excluded meshes
  91551. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  91552. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  91553. if (mesh) {
  91554. hl.addExcludedMesh(mesh);
  91555. }
  91556. }
  91557. // Included meshes
  91558. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  91559. var highlightedMesh = parsedHightlightLayer.meshes[index];
  91560. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  91561. if (mesh) {
  91562. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  91563. }
  91564. }
  91565. return hl;
  91566. };
  91567. /**
  91568. * Effect Name of the highlight layer.
  91569. */
  91570. HighlightLayer.EffectName = "HighlightLayer";
  91571. /**
  91572. * The neutral color used during the preparation of the glow effect.
  91573. * This is black by default as the blend operation is a blend operation.
  91574. */
  91575. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  91576. /**
  91577. * Stencil value used for glowing meshes.
  91578. */
  91579. HighlightLayer.GlowingMeshStencilReference = 0x02;
  91580. /**
  91581. * Stencil value used for the other meshes in the scene.
  91582. */
  91583. HighlightLayer.NormalMeshStencilReference = 0x01;
  91584. __decorate([
  91585. BABYLON.serialize()
  91586. ], HighlightLayer.prototype, "innerGlow", void 0);
  91587. __decorate([
  91588. BABYLON.serialize()
  91589. ], HighlightLayer.prototype, "outerGlow", void 0);
  91590. __decorate([
  91591. BABYLON.serialize()
  91592. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  91593. __decorate([
  91594. BABYLON.serialize()
  91595. ], HighlightLayer.prototype, "blurVerticalSize", null);
  91596. __decorate([
  91597. BABYLON.serialize("options")
  91598. ], HighlightLayer.prototype, "_options", void 0);
  91599. return HighlightLayer;
  91600. }(BABYLON.EffectLayer));
  91601. BABYLON.HighlightLayer = HighlightLayer;
  91602. })(BABYLON || (BABYLON = {}));
  91603. //# sourceMappingURL=babylon.highlightLayer.js.map
  91604. var BABYLON;
  91605. (function (BABYLON) {
  91606. /**
  91607. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  91608. *
  91609. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91610. * glowy meshes to your scene.
  91611. *
  91612. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  91613. */
  91614. var GlowLayer = /** @class */ (function (_super) {
  91615. __extends(GlowLayer, _super);
  91616. /**
  91617. * Instantiates a new glow Layer and references it to the scene.
  91618. * @param name The name of the layer
  91619. * @param scene The scene to use the layer in
  91620. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  91621. */
  91622. function GlowLayer(name, scene, options) {
  91623. var _this = _super.call(this, name, scene) || this;
  91624. _this._intensity = 1.0;
  91625. _this._includedOnlyMeshes = [];
  91626. _this._excludedMeshes = [];
  91627. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  91628. // Adapt options
  91629. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  91630. // Initialize the layer
  91631. _this._init({
  91632. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  91633. camera: _this._options.camera,
  91634. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91635. mainTextureRatio: _this._options.mainTextureRatio
  91636. });
  91637. return _this;
  91638. }
  91639. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  91640. /**
  91641. * Gets the kernel size of the blur.
  91642. */
  91643. get: function () {
  91644. return this._horizontalBlurPostprocess1.kernel;
  91645. },
  91646. /**
  91647. * Sets the kernel size of the blur.
  91648. */
  91649. set: function (value) {
  91650. this._horizontalBlurPostprocess1.kernel = value;
  91651. this._verticalBlurPostprocess1.kernel = value;
  91652. this._horizontalBlurPostprocess2.kernel = value;
  91653. this._verticalBlurPostprocess2.kernel = value;
  91654. },
  91655. enumerable: true,
  91656. configurable: true
  91657. });
  91658. Object.defineProperty(GlowLayer.prototype, "intensity", {
  91659. /**
  91660. * Gets the glow intensity.
  91661. */
  91662. get: function () {
  91663. return this._intensity;
  91664. },
  91665. /**
  91666. * Sets the glow intensity.
  91667. */
  91668. set: function (value) {
  91669. this._intensity = value;
  91670. },
  91671. enumerable: true,
  91672. configurable: true
  91673. });
  91674. /**
  91675. * Get the effect name of the layer.
  91676. * @return The effect name
  91677. */
  91678. GlowLayer.prototype.getEffectName = function () {
  91679. return GlowLayer.EffectName;
  91680. };
  91681. /**
  91682. * Create the merge effect. This is the shader use to blit the information back
  91683. * to the main canvas at the end of the scene rendering.
  91684. */
  91685. GlowLayer.prototype._createMergeEffect = function () {
  91686. // Effect
  91687. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  91688. };
  91689. /**
  91690. * Creates the render target textures and post processes used in the glow layer.
  91691. */
  91692. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  91693. var _this = this;
  91694. var blurTextureWidth = this._mainTextureDesiredSize.width;
  91695. var blurTextureHeight = this._mainTextureDesiredSize.height;
  91696. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91697. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91698. var textureType = 0;
  91699. if (this._engine.getCaps().textureHalfFloatRender) {
  91700. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  91701. }
  91702. else {
  91703. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  91704. }
  91705. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  91706. width: blurTextureWidth,
  91707. height: blurTextureHeight
  91708. }, this._scene, false, true, textureType);
  91709. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91710. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91711. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91712. this._blurTexture1.renderParticles = false;
  91713. this._blurTexture1.ignoreCameraViewport = true;
  91714. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  91715. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  91716. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  91717. width: blurTextureWidth2,
  91718. height: blurTextureHeight2
  91719. }, this._scene, false, true, textureType);
  91720. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91721. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91722. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91723. this._blurTexture2.renderParticles = false;
  91724. this._blurTexture2.ignoreCameraViewport = true;
  91725. this._textures = [this._blurTexture1, this._blurTexture2];
  91726. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91727. width: blurTextureWidth,
  91728. height: blurTextureHeight
  91729. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91730. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  91731. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  91732. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  91733. effect.setTexture("textureSampler", _this._mainTexture);
  91734. });
  91735. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91736. width: blurTextureWidth,
  91737. height: blurTextureHeight
  91738. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91739. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  91740. width: blurTextureWidth2,
  91741. height: blurTextureHeight2
  91742. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91743. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  91744. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  91745. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  91746. effect.setTexture("textureSampler", _this._blurTexture1);
  91747. });
  91748. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  91749. width: blurTextureWidth2,
  91750. height: blurTextureHeight2
  91751. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  91752. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91753. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  91754. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  91755. this._mainTexture.samples = this._options.mainTextureSamples;
  91756. this._mainTexture.onAfterUnbindObservable.add(function () {
  91757. var internalTexture = _this._blurTexture1.getInternalTexture();
  91758. if (internalTexture) {
  91759. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  91760. internalTexture = _this._blurTexture2.getInternalTexture();
  91761. if (internalTexture) {
  91762. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  91763. }
  91764. }
  91765. });
  91766. // Prevent autoClear.
  91767. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91768. };
  91769. /**
  91770. * Checks for the readiness of the element composing the layer.
  91771. * @param subMesh the mesh to check for
  91772. * @param useInstances specify wether or not to use instances to render the mesh
  91773. * @param emissiveTexture the associated emissive texture used to generate the glow
  91774. * @return true if ready otherwise, false
  91775. */
  91776. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  91777. var material = subMesh.getMaterial();
  91778. var mesh = subMesh.getRenderingMesh();
  91779. if (!material || !mesh) {
  91780. return false;
  91781. }
  91782. var emissiveTexture = material.emissiveTexture;
  91783. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91784. };
  91785. /**
  91786. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91787. */
  91788. GlowLayer.prototype.needStencil = function () {
  91789. return false;
  91790. };
  91791. /**
  91792. * Implementation specific of rendering the generating effect on the main canvas.
  91793. * @param effect The effect used to render through
  91794. */
  91795. GlowLayer.prototype._internalRender = function (effect) {
  91796. // Texture
  91797. effect.setTexture("textureSampler", this._blurTexture1);
  91798. effect.setTexture("textureSampler2", this._blurTexture2);
  91799. effect.setFloat("offset", this._intensity);
  91800. // Cache
  91801. var engine = this._engine;
  91802. var previousStencilBuffer = engine.getStencilBuffer();
  91803. // Draw order
  91804. engine.setStencilBuffer(false);
  91805. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91806. // Draw order
  91807. engine.setStencilBuffer(previousStencilBuffer);
  91808. };
  91809. /**
  91810. * Sets the required values for both the emissive texture and and the main color.
  91811. */
  91812. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91813. var textureLevel = 1.0;
  91814. if (this.customEmissiveTextureSelector) {
  91815. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  91816. }
  91817. else {
  91818. if (material) {
  91819. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91820. if (this._emissiveTextureAndColor.texture) {
  91821. textureLevel = this._emissiveTextureAndColor.texture.level;
  91822. }
  91823. }
  91824. else {
  91825. this._emissiveTextureAndColor.texture = null;
  91826. }
  91827. }
  91828. if (this.customEmissiveColorSelector) {
  91829. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  91830. }
  91831. else {
  91832. if (material.emissiveColor) {
  91833. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  91834. }
  91835. else {
  91836. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91837. }
  91838. }
  91839. };
  91840. /**
  91841. * Returns true if the mesh should render, otherwise false.
  91842. * @param mesh The mesh to render
  91843. * @returns true if it should render otherwise false
  91844. */
  91845. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  91846. return this.hasMesh(mesh);
  91847. };
  91848. /**
  91849. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  91850. * @param mesh The mesh to exclude from the glow layer
  91851. */
  91852. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  91853. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  91854. this._excludedMeshes.push(mesh.uniqueId);
  91855. }
  91856. };
  91857. /**
  91858. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  91859. * @param mesh The mesh to remove
  91860. */
  91861. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  91862. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  91863. if (index !== -1) {
  91864. this._excludedMeshes.splice(index, 1);
  91865. }
  91866. };
  91867. /**
  91868. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  91869. * @param mesh The mesh to include in the glow layer
  91870. */
  91871. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  91872. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  91873. this._includedOnlyMeshes.push(mesh.uniqueId);
  91874. }
  91875. };
  91876. /**
  91877. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  91878. * @param mesh The mesh to remove
  91879. */
  91880. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  91881. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  91882. if (index !== -1) {
  91883. this._includedOnlyMeshes.splice(index, 1);
  91884. }
  91885. };
  91886. /**
  91887. * Determine if a given mesh will be used in the glow layer
  91888. * @param mesh The mesh to test
  91889. * @returns true if the mesh will be highlighted by the current glow layer
  91890. */
  91891. GlowLayer.prototype.hasMesh = function (mesh) {
  91892. // Included Mesh
  91893. if (this._includedOnlyMeshes.length) {
  91894. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  91895. }
  91896. ;
  91897. // Excluded Mesh
  91898. if (this._excludedMeshes.length) {
  91899. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  91900. }
  91901. ;
  91902. return true;
  91903. };
  91904. /**
  91905. * Free any resources and references associated to a mesh.
  91906. * Internal use
  91907. * @param mesh The mesh to free.
  91908. */
  91909. GlowLayer.prototype._disposeMesh = function (mesh) {
  91910. this.removeIncludedOnlyMesh(mesh);
  91911. this.removeExcludedMesh(mesh);
  91912. };
  91913. /**
  91914. * Gets the class name of the effect layer
  91915. * @returns the string with the class name of the effect layer
  91916. */
  91917. GlowLayer.prototype.getClassName = function () {
  91918. return "GlowLayer";
  91919. };
  91920. /**
  91921. * Serializes this glow layer
  91922. * @returns a serialized glow layer object
  91923. */
  91924. GlowLayer.prototype.serialize = function () {
  91925. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91926. serializationObject.customType = "BABYLON.GlowLayer";
  91927. var index;
  91928. // Included meshes
  91929. serializationObject.includedMeshes = [];
  91930. if (this._includedOnlyMeshes.length) {
  91931. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  91932. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  91933. if (mesh) {
  91934. serializationObject.includedMeshes.push(mesh.id);
  91935. }
  91936. }
  91937. }
  91938. // Excluded meshes
  91939. serializationObject.excludedMeshes = [];
  91940. if (this._excludedMeshes.length) {
  91941. for (index = 0; index < this._excludedMeshes.length; index++) {
  91942. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  91943. if (mesh) {
  91944. serializationObject.excludedMeshes.push(mesh.id);
  91945. }
  91946. }
  91947. }
  91948. return serializationObject;
  91949. };
  91950. /**
  91951. * Creates a Glow Layer from parsed glow layer data
  91952. * @param parsedGlowLayer defines glow layer data
  91953. * @param scene defines the current scene
  91954. * @param rootUrl defines the root URL containing the glow layer information
  91955. * @returns a parsed Glow Layer
  91956. */
  91957. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  91958. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  91959. var index;
  91960. // Excluded meshes
  91961. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  91962. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  91963. if (mesh) {
  91964. gl.addExcludedMesh(mesh);
  91965. }
  91966. }
  91967. // Included meshes
  91968. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  91969. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  91970. if (mesh) {
  91971. gl.addIncludedOnlyMesh(mesh);
  91972. }
  91973. }
  91974. return gl;
  91975. };
  91976. /**
  91977. * Effect Name of the layer.
  91978. */
  91979. GlowLayer.EffectName = "GlowLayer";
  91980. /**
  91981. * The default blur kernel size used for the glow.
  91982. */
  91983. GlowLayer.DefaultBlurKernelSize = 32;
  91984. /**
  91985. * The default texture size ratio used for the glow.
  91986. */
  91987. GlowLayer.DefaultTextureRatio = 0.5;
  91988. __decorate([
  91989. BABYLON.serialize()
  91990. ], GlowLayer.prototype, "blurKernelSize", null);
  91991. __decorate([
  91992. BABYLON.serialize()
  91993. ], GlowLayer.prototype, "intensity", null);
  91994. __decorate([
  91995. BABYLON.serialize("options")
  91996. ], GlowLayer.prototype, "_options", void 0);
  91997. return GlowLayer;
  91998. }(BABYLON.EffectLayer));
  91999. BABYLON.GlowLayer = GlowLayer;
  92000. })(BABYLON || (BABYLON = {}));
  92001. //# sourceMappingURL=babylon.glowLayer.js.map
  92002. var BABYLON;
  92003. (function (BABYLON) {
  92004. /**
  92005. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92006. */
  92007. var AssetTaskState;
  92008. (function (AssetTaskState) {
  92009. /**
  92010. * Initialization
  92011. */
  92012. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92013. /**
  92014. * Running
  92015. */
  92016. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92017. /**
  92018. * Done
  92019. */
  92020. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92021. /**
  92022. * Error
  92023. */
  92024. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92025. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92026. /**
  92027. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92028. */
  92029. var AbstractAssetTask = /** @class */ (function () {
  92030. /**
  92031. * Creates a new {BABYLON.AssetsManager}
  92032. * @param name defines the name of the task
  92033. */
  92034. function AbstractAssetTask(
  92035. /**
  92036. * Task name
  92037. */ name) {
  92038. this.name = name;
  92039. this._isCompleted = false;
  92040. this._taskState = AssetTaskState.INIT;
  92041. }
  92042. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92043. /**
  92044. * Get if the task is completed
  92045. */
  92046. get: function () {
  92047. return this._isCompleted;
  92048. },
  92049. enumerable: true,
  92050. configurable: true
  92051. });
  92052. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92053. /**
  92054. * Gets the current state of the task
  92055. */
  92056. get: function () {
  92057. return this._taskState;
  92058. },
  92059. enumerable: true,
  92060. configurable: true
  92061. });
  92062. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92063. /**
  92064. * Gets the current error object (if task is in error)
  92065. */
  92066. get: function () {
  92067. return this._errorObject;
  92068. },
  92069. enumerable: true,
  92070. configurable: true
  92071. });
  92072. /**
  92073. * Internal only
  92074. * @ignore
  92075. */
  92076. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92077. if (this._errorObject) {
  92078. return;
  92079. }
  92080. this._errorObject = {
  92081. message: message,
  92082. exception: exception
  92083. };
  92084. };
  92085. /**
  92086. * Execute the current task
  92087. * @param scene defines the scene where you want your assets to be loaded
  92088. * @param onSuccess is a callback called when the task is successfully executed
  92089. * @param onError is a callback called if an error occurs
  92090. */
  92091. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92092. var _this = this;
  92093. this._taskState = AssetTaskState.RUNNING;
  92094. this.runTask(scene, function () {
  92095. _this.onDoneCallback(onSuccess, onError);
  92096. }, function (msg, exception) {
  92097. _this.onErrorCallback(onError, msg, exception);
  92098. });
  92099. };
  92100. /**
  92101. * Execute the current task
  92102. * @param scene defines the scene where you want your assets to be loaded
  92103. * @param onSuccess is a callback called when the task is successfully executed
  92104. * @param onError is a callback called if an error occurs
  92105. */
  92106. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92107. throw new Error("runTask is not implemented");
  92108. };
  92109. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92110. this._taskState = AssetTaskState.ERROR;
  92111. this._errorObject = {
  92112. message: message,
  92113. exception: exception
  92114. };
  92115. if (this.onError) {
  92116. this.onError(this, message, exception);
  92117. }
  92118. onError();
  92119. };
  92120. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92121. try {
  92122. this._taskState = AssetTaskState.DONE;
  92123. this._isCompleted = true;
  92124. if (this.onSuccess) {
  92125. this.onSuccess(this);
  92126. }
  92127. onSuccess();
  92128. }
  92129. catch (e) {
  92130. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92131. }
  92132. };
  92133. return AbstractAssetTask;
  92134. }());
  92135. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92136. /**
  92137. * Class used to share progress information about assets loading
  92138. */
  92139. var AssetsProgressEvent = /** @class */ (function () {
  92140. /**
  92141. * Creates a {BABYLON.AssetsProgressEvent}
  92142. * @param remainingCount defines the number of remaining tasks to process
  92143. * @param totalCount defines the total number of tasks
  92144. * @param task defines the task that was just processed
  92145. */
  92146. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92147. this.remainingCount = remainingCount;
  92148. this.totalCount = totalCount;
  92149. this.task = task;
  92150. }
  92151. return AssetsProgressEvent;
  92152. }());
  92153. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92154. /**
  92155. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92156. */
  92157. var MeshAssetTask = /** @class */ (function (_super) {
  92158. __extends(MeshAssetTask, _super);
  92159. /**
  92160. * Creates a new {BABYLON.MeshAssetTask}
  92161. * @param name defines the name of the task
  92162. * @param meshesNames defines the list of mesh's names you want to load
  92163. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92164. * @param sceneFilename defines the filename of the scene to load from
  92165. */
  92166. function MeshAssetTask(
  92167. /**
  92168. * Defines the name of the task
  92169. */
  92170. name,
  92171. /**
  92172. * Defines the list of mesh's names you want to load
  92173. */
  92174. meshesNames,
  92175. /**
  92176. * Defines the root url to use as a base to load your meshes and associated resources
  92177. */
  92178. rootUrl,
  92179. /**
  92180. * Defines the filename of the scene to load from
  92181. */
  92182. sceneFilename) {
  92183. var _this = _super.call(this, name) || this;
  92184. _this.name = name;
  92185. _this.meshesNames = meshesNames;
  92186. _this.rootUrl = rootUrl;
  92187. _this.sceneFilename = sceneFilename;
  92188. return _this;
  92189. }
  92190. /**
  92191. * Execute the current task
  92192. * @param scene defines the scene where you want your assets to be loaded
  92193. * @param onSuccess is a callback called when the task is successfully executed
  92194. * @param onError is a callback called if an error occurs
  92195. */
  92196. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92197. var _this = this;
  92198. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92199. _this.loadedMeshes = meshes;
  92200. _this.loadedParticleSystems = particleSystems;
  92201. _this.loadedSkeletons = skeletons;
  92202. onSuccess();
  92203. }, null, function (scene, message, exception) {
  92204. onError(message, exception);
  92205. });
  92206. };
  92207. return MeshAssetTask;
  92208. }(AbstractAssetTask));
  92209. BABYLON.MeshAssetTask = MeshAssetTask;
  92210. /**
  92211. * Define a task used by {BABYLON.AssetsManager} to load text content
  92212. */
  92213. var TextFileAssetTask = /** @class */ (function (_super) {
  92214. __extends(TextFileAssetTask, _super);
  92215. /**
  92216. * Creates a new TextFileAssetTask object
  92217. * @param name defines the name of the task
  92218. * @param url defines the location of the file to load
  92219. */
  92220. function TextFileAssetTask(
  92221. /**
  92222. * Defines the name of the task
  92223. */
  92224. name,
  92225. /**
  92226. * Defines the location of the file to load
  92227. */
  92228. url) {
  92229. var _this = _super.call(this, name) || this;
  92230. _this.name = name;
  92231. _this.url = url;
  92232. return _this;
  92233. }
  92234. /**
  92235. * Execute the current task
  92236. * @param scene defines the scene where you want your assets to be loaded
  92237. * @param onSuccess is a callback called when the task is successfully executed
  92238. * @param onError is a callback called if an error occurs
  92239. */
  92240. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92241. var _this = this;
  92242. scene._loadFile(this.url, function (data) {
  92243. _this.text = data;
  92244. onSuccess();
  92245. }, undefined, false, false, function (request, exception) {
  92246. if (request) {
  92247. onError(request.status + " " + request.statusText, exception);
  92248. }
  92249. });
  92250. };
  92251. return TextFileAssetTask;
  92252. }(AbstractAssetTask));
  92253. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92254. /**
  92255. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92256. */
  92257. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92258. __extends(BinaryFileAssetTask, _super);
  92259. /**
  92260. * Creates a new BinaryFileAssetTask object
  92261. * @param name defines the name of the new task
  92262. * @param url defines the location of the file to load
  92263. */
  92264. function BinaryFileAssetTask(
  92265. /**
  92266. * Defines the name of the task
  92267. */
  92268. name,
  92269. /**
  92270. * Defines the location of the file to load
  92271. */
  92272. url) {
  92273. var _this = _super.call(this, name) || this;
  92274. _this.name = name;
  92275. _this.url = url;
  92276. return _this;
  92277. }
  92278. /**
  92279. * Execute the current task
  92280. * @param scene defines the scene where you want your assets to be loaded
  92281. * @param onSuccess is a callback called when the task is successfully executed
  92282. * @param onError is a callback called if an error occurs
  92283. */
  92284. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92285. var _this = this;
  92286. scene._loadFile(this.url, function (data) {
  92287. _this.data = data;
  92288. onSuccess();
  92289. }, undefined, true, true, function (request, exception) {
  92290. if (request) {
  92291. onError(request.status + " " + request.statusText, exception);
  92292. }
  92293. });
  92294. };
  92295. return BinaryFileAssetTask;
  92296. }(AbstractAssetTask));
  92297. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92298. /**
  92299. * Define a task used by {BABYLON.AssetsManager} to load images
  92300. */
  92301. var ImageAssetTask = /** @class */ (function (_super) {
  92302. __extends(ImageAssetTask, _super);
  92303. /**
  92304. * Creates a new ImageAssetTask
  92305. * @param name defines the name of the task
  92306. * @param url defines the location of the image to load
  92307. */
  92308. function ImageAssetTask(
  92309. /**
  92310. * Defines the name of the task
  92311. */
  92312. name,
  92313. /**
  92314. * Defines the location of the image to load
  92315. */
  92316. url) {
  92317. var _this = _super.call(this, name) || this;
  92318. _this.name = name;
  92319. _this.url = url;
  92320. return _this;
  92321. }
  92322. /**
  92323. * Execute the current task
  92324. * @param scene defines the scene where you want your assets to be loaded
  92325. * @param onSuccess is a callback called when the task is successfully executed
  92326. * @param onError is a callback called if an error occurs
  92327. */
  92328. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92329. var _this = this;
  92330. var img = new Image();
  92331. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92332. img.onload = function () {
  92333. _this.image = img;
  92334. onSuccess();
  92335. };
  92336. img.onerror = function (err) {
  92337. onError("Error loading image", err);
  92338. };
  92339. img.src = this.url;
  92340. };
  92341. return ImageAssetTask;
  92342. }(AbstractAssetTask));
  92343. BABYLON.ImageAssetTask = ImageAssetTask;
  92344. /**
  92345. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92346. */
  92347. var TextureAssetTask = /** @class */ (function (_super) {
  92348. __extends(TextureAssetTask, _super);
  92349. /**
  92350. * Creates a new TextureAssetTask object
  92351. * @param name defines the name of the task
  92352. * @param url defines the location of the file to load
  92353. * @param noMipmap defines if mipmap should not be generated (default is false)
  92354. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92355. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92356. */
  92357. function TextureAssetTask(
  92358. /**
  92359. * Defines the name of the task
  92360. */
  92361. name,
  92362. /**
  92363. * Defines the location of the file to load
  92364. */
  92365. url,
  92366. /**
  92367. * Defines if mipmap should not be generated (default is false)
  92368. */
  92369. noMipmap,
  92370. /**
  92371. * Defines if texture must be inverted on Y axis (default is false)
  92372. */
  92373. invertY,
  92374. /**
  92375. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92376. */
  92377. samplingMode) {
  92378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92379. var _this = _super.call(this, name) || this;
  92380. _this.name = name;
  92381. _this.url = url;
  92382. _this.noMipmap = noMipmap;
  92383. _this.invertY = invertY;
  92384. _this.samplingMode = samplingMode;
  92385. return _this;
  92386. }
  92387. /**
  92388. * Execute the current task
  92389. * @param scene defines the scene where you want your assets to be loaded
  92390. * @param onSuccess is a callback called when the task is successfully executed
  92391. * @param onError is a callback called if an error occurs
  92392. */
  92393. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92394. var onload = function () {
  92395. onSuccess();
  92396. };
  92397. var onerror = function (message, exception) {
  92398. onError(message, exception);
  92399. };
  92400. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92401. };
  92402. return TextureAssetTask;
  92403. }(AbstractAssetTask));
  92404. BABYLON.TextureAssetTask = TextureAssetTask;
  92405. /**
  92406. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92407. */
  92408. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92409. __extends(CubeTextureAssetTask, _super);
  92410. /**
  92411. * Creates a new CubeTextureAssetTask
  92412. * @param name defines the name of the task
  92413. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92414. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92415. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92416. * @param files defines the explicit list of files (undefined by default)
  92417. */
  92418. function CubeTextureAssetTask(
  92419. /**
  92420. * Defines the name of the task
  92421. */
  92422. name,
  92423. /**
  92424. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92425. */
  92426. url,
  92427. /**
  92428. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92429. */
  92430. extensions,
  92431. /**
  92432. * Defines if mipmaps should not be generated (default is false)
  92433. */
  92434. noMipmap,
  92435. /**
  92436. * Defines the explicit list of files (undefined by default)
  92437. */
  92438. files) {
  92439. var _this = _super.call(this, name) || this;
  92440. _this.name = name;
  92441. _this.url = url;
  92442. _this.extensions = extensions;
  92443. _this.noMipmap = noMipmap;
  92444. _this.files = files;
  92445. return _this;
  92446. }
  92447. /**
  92448. * Execute the current task
  92449. * @param scene defines the scene where you want your assets to be loaded
  92450. * @param onSuccess is a callback called when the task is successfully executed
  92451. * @param onError is a callback called if an error occurs
  92452. */
  92453. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92454. var onload = function () {
  92455. onSuccess();
  92456. };
  92457. var onerror = function (message, exception) {
  92458. onError(message, exception);
  92459. };
  92460. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  92461. };
  92462. return CubeTextureAssetTask;
  92463. }(AbstractAssetTask));
  92464. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  92465. /**
  92466. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  92467. */
  92468. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  92469. __extends(HDRCubeTextureAssetTask, _super);
  92470. /**
  92471. * Creates a new HDRCubeTextureAssetTask object
  92472. * @param name defines the name of the task
  92473. * @param url defines the location of the file to load
  92474. * @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.
  92475. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92476. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92477. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  92478. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92479. */
  92480. function HDRCubeTextureAssetTask(
  92481. /**
  92482. * Defines the name of the task
  92483. */
  92484. name,
  92485. /**
  92486. * Defines the location of the file to load
  92487. */
  92488. url,
  92489. /**
  92490. * 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.
  92491. */
  92492. size,
  92493. /**
  92494. * Defines if mipmaps should not be generated (default is false)
  92495. */
  92496. noMipmap,
  92497. /**
  92498. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92499. */
  92500. generateHarmonics,
  92501. /**
  92502. * 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)
  92503. */
  92504. useInGammaSpace,
  92505. /**
  92506. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  92507. */
  92508. usePMREMGenerator) {
  92509. if (noMipmap === void 0) { noMipmap = false; }
  92510. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92511. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92512. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92513. var _this = _super.call(this, name) || this;
  92514. _this.name = name;
  92515. _this.url = url;
  92516. _this.size = size;
  92517. _this.noMipmap = noMipmap;
  92518. _this.generateHarmonics = generateHarmonics;
  92519. _this.useInGammaSpace = useInGammaSpace;
  92520. _this.usePMREMGenerator = usePMREMGenerator;
  92521. return _this;
  92522. }
  92523. /**
  92524. * Execute the current task
  92525. * @param scene defines the scene where you want your assets to be loaded
  92526. * @param onSuccess is a callback called when the task is successfully executed
  92527. * @param onError is a callback called if an error occurs
  92528. */
  92529. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92530. var onload = function () {
  92531. onSuccess();
  92532. };
  92533. var onerror = function (message, exception) {
  92534. onError(message, exception);
  92535. };
  92536. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  92537. };
  92538. return HDRCubeTextureAssetTask;
  92539. }(AbstractAssetTask));
  92540. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  92541. /**
  92542. * This class can be used to easily import assets into a scene
  92543. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  92544. */
  92545. var AssetsManager = /** @class */ (function () {
  92546. /**
  92547. * Creates a new AssetsManager
  92548. * @param scene defines the scene to work on
  92549. */
  92550. function AssetsManager(scene) {
  92551. this._isLoading = false;
  92552. this._tasks = new Array();
  92553. this._waitingTasksCount = 0;
  92554. this._totalTasksCount = 0;
  92555. /**
  92556. * Observable called when all tasks are processed
  92557. */
  92558. this.onTaskSuccessObservable = new BABYLON.Observable();
  92559. /**
  92560. * Observable called when a task had an error
  92561. */
  92562. this.onTaskErrorObservable = new BABYLON.Observable();
  92563. /**
  92564. * Observable called when a task is successful
  92565. */
  92566. this.onTasksDoneObservable = new BABYLON.Observable();
  92567. /**
  92568. * Observable called when a task is done (whatever the result is)
  92569. */
  92570. this.onProgressObservable = new BABYLON.Observable();
  92571. /**
  92572. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  92573. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  92574. */
  92575. this.useDefaultLoadingScreen = true;
  92576. this._scene = scene;
  92577. }
  92578. /**
  92579. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  92580. * @param taskName defines the name of the new task
  92581. * @param meshesNames defines the name of meshes to load
  92582. * @param rootUrl defines the root url to use to locate files
  92583. * @param sceneFilename defines the filename of the scene file
  92584. * @returns a new {BABYLON.MeshAssetTask} object
  92585. */
  92586. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  92587. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  92588. this._tasks.push(task);
  92589. return task;
  92590. };
  92591. /**
  92592. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  92593. * @param taskName defines the name of the new task
  92594. * @param url defines the url of the file to load
  92595. * @returns a new {BABYLON.TextFileAssetTask} object
  92596. */
  92597. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  92598. var task = new TextFileAssetTask(taskName, url);
  92599. this._tasks.push(task);
  92600. return task;
  92601. };
  92602. /**
  92603. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  92604. * @param taskName defines the name of the new task
  92605. * @param url defines the url of the file to load
  92606. * @returns a new {BABYLON.BinaryFileAssetTask} object
  92607. */
  92608. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  92609. var task = new BinaryFileAssetTask(taskName, url);
  92610. this._tasks.push(task);
  92611. return task;
  92612. };
  92613. /**
  92614. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  92615. * @param taskName defines the name of the new task
  92616. * @param url defines the url of the file to load
  92617. * @returns a new {BABYLON.ImageAssetTask} object
  92618. */
  92619. AssetsManager.prototype.addImageTask = function (taskName, url) {
  92620. var task = new ImageAssetTask(taskName, url);
  92621. this._tasks.push(task);
  92622. return task;
  92623. };
  92624. /**
  92625. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  92626. * @param taskName defines the name of the new task
  92627. * @param url defines the url of the file to load
  92628. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92629. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  92630. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  92631. * @returns a new {BABYLON.TextureAssetTask} object
  92632. */
  92633. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  92634. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92635. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  92636. this._tasks.push(task);
  92637. return task;
  92638. };
  92639. /**
  92640. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  92641. * @param taskName defines the name of the new task
  92642. * @param url defines the url of the file to load
  92643. * @param extensions defines the extension to use to load the cube map (can be null)
  92644. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92645. * @param files defines the list of files to load (can be null)
  92646. * @returns a new {BABYLON.CubeTextureAssetTask} object
  92647. */
  92648. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  92649. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  92650. this._tasks.push(task);
  92651. return task;
  92652. };
  92653. /**
  92654. *
  92655. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  92656. * @param taskName defines the name of the new task
  92657. * @param url defines the url of the file to load
  92658. * @param size defines the size you want for the cubemap (can be null)
  92659. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  92660. * @param generateHarmonics defines if you want to automatically generate (true by default)
  92661. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  92662. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  92663. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  92664. */
  92665. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  92666. if (noMipmap === void 0) { noMipmap = false; }
  92667. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92668. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  92669. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  92670. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  92671. this._tasks.push(task);
  92672. return task;
  92673. };
  92674. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  92675. var _this = this;
  92676. this._waitingTasksCount--;
  92677. try {
  92678. if (task.taskState === AssetTaskState.DONE) {
  92679. // Let's remove successfull tasks
  92680. BABYLON.Tools.SetImmediate(function () {
  92681. var index = _this._tasks.indexOf(task);
  92682. if (index > -1) {
  92683. _this._tasks.splice(index, 1);
  92684. }
  92685. });
  92686. }
  92687. if (this.onProgress) {
  92688. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  92689. }
  92690. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  92691. }
  92692. catch (e) {
  92693. BABYLON.Tools.Error("Error running progress callbacks.");
  92694. console.log(e);
  92695. }
  92696. if (this._waitingTasksCount === 0) {
  92697. try {
  92698. if (this.onFinish) {
  92699. this.onFinish(this._tasks);
  92700. }
  92701. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92702. }
  92703. catch (e) {
  92704. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  92705. console.log(e);
  92706. }
  92707. this._isLoading = false;
  92708. this._scene.getEngine().hideLoadingUI();
  92709. }
  92710. };
  92711. AssetsManager.prototype._runTask = function (task) {
  92712. var _this = this;
  92713. var done = function () {
  92714. try {
  92715. if (_this.onTaskSuccess) {
  92716. _this.onTaskSuccess(task);
  92717. }
  92718. _this.onTaskSuccessObservable.notifyObservers(task);
  92719. _this._decreaseWaitingTasksCount(task);
  92720. }
  92721. catch (e) {
  92722. error("Error executing task success callbacks", e);
  92723. }
  92724. };
  92725. var error = function (message, exception) {
  92726. task._setErrorObject(message, exception);
  92727. if (_this.onTaskError) {
  92728. _this.onTaskError(task);
  92729. }
  92730. _this.onTaskErrorObservable.notifyObservers(task);
  92731. _this._decreaseWaitingTasksCount(task);
  92732. };
  92733. task.run(this._scene, done, error);
  92734. };
  92735. /**
  92736. * Reset the {BABYLON.AssetsManager} and remove all tasks
  92737. * @return the current instance of the {BABYLON.AssetsManager}
  92738. */
  92739. AssetsManager.prototype.reset = function () {
  92740. this._isLoading = false;
  92741. this._tasks = new Array();
  92742. return this;
  92743. };
  92744. /**
  92745. * Start the loading process
  92746. * @return the current instance of the {BABYLON.AssetsManager}
  92747. */
  92748. AssetsManager.prototype.load = function () {
  92749. if (this._isLoading) {
  92750. return this;
  92751. }
  92752. this._isLoading = true;
  92753. this._waitingTasksCount = this._tasks.length;
  92754. this._totalTasksCount = this._tasks.length;
  92755. if (this._waitingTasksCount === 0) {
  92756. this._isLoading = false;
  92757. if (this.onFinish) {
  92758. this.onFinish(this._tasks);
  92759. }
  92760. this.onTasksDoneObservable.notifyObservers(this._tasks);
  92761. return this;
  92762. }
  92763. if (this.useDefaultLoadingScreen) {
  92764. this._scene.getEngine().displayLoadingUI();
  92765. }
  92766. for (var index = 0; index < this._tasks.length; index++) {
  92767. var task = this._tasks[index];
  92768. this._runTask(task);
  92769. }
  92770. return this;
  92771. };
  92772. return AssetsManager;
  92773. }());
  92774. BABYLON.AssetsManager = AssetsManager;
  92775. })(BABYLON || (BABYLON = {}));
  92776. //# sourceMappingURL=babylon.assetsManager.js.map
  92777. var BABYLON;
  92778. (function (BABYLON) {
  92779. var serializedGeometries = [];
  92780. var serializeGeometry = function (geometry, serializationGeometries) {
  92781. if (serializedGeometries[geometry.id]) {
  92782. return;
  92783. }
  92784. if (geometry.doNotSerialize) {
  92785. return;
  92786. }
  92787. if (geometry instanceof BABYLON.BoxGeometry) {
  92788. serializationGeometries.boxes.push(geometry.serialize());
  92789. }
  92790. else if (geometry instanceof BABYLON.SphereGeometry) {
  92791. serializationGeometries.spheres.push(geometry.serialize());
  92792. }
  92793. else if (geometry instanceof BABYLON.CylinderGeometry) {
  92794. serializationGeometries.cylinders.push(geometry.serialize());
  92795. }
  92796. else if (geometry instanceof BABYLON.TorusGeometry) {
  92797. serializationGeometries.toruses.push(geometry.serialize());
  92798. }
  92799. else if (geometry instanceof BABYLON.GroundGeometry) {
  92800. serializationGeometries.grounds.push(geometry.serialize());
  92801. }
  92802. else if (geometry instanceof BABYLON.Plane) {
  92803. serializationGeometries.planes.push(geometry.serialize());
  92804. }
  92805. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  92806. serializationGeometries.torusKnots.push(geometry.serialize());
  92807. }
  92808. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  92809. throw new Error("Unknown primitive type");
  92810. }
  92811. else {
  92812. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  92813. }
  92814. serializedGeometries[geometry.id] = true;
  92815. };
  92816. var serializeMesh = function (mesh, serializationScene) {
  92817. var serializationObject = {};
  92818. // Geometry
  92819. var geometry = mesh._geometry;
  92820. if (geometry) {
  92821. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  92822. // 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
  92823. serializeGeometry(geometry, serializationScene.geometries);
  92824. }
  92825. }
  92826. // Custom
  92827. if (mesh.serialize) {
  92828. mesh.serialize(serializationObject);
  92829. }
  92830. return serializationObject;
  92831. };
  92832. var finalizeSingleMesh = function (mesh, serializationObject) {
  92833. //only works if the mesh is already loaded
  92834. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  92835. //serialize material
  92836. if (mesh.material) {
  92837. if (mesh.material instanceof BABYLON.StandardMaterial) {
  92838. serializationObject.materials = serializationObject.materials || [];
  92839. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92840. serializationObject.materials.push(mesh.material.serialize());
  92841. }
  92842. }
  92843. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  92844. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  92845. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  92846. serializationObject.multiMaterials.push(mesh.material.serialize());
  92847. }
  92848. }
  92849. }
  92850. //serialize geometry
  92851. var geometry = mesh._geometry;
  92852. if (geometry) {
  92853. if (!serializationObject.geometries) {
  92854. serializationObject.geometries = {};
  92855. serializationObject.geometries.boxes = [];
  92856. serializationObject.geometries.spheres = [];
  92857. serializationObject.geometries.cylinders = [];
  92858. serializationObject.geometries.toruses = [];
  92859. serializationObject.geometries.grounds = [];
  92860. serializationObject.geometries.planes = [];
  92861. serializationObject.geometries.torusKnots = [];
  92862. serializationObject.geometries.vertexData = [];
  92863. }
  92864. serializeGeometry(geometry, serializationObject.geometries);
  92865. }
  92866. // Skeletons
  92867. if (mesh.skeleton) {
  92868. serializationObject.skeletons = serializationObject.skeletons || [];
  92869. serializationObject.skeletons.push(mesh.skeleton.serialize());
  92870. }
  92871. //serialize the actual mesh
  92872. serializationObject.meshes = serializationObject.meshes || [];
  92873. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  92874. }
  92875. };
  92876. var SceneSerializer = /** @class */ (function () {
  92877. function SceneSerializer() {
  92878. }
  92879. SceneSerializer.ClearCache = function () {
  92880. serializedGeometries = [];
  92881. };
  92882. SceneSerializer.Serialize = function (scene) {
  92883. var serializationObject = {};
  92884. SceneSerializer.ClearCache();
  92885. // Scene
  92886. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  92887. serializationObject.autoClear = scene.autoClear;
  92888. serializationObject.clearColor = scene.clearColor.asArray();
  92889. serializationObject.ambientColor = scene.ambientColor.asArray();
  92890. serializationObject.gravity = scene.gravity.asArray();
  92891. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  92892. serializationObject.workerCollisions = scene.workerCollisions;
  92893. // Fog
  92894. if (scene.fogMode && scene.fogMode !== 0) {
  92895. serializationObject.fogMode = scene.fogMode;
  92896. serializationObject.fogColor = scene.fogColor.asArray();
  92897. serializationObject.fogStart = scene.fogStart;
  92898. serializationObject.fogEnd = scene.fogEnd;
  92899. serializationObject.fogDensity = scene.fogDensity;
  92900. }
  92901. //Physics
  92902. if (scene.isPhysicsEnabled()) {
  92903. var physicEngine = scene.getPhysicsEngine();
  92904. if (physicEngine) {
  92905. serializationObject.physicsEnabled = true;
  92906. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  92907. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  92908. }
  92909. }
  92910. // Metadata
  92911. if (scene.metadata) {
  92912. serializationObject.metadata = scene.metadata;
  92913. }
  92914. // Morph targets
  92915. serializationObject.morphTargetManagers = [];
  92916. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  92917. var abstractMesh = _a[_i];
  92918. var manager = abstractMesh.morphTargetManager;
  92919. if (manager) {
  92920. serializationObject.morphTargetManagers.push(manager.serialize());
  92921. }
  92922. }
  92923. // Lights
  92924. serializationObject.lights = [];
  92925. var index;
  92926. var light;
  92927. for (index = 0; index < scene.lights.length; index++) {
  92928. light = scene.lights[index];
  92929. if (!light.doNotSerialize) {
  92930. serializationObject.lights.push(light.serialize());
  92931. }
  92932. }
  92933. // Cameras
  92934. serializationObject.cameras = [];
  92935. for (index = 0; index < scene.cameras.length; index++) {
  92936. var camera = scene.cameras[index];
  92937. if (!camera.doNotSerialize) {
  92938. serializationObject.cameras.push(camera.serialize());
  92939. }
  92940. }
  92941. if (scene.activeCamera) {
  92942. serializationObject.activeCameraID = scene.activeCamera.id;
  92943. }
  92944. // Animations
  92945. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  92946. // Materials
  92947. serializationObject.materials = [];
  92948. serializationObject.multiMaterials = [];
  92949. var material;
  92950. for (index = 0; index < scene.materials.length; index++) {
  92951. material = scene.materials[index];
  92952. if (!material.doNotSerialize) {
  92953. serializationObject.materials.push(material.serialize());
  92954. }
  92955. }
  92956. // MultiMaterials
  92957. serializationObject.multiMaterials = [];
  92958. for (index = 0; index < scene.multiMaterials.length; index++) {
  92959. var multiMaterial = scene.multiMaterials[index];
  92960. serializationObject.multiMaterials.push(multiMaterial.serialize());
  92961. }
  92962. // Environment texture
  92963. if (scene.environmentTexture) {
  92964. serializationObject.environmentTexture = scene.environmentTexture.name;
  92965. }
  92966. // Skeletons
  92967. serializationObject.skeletons = [];
  92968. for (index = 0; index < scene.skeletons.length; index++) {
  92969. var skeleton = scene.skeletons[index];
  92970. if (!skeleton.doNotSerialize) {
  92971. serializationObject.skeletons.push(skeleton.serialize());
  92972. }
  92973. }
  92974. // Transform nodes
  92975. serializationObject.transformNodes = [];
  92976. for (index = 0; index < scene.transformNodes.length; index++) {
  92977. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  92978. }
  92979. // Geometries
  92980. serializationObject.geometries = {};
  92981. serializationObject.geometries.boxes = [];
  92982. serializationObject.geometries.spheres = [];
  92983. serializationObject.geometries.cylinders = [];
  92984. serializationObject.geometries.toruses = [];
  92985. serializationObject.geometries.grounds = [];
  92986. serializationObject.geometries.planes = [];
  92987. serializationObject.geometries.torusKnots = [];
  92988. serializationObject.geometries.vertexData = [];
  92989. serializedGeometries = [];
  92990. var geometries = scene.getGeometries();
  92991. for (index = 0; index < geometries.length; index++) {
  92992. var geometry = geometries[index];
  92993. if (geometry.isReady()) {
  92994. serializeGeometry(geometry, serializationObject.geometries);
  92995. }
  92996. }
  92997. // Meshes
  92998. serializationObject.meshes = [];
  92999. for (index = 0; index < scene.meshes.length; index++) {
  93000. var abstractMesh = scene.meshes[index];
  93001. if (abstractMesh instanceof BABYLON.Mesh) {
  93002. var mesh = abstractMesh;
  93003. if (!mesh.doNotSerialize) {
  93004. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93005. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93006. }
  93007. }
  93008. }
  93009. }
  93010. // Particles Systems
  93011. serializationObject.particleSystems = [];
  93012. for (index = 0; index < scene.particleSystems.length; index++) {
  93013. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93014. }
  93015. // Lens flares
  93016. serializationObject.lensFlareSystems = [];
  93017. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93018. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93019. }
  93020. // Shadows
  93021. serializationObject.shadowGenerators = [];
  93022. for (index = 0; index < scene.lights.length; index++) {
  93023. light = scene.lights[index];
  93024. var shadowGenerator = light.getShadowGenerator();
  93025. if (shadowGenerator) {
  93026. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93027. }
  93028. }
  93029. // Action Manager
  93030. if (scene.actionManager) {
  93031. serializationObject.actions = scene.actionManager.serialize("scene");
  93032. }
  93033. // Audio
  93034. serializationObject.sounds = [];
  93035. for (index = 0; index < scene.soundTracks.length; index++) {
  93036. var soundtrack = scene.soundTracks[index];
  93037. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93038. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93039. }
  93040. }
  93041. // Effect layers
  93042. serializationObject.effectLayers = [];
  93043. for (index = 0; index < scene.effectLayers.length; index++) {
  93044. var layer = scene.effectLayers[index];
  93045. if (layer.serialize) {
  93046. serializationObject.effectLayers.push(layer.serialize());
  93047. }
  93048. }
  93049. return serializationObject;
  93050. };
  93051. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93052. if (withParents === void 0) { withParents = false; }
  93053. if (withChildren === void 0) { withChildren = false; }
  93054. var serializationObject = {};
  93055. SceneSerializer.ClearCache();
  93056. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93057. if (withParents || withChildren) {
  93058. //deliberate for loop! not for each, appended should be processed as well.
  93059. for (var i = 0; i < toSerialize.length; ++i) {
  93060. if (withChildren) {
  93061. toSerialize[i].getDescendants().forEach(function (node) {
  93062. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93063. toSerialize.push(node);
  93064. }
  93065. });
  93066. }
  93067. //make sure the array doesn't contain the object already
  93068. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93069. toSerialize.push(toSerialize[i].parent);
  93070. }
  93071. }
  93072. }
  93073. toSerialize.forEach(function (mesh) {
  93074. finalizeSingleMesh(mesh, serializationObject);
  93075. });
  93076. return serializationObject;
  93077. };
  93078. return SceneSerializer;
  93079. }());
  93080. BABYLON.SceneSerializer = SceneSerializer;
  93081. })(BABYLON || (BABYLON = {}));
  93082. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93083. var BABYLON;
  93084. (function (BABYLON) {
  93085. var ReflectionProbe = /** @class */ (function () {
  93086. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93087. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93088. var _this = this;
  93089. this.name = name;
  93090. this._viewMatrix = BABYLON.Matrix.Identity();
  93091. this._target = BABYLON.Vector3.Zero();
  93092. this._add = BABYLON.Vector3.Zero();
  93093. this._invertYAxis = false;
  93094. this.position = BABYLON.Vector3.Zero();
  93095. this._scene = scene;
  93096. this._scene.reflectionProbes.push(this);
  93097. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93098. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93099. switch (faceIndex) {
  93100. case 0:
  93101. _this._add.copyFromFloats(1, 0, 0);
  93102. break;
  93103. case 1:
  93104. _this._add.copyFromFloats(-1, 0, 0);
  93105. break;
  93106. case 2:
  93107. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93108. break;
  93109. case 3:
  93110. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93111. break;
  93112. case 4:
  93113. _this._add.copyFromFloats(0, 0, 1);
  93114. break;
  93115. case 5:
  93116. _this._add.copyFromFloats(0, 0, -1);
  93117. break;
  93118. }
  93119. if (_this._attachedMesh) {
  93120. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93121. }
  93122. _this.position.addToRef(_this._add, _this._target);
  93123. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93124. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93125. scene._forcedViewPosition = _this.position;
  93126. });
  93127. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93128. scene._forcedViewPosition = null;
  93129. scene.updateTransformMatrix(true);
  93130. });
  93131. if (scene.activeCamera) {
  93132. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93133. }
  93134. }
  93135. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93136. get: function () {
  93137. return this._renderTargetTexture.samples;
  93138. },
  93139. set: function (value) {
  93140. this._renderTargetTexture.samples = value;
  93141. },
  93142. enumerable: true,
  93143. configurable: true
  93144. });
  93145. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93146. get: function () {
  93147. return this._renderTargetTexture.refreshRate;
  93148. },
  93149. set: function (value) {
  93150. this._renderTargetTexture.refreshRate = value;
  93151. },
  93152. enumerable: true,
  93153. configurable: true
  93154. });
  93155. ReflectionProbe.prototype.getScene = function () {
  93156. return this._scene;
  93157. };
  93158. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93159. get: function () {
  93160. return this._renderTargetTexture;
  93161. },
  93162. enumerable: true,
  93163. configurable: true
  93164. });
  93165. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93166. get: function () {
  93167. return this._renderTargetTexture.renderList;
  93168. },
  93169. enumerable: true,
  93170. configurable: true
  93171. });
  93172. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93173. this._attachedMesh = mesh;
  93174. };
  93175. /**
  93176. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93177. *
  93178. * @param renderingGroupId The rendering group id corresponding to its index
  93179. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93180. */
  93181. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93182. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93183. };
  93184. ReflectionProbe.prototype.dispose = function () {
  93185. var index = this._scene.reflectionProbes.indexOf(this);
  93186. if (index !== -1) {
  93187. // Remove from the scene if found
  93188. this._scene.reflectionProbes.splice(index, 1);
  93189. }
  93190. if (this._renderTargetTexture) {
  93191. this._renderTargetTexture.dispose();
  93192. this._renderTargetTexture = null;
  93193. }
  93194. };
  93195. return ReflectionProbe;
  93196. }());
  93197. BABYLON.ReflectionProbe = ReflectionProbe;
  93198. })(BABYLON || (BABYLON = {}));
  93199. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93200. var BABYLON;
  93201. (function (BABYLON) {
  93202. var Layer = /** @class */ (function () {
  93203. function Layer(name, imgUrl, scene, isBackground, color) {
  93204. this.name = name;
  93205. this.scale = new BABYLON.Vector2(1, 1);
  93206. this.offset = new BABYLON.Vector2(0, 0);
  93207. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93208. this.layerMask = 0x0FFFFFFF;
  93209. this._vertexBuffers = {};
  93210. // Events
  93211. /**
  93212. * An event triggered when the layer is disposed.
  93213. */
  93214. this.onDisposeObservable = new BABYLON.Observable();
  93215. /**
  93216. * An event triggered before rendering the scene
  93217. */
  93218. this.onBeforeRenderObservable = new BABYLON.Observable();
  93219. /**
  93220. * An event triggered after rendering the scene
  93221. */
  93222. this.onAfterRenderObservable = new BABYLON.Observable();
  93223. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93224. this.isBackground = isBackground === undefined ? true : isBackground;
  93225. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93226. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93227. this._scene.layers.push(this);
  93228. var engine = this._scene.getEngine();
  93229. // VBO
  93230. var vertices = [];
  93231. vertices.push(1, 1);
  93232. vertices.push(-1, 1);
  93233. vertices.push(-1, -1);
  93234. vertices.push(1, -1);
  93235. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93236. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93237. this._createIndexBuffer();
  93238. // Effects
  93239. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93240. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93241. }
  93242. Object.defineProperty(Layer.prototype, "onDispose", {
  93243. set: function (callback) {
  93244. if (this._onDisposeObserver) {
  93245. this.onDisposeObservable.remove(this._onDisposeObserver);
  93246. }
  93247. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93248. },
  93249. enumerable: true,
  93250. configurable: true
  93251. });
  93252. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93253. set: function (callback) {
  93254. if (this._onBeforeRenderObserver) {
  93255. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93256. }
  93257. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93258. },
  93259. enumerable: true,
  93260. configurable: true
  93261. });
  93262. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93263. set: function (callback) {
  93264. if (this._onAfterRenderObserver) {
  93265. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93266. }
  93267. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93268. },
  93269. enumerable: true,
  93270. configurable: true
  93271. });
  93272. Layer.prototype._createIndexBuffer = function () {
  93273. var engine = this._scene.getEngine();
  93274. // Indices
  93275. var indices = [];
  93276. indices.push(0);
  93277. indices.push(1);
  93278. indices.push(2);
  93279. indices.push(0);
  93280. indices.push(2);
  93281. indices.push(3);
  93282. this._indexBuffer = engine.createIndexBuffer(indices);
  93283. };
  93284. Layer.prototype._rebuild = function () {
  93285. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93286. if (vb) {
  93287. vb._rebuild();
  93288. }
  93289. this._createIndexBuffer();
  93290. };
  93291. Layer.prototype.render = function () {
  93292. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93293. // Check
  93294. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93295. return;
  93296. var engine = this._scene.getEngine();
  93297. this.onBeforeRenderObservable.notifyObservers(this);
  93298. // Render
  93299. engine.enableEffect(currentEffect);
  93300. engine.setState(false);
  93301. // Texture
  93302. currentEffect.setTexture("textureSampler", this.texture);
  93303. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93304. // Color
  93305. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93306. // Scale / offset
  93307. currentEffect.setVector2("offset", this.offset);
  93308. currentEffect.setVector2("scale", this.scale);
  93309. // VBOs
  93310. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93311. // Draw order
  93312. if (!this.alphaTest) {
  93313. engine.setAlphaMode(this.alphaBlendingMode);
  93314. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93316. }
  93317. else {
  93318. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93319. }
  93320. this.onAfterRenderObservable.notifyObservers(this);
  93321. };
  93322. Layer.prototype.dispose = function () {
  93323. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93324. if (vertexBuffer) {
  93325. vertexBuffer.dispose();
  93326. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93327. }
  93328. if (this._indexBuffer) {
  93329. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93330. this._indexBuffer = null;
  93331. }
  93332. if (this.texture) {
  93333. this.texture.dispose();
  93334. this.texture = null;
  93335. }
  93336. // Remove from scene
  93337. var index = this._scene.layers.indexOf(this);
  93338. this._scene.layers.splice(index, 1);
  93339. // Callback
  93340. this.onDisposeObservable.notifyObservers(this);
  93341. this.onDisposeObservable.clear();
  93342. this.onAfterRenderObservable.clear();
  93343. this.onBeforeRenderObservable.clear();
  93344. };
  93345. return Layer;
  93346. }());
  93347. BABYLON.Layer = Layer;
  93348. })(BABYLON || (BABYLON = {}));
  93349. //# sourceMappingURL=babylon.layer.js.map
  93350. var BABYLON;
  93351. (function (BABYLON) {
  93352. var TextureTools = /** @class */ (function () {
  93353. function TextureTools() {
  93354. }
  93355. /**
  93356. * Uses the GPU to create a copy texture rescaled at a given size
  93357. * @param texture Texture to copy from
  93358. * @param width Desired width
  93359. * @param height Desired height
  93360. * @return Generated texture
  93361. */
  93362. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93363. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93364. var scene = texture.getScene();
  93365. var engine = scene.getEngine();
  93366. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93367. rtt.wrapU = texture.wrapU;
  93368. rtt.wrapV = texture.wrapV;
  93369. rtt.uOffset = texture.uOffset;
  93370. rtt.vOffset = texture.vOffset;
  93371. rtt.uScale = texture.uScale;
  93372. rtt.vScale = texture.vScale;
  93373. rtt.uAng = texture.uAng;
  93374. rtt.vAng = texture.vAng;
  93375. rtt.wAng = texture.wAng;
  93376. rtt.coordinatesIndex = texture.coordinatesIndex;
  93377. rtt.level = texture.level;
  93378. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93379. rtt._texture.isReady = false;
  93380. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93381. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93382. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93383. passPostProcess.getEffect().executeWhenCompiled(function () {
  93384. passPostProcess.onApply = function (effect) {
  93385. effect.setTexture("textureSampler", texture);
  93386. };
  93387. var internalTexture = rtt.getInternalTexture();
  93388. if (internalTexture) {
  93389. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93390. engine.unBindFramebuffer(internalTexture);
  93391. rtt.disposeFramebufferObjects();
  93392. passPostProcess.dispose();
  93393. internalTexture.isReady = true;
  93394. }
  93395. });
  93396. return rtt;
  93397. };
  93398. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93399. if (!scene._environmentBRDFTexture) {
  93400. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93401. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93402. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93403. scene._environmentBRDFTexture = texture;
  93404. }
  93405. return scene._environmentBRDFTexture;
  93406. };
  93407. 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=";
  93408. return TextureTools;
  93409. }());
  93410. BABYLON.TextureTools = TextureTools;
  93411. })(BABYLON || (BABYLON = {}));
  93412. //# sourceMappingURL=babylon.textureTools.js.map
  93413. var BABYLON;
  93414. (function (BABYLON) {
  93415. var FramingBehavior = /** @class */ (function () {
  93416. function FramingBehavior() {
  93417. this._mode = FramingBehavior.FitFrustumSidesMode;
  93418. this._radiusScale = 1.0;
  93419. this._positionScale = 0.5;
  93420. this._defaultElevation = 0.3;
  93421. this._elevationReturnTime = 1500;
  93422. this._elevationReturnWaitTime = 1000;
  93423. this._zoomStopsAnimation = false;
  93424. this._framingTime = 1500;
  93425. this._isPointerDown = false;
  93426. this._lastInteractionTime = -Infinity;
  93427. // Framing control
  93428. this._animatables = new Array();
  93429. this._betaIsAnimating = false;
  93430. }
  93431. Object.defineProperty(FramingBehavior.prototype, "name", {
  93432. get: function () {
  93433. return "Framing";
  93434. },
  93435. enumerable: true,
  93436. configurable: true
  93437. });
  93438. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93439. /**
  93440. * Gets current mode used by the behavior.
  93441. */
  93442. get: function () {
  93443. return this._mode;
  93444. },
  93445. /**
  93446. * Sets the current mode used by the behavior
  93447. */
  93448. set: function (mode) {
  93449. this._mode = mode;
  93450. },
  93451. enumerable: true,
  93452. configurable: true
  93453. });
  93454. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93455. /**
  93456. * Gets the scale applied to the radius
  93457. */
  93458. get: function () {
  93459. return this._radiusScale;
  93460. },
  93461. /**
  93462. * Sets the scale applied to the radius (1 by default)
  93463. */
  93464. set: function (radius) {
  93465. this._radiusScale = radius;
  93466. },
  93467. enumerable: true,
  93468. configurable: true
  93469. });
  93470. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  93471. /**
  93472. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93473. */
  93474. get: function () {
  93475. return this._positionScale;
  93476. },
  93477. /**
  93478. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93479. */
  93480. set: function (scale) {
  93481. this._positionScale = scale;
  93482. },
  93483. enumerable: true,
  93484. configurable: true
  93485. });
  93486. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  93487. /**
  93488. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93489. * behaviour is triggered, in radians.
  93490. */
  93491. get: function () {
  93492. return this._defaultElevation;
  93493. },
  93494. /**
  93495. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93496. * behaviour is triggered, in radians.
  93497. */
  93498. set: function (elevation) {
  93499. this._defaultElevation = elevation;
  93500. },
  93501. enumerable: true,
  93502. configurable: true
  93503. });
  93504. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  93505. /**
  93506. * Gets the time (in milliseconds) taken to return to the default beta position.
  93507. * Negative value indicates camera should not return to default.
  93508. */
  93509. get: function () {
  93510. return this._elevationReturnTime;
  93511. },
  93512. /**
  93513. * Sets the time (in milliseconds) taken to return to the default beta position.
  93514. * Negative value indicates camera should not return to default.
  93515. */
  93516. set: function (speed) {
  93517. this._elevationReturnTime = speed;
  93518. },
  93519. enumerable: true,
  93520. configurable: true
  93521. });
  93522. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  93523. /**
  93524. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93525. */
  93526. get: function () {
  93527. return this._elevationReturnWaitTime;
  93528. },
  93529. /**
  93530. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  93531. */
  93532. set: function (time) {
  93533. this._elevationReturnWaitTime = time;
  93534. },
  93535. enumerable: true,
  93536. configurable: true
  93537. });
  93538. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  93539. /**
  93540. * Gets the flag that indicates if user zooming should stop animation.
  93541. */
  93542. get: function () {
  93543. return this._zoomStopsAnimation;
  93544. },
  93545. /**
  93546. * Sets the flag that indicates if user zooming should stop animation.
  93547. */
  93548. set: function (flag) {
  93549. this._zoomStopsAnimation = flag;
  93550. },
  93551. enumerable: true,
  93552. configurable: true
  93553. });
  93554. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  93555. /**
  93556. * Gets the transition time when framing the mesh, in milliseconds
  93557. */
  93558. get: function () {
  93559. return this._framingTime;
  93560. },
  93561. /**
  93562. * Sets the transition time when framing the mesh, in milliseconds
  93563. */
  93564. set: function (time) {
  93565. this._framingTime = time;
  93566. },
  93567. enumerable: true,
  93568. configurable: true
  93569. });
  93570. FramingBehavior.prototype.init = function () {
  93571. // Do notihng
  93572. };
  93573. FramingBehavior.prototype.attach = function (camera) {
  93574. var _this = this;
  93575. this._attachedCamera = camera;
  93576. var scene = this._attachedCamera.getScene();
  93577. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  93578. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  93579. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  93580. _this._isPointerDown = true;
  93581. return;
  93582. }
  93583. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  93584. _this._isPointerDown = false;
  93585. }
  93586. });
  93587. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93588. if (mesh) {
  93589. _this.zoomOnMesh(mesh);
  93590. }
  93591. });
  93592. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93593. // Stop the animation if there is user interaction and the animation should stop for this interaction
  93594. _this._applyUserInteraction();
  93595. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  93596. // back to the default position after a given timeout
  93597. _this._maintainCameraAboveGround();
  93598. });
  93599. };
  93600. FramingBehavior.prototype.detach = function () {
  93601. if (!this._attachedCamera) {
  93602. return;
  93603. }
  93604. var scene = this._attachedCamera.getScene();
  93605. if (this._onPrePointerObservableObserver) {
  93606. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  93607. }
  93608. if (this._onAfterCheckInputsObserver) {
  93609. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93610. }
  93611. if (this._onMeshTargetChangedObserver) {
  93612. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93613. }
  93614. this._attachedCamera = null;
  93615. };
  93616. /**
  93617. * Targets the given mesh and updates zoom level accordingly.
  93618. * @param mesh The mesh to target.
  93619. * @param radius Optional. If a cached radius position already exists, overrides default.
  93620. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93621. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93622. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93623. */
  93624. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93625. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93626. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93627. mesh.computeWorldMatrix(true);
  93628. var boundingBox = mesh.getBoundingInfo().boundingBox;
  93629. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  93630. };
  93631. /**
  93632. * Targets the given mesh with its children and updates zoom level accordingly.
  93633. * @param mesh The mesh to target.
  93634. * @param radius Optional. If a cached radius position already exists, overrides default.
  93635. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93636. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93637. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93638. */
  93639. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  93640. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93641. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93642. mesh.computeWorldMatrix(true);
  93643. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  93644. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  93645. };
  93646. /**
  93647. * Targets the given meshes with their children and updates zoom level accordingly.
  93648. * @param meshes The mesh to target.
  93649. * @param radius Optional. If a cached radius position already exists, overrides default.
  93650. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93651. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93652. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93653. */
  93654. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  93655. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93656. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93657. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  93658. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  93659. for (var i = 0; i < meshes.length; i++) {
  93660. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  93661. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  93662. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  93663. }
  93664. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  93665. };
  93666. /**
  93667. * Targets the given mesh and updates zoom level accordingly.
  93668. * @param mesh The mesh to target.
  93669. * @param radius Optional. If a cached radius position already exists, overrides default.
  93670. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  93671. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  93672. * @param onAnimationEnd Callback triggered at the end of the framing animation
  93673. */
  93674. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  93675. var _this = this;
  93676. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  93677. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  93678. var zoomTarget;
  93679. if (!this._attachedCamera) {
  93680. return;
  93681. }
  93682. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  93683. var bottom = minimumWorld.y;
  93684. var top = maximumWorld.y;
  93685. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  93686. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  93687. if (focusOnOriginXZ) {
  93688. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  93689. }
  93690. else {
  93691. var centerWorld = minimumWorld.add(radiusWorld);
  93692. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  93693. }
  93694. if (!this._vectorTransition) {
  93695. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  93696. }
  93697. this._betaIsAnimating = true;
  93698. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  93699. if (animatable) {
  93700. this._animatables.push(animatable);
  93701. }
  93702. // sets the radius and lower radius bounds
  93703. // Small delta ensures camera is not always at lower zoom limit.
  93704. var radius = 0;
  93705. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  93706. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93707. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  93708. radius = position;
  93709. }
  93710. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93711. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  93712. if (this._attachedCamera.lowerRadiusLimit === null) {
  93713. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  93714. }
  93715. }
  93716. // Set sensibilities
  93717. var extend = maximumWorld.subtract(minimumWorld).length();
  93718. this._attachedCamera.panningSensibility = 5000 / extend;
  93719. this._attachedCamera.wheelPrecision = 100 / radius;
  93720. // transition to new radius
  93721. if (!this._radiusTransition) {
  93722. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93723. }
  93724. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  93725. _this.stopAllAnimations();
  93726. if (onAnimationEnd) {
  93727. onAnimationEnd();
  93728. }
  93729. if (_this._attachedCamera) {
  93730. _this._attachedCamera.storeState();
  93731. }
  93732. });
  93733. if (animatable) {
  93734. this._animatables.push(animatable);
  93735. }
  93736. };
  93737. /**
  93738. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  93739. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  93740. * frustum width.
  93741. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  93742. * to fully enclose the mesh in the viewing frustum.
  93743. */
  93744. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  93745. var size = maximumWorld.subtract(minimumWorld);
  93746. var boxVectorGlobalDiagonal = size.length();
  93747. var frustumSlope = this._getFrustumSlope();
  93748. // Formula for setting distance
  93749. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  93750. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  93751. // Horizon distance
  93752. var radius = radiusWithoutFraming * this._radiusScale;
  93753. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  93754. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  93755. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  93756. var camera = this._attachedCamera;
  93757. if (!camera) {
  93758. return 0;
  93759. }
  93760. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  93761. // Don't exceed the requested limit
  93762. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  93763. }
  93764. // Don't exceed the upper radius limit
  93765. if (camera.upperRadiusLimit) {
  93766. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  93767. }
  93768. return distance;
  93769. };
  93770. /**
  93771. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  93772. * is automatically returned to its default position (expected to be above ground plane).
  93773. */
  93774. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  93775. var _this = this;
  93776. if (this._elevationReturnTime < 0) {
  93777. return;
  93778. }
  93779. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  93780. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  93781. var limitBeta = Math.PI * 0.5;
  93782. // Bring the camera back up if below the ground plane
  93783. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  93784. this._betaIsAnimating = true;
  93785. //Transition to new position
  93786. this.stopAllAnimations();
  93787. if (!this._betaTransition) {
  93788. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  93789. }
  93790. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  93791. _this._clearAnimationLocks();
  93792. _this.stopAllAnimations();
  93793. });
  93794. if (animatabe) {
  93795. this._animatables.push(animatabe);
  93796. }
  93797. }
  93798. };
  93799. /**
  93800. * Returns the frustum slope based on the canvas ratio and camera FOV
  93801. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  93802. */
  93803. FramingBehavior.prototype._getFrustumSlope = function () {
  93804. // Calculate the viewport ratio
  93805. // Aspect Ratio is Height/Width.
  93806. var camera = this._attachedCamera;
  93807. if (!camera) {
  93808. return BABYLON.Vector2.Zero();
  93809. }
  93810. var engine = camera.getScene().getEngine();
  93811. var aspectRatio = engine.getAspectRatio(camera);
  93812. // Camera FOV is the vertical field of view (top-bottom) in radians.
  93813. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  93814. var frustumSlopeY = Math.tan(camera.fov / 2);
  93815. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  93816. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  93817. // along the forward vector.
  93818. var frustumSlopeX = frustumSlopeY * aspectRatio;
  93819. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  93820. };
  93821. /**
  93822. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  93823. */
  93824. FramingBehavior.prototype._clearAnimationLocks = function () {
  93825. this._betaIsAnimating = false;
  93826. };
  93827. /**
  93828. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  93829. */
  93830. FramingBehavior.prototype._applyUserInteraction = function () {
  93831. if (this.isUserIsMoving) {
  93832. this._lastInteractionTime = BABYLON.Tools.Now;
  93833. this.stopAllAnimations();
  93834. this._clearAnimationLocks();
  93835. }
  93836. };
  93837. /**
  93838. * Stops and removes all animations that have been applied to the camera
  93839. */
  93840. FramingBehavior.prototype.stopAllAnimations = function () {
  93841. if (this._attachedCamera) {
  93842. this._attachedCamera.animations = [];
  93843. }
  93844. while (this._animatables.length) {
  93845. if (this._animatables[0]) {
  93846. this._animatables[0].onAnimationEnd = null;
  93847. this._animatables[0].stop();
  93848. }
  93849. this._animatables.shift();
  93850. }
  93851. };
  93852. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  93853. /**
  93854. * Gets a value indicating if the user is moving the camera
  93855. */
  93856. get: function () {
  93857. if (!this._attachedCamera) {
  93858. return false;
  93859. }
  93860. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  93861. this._attachedCamera.inertialBetaOffset !== 0 ||
  93862. this._attachedCamera.inertialRadiusOffset !== 0 ||
  93863. this._attachedCamera.inertialPanningX !== 0 ||
  93864. this._attachedCamera.inertialPanningY !== 0 ||
  93865. this._isPointerDown;
  93866. },
  93867. enumerable: true,
  93868. configurable: true
  93869. });
  93870. /**
  93871. * The easing function used by animations
  93872. */
  93873. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  93874. /**
  93875. * The easing mode used by animations
  93876. */
  93877. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  93878. // Statics
  93879. /**
  93880. * The camera can move all the way towards the mesh.
  93881. */
  93882. FramingBehavior.IgnoreBoundsSizeMode = 0;
  93883. /**
  93884. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  93885. */
  93886. FramingBehavior.FitFrustumSidesMode = 1;
  93887. return FramingBehavior;
  93888. }());
  93889. BABYLON.FramingBehavior = FramingBehavior;
  93890. })(BABYLON || (BABYLON = {}));
  93891. //# sourceMappingURL=babylon.framingBehavior.js.map
  93892. var BABYLON;
  93893. (function (BABYLON) {
  93894. /**
  93895. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  93896. */
  93897. var BouncingBehavior = /** @class */ (function () {
  93898. function BouncingBehavior() {
  93899. /**
  93900. * The duration of the animation, in milliseconds
  93901. */
  93902. this.transitionDuration = 450;
  93903. /**
  93904. * Length of the distance animated by the transition when lower radius is reached
  93905. */
  93906. this.lowerRadiusTransitionRange = 2;
  93907. /**
  93908. * Length of the distance animated by the transition when upper radius is reached
  93909. */
  93910. this.upperRadiusTransitionRange = -2;
  93911. this._autoTransitionRange = false;
  93912. // Animations
  93913. this._radiusIsAnimating = false;
  93914. this._radiusBounceTransition = null;
  93915. this._animatables = new Array();
  93916. }
  93917. Object.defineProperty(BouncingBehavior.prototype, "name", {
  93918. get: function () {
  93919. return "Bouncing";
  93920. },
  93921. enumerable: true,
  93922. configurable: true
  93923. });
  93924. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  93925. /**
  93926. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93927. */
  93928. get: function () {
  93929. return this._autoTransitionRange;
  93930. },
  93931. /**
  93932. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  93933. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  93934. */
  93935. set: function (value) {
  93936. var _this = this;
  93937. if (this._autoTransitionRange === value) {
  93938. return;
  93939. }
  93940. this._autoTransitionRange = value;
  93941. var camera = this._attachedCamera;
  93942. if (!camera) {
  93943. return;
  93944. }
  93945. if (value) {
  93946. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  93947. if (!mesh) {
  93948. return;
  93949. }
  93950. mesh.computeWorldMatrix(true);
  93951. var diagonal = mesh.getBoundingInfo().diagonalLength;
  93952. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  93953. _this.upperRadiusTransitionRange = diagonal * 0.05;
  93954. });
  93955. }
  93956. else if (this._onMeshTargetChangedObserver) {
  93957. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93958. }
  93959. },
  93960. enumerable: true,
  93961. configurable: true
  93962. });
  93963. BouncingBehavior.prototype.init = function () {
  93964. // Do notihng
  93965. };
  93966. BouncingBehavior.prototype.attach = function (camera) {
  93967. var _this = this;
  93968. this._attachedCamera = camera;
  93969. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  93970. if (!_this._attachedCamera) {
  93971. return;
  93972. }
  93973. // Add the bounce animation to the lower radius limit
  93974. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  93975. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  93976. }
  93977. // Add the bounce animation to the upper radius limit
  93978. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  93979. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  93980. }
  93981. });
  93982. };
  93983. BouncingBehavior.prototype.detach = function () {
  93984. if (!this._attachedCamera) {
  93985. return;
  93986. }
  93987. if (this._onAfterCheckInputsObserver) {
  93988. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  93989. }
  93990. if (this._onMeshTargetChangedObserver) {
  93991. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  93992. }
  93993. this._attachedCamera = null;
  93994. };
  93995. /**
  93996. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  93997. * @param radiusLimit The limit to check against.
  93998. * @return Bool to indicate if at limit.
  93999. */
  94000. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94001. if (!this._attachedCamera) {
  94002. return false;
  94003. }
  94004. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94005. return true;
  94006. }
  94007. return false;
  94008. };
  94009. /**
  94010. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94011. * @param radiusDelta The delta by which to animate to. Can be negative.
  94012. */
  94013. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94014. var _this = this;
  94015. if (!this._attachedCamera) {
  94016. return;
  94017. }
  94018. if (!this._radiusBounceTransition) {
  94019. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94020. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94021. }
  94022. // Prevent zoom until bounce has completed
  94023. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94024. this._attachedCamera.wheelPrecision = Infinity;
  94025. this._attachedCamera.inertialRadiusOffset = 0;
  94026. // Animate to the radius limit
  94027. this.stopAllAnimations();
  94028. this._radiusIsAnimating = true;
  94029. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94030. if (animatable) {
  94031. this._animatables.push(animatable);
  94032. }
  94033. };
  94034. /**
  94035. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94036. */
  94037. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94038. this._radiusIsAnimating = false;
  94039. if (this._attachedCamera) {
  94040. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94041. }
  94042. };
  94043. /**
  94044. * Stops and removes all animations that have been applied to the camera
  94045. */
  94046. BouncingBehavior.prototype.stopAllAnimations = function () {
  94047. if (this._attachedCamera) {
  94048. this._attachedCamera.animations = [];
  94049. }
  94050. while (this._animatables.length) {
  94051. this._animatables[0].onAnimationEnd = null;
  94052. this._animatables[0].stop();
  94053. this._animatables.shift();
  94054. }
  94055. };
  94056. /**
  94057. * The easing function used by animations
  94058. */
  94059. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94060. /**
  94061. * The easing mode used by animations
  94062. */
  94063. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94064. return BouncingBehavior;
  94065. }());
  94066. BABYLON.BouncingBehavior = BouncingBehavior;
  94067. })(BABYLON || (BABYLON = {}));
  94068. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94069. var BABYLON;
  94070. (function (BABYLON) {
  94071. var AutoRotationBehavior = /** @class */ (function () {
  94072. function AutoRotationBehavior() {
  94073. this._zoomStopsAnimation = false;
  94074. this._idleRotationSpeed = 0.05;
  94075. this._idleRotationWaitTime = 2000;
  94076. this._idleRotationSpinupTime = 2000;
  94077. this._isPointerDown = false;
  94078. this._lastFrameTime = null;
  94079. this._lastInteractionTime = -Infinity;
  94080. this._cameraRotationSpeed = 0;
  94081. this._lastFrameRadius = 0;
  94082. }
  94083. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94084. get: function () {
  94085. return "AutoRotation";
  94086. },
  94087. enumerable: true,
  94088. configurable: true
  94089. });
  94090. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94091. /**
  94092. * Gets the flag that indicates if user zooming should stop animation.
  94093. */
  94094. get: function () {
  94095. return this._zoomStopsAnimation;
  94096. },
  94097. /**
  94098. * Sets the flag that indicates if user zooming should stop animation.
  94099. */
  94100. set: function (flag) {
  94101. this._zoomStopsAnimation = flag;
  94102. },
  94103. enumerable: true,
  94104. configurable: true
  94105. });
  94106. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94107. /**
  94108. * Gets the default speed at which the camera rotates around the model.
  94109. */
  94110. get: function () {
  94111. return this._idleRotationSpeed;
  94112. },
  94113. /**
  94114. * Sets the default speed at which the camera rotates around the model.
  94115. */
  94116. set: function (speed) {
  94117. this._idleRotationSpeed = speed;
  94118. },
  94119. enumerable: true,
  94120. configurable: true
  94121. });
  94122. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94123. /**
  94124. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94125. */
  94126. get: function () {
  94127. return this._idleRotationWaitTime;
  94128. },
  94129. /**
  94130. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94131. */
  94132. set: function (time) {
  94133. this._idleRotationWaitTime = time;
  94134. },
  94135. enumerable: true,
  94136. configurable: true
  94137. });
  94138. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94139. /**
  94140. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94141. */
  94142. get: function () {
  94143. return this._idleRotationSpinupTime;
  94144. },
  94145. /**
  94146. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94147. */
  94148. set: function (time) {
  94149. this._idleRotationSpinupTime = time;
  94150. },
  94151. enumerable: true,
  94152. configurable: true
  94153. });
  94154. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94155. /**
  94156. * Gets a value indicating if the camera is currently rotating because of this behavior
  94157. */
  94158. get: function () {
  94159. return Math.abs(this._cameraRotationSpeed) > 0;
  94160. },
  94161. enumerable: true,
  94162. configurable: true
  94163. });
  94164. AutoRotationBehavior.prototype.init = function () {
  94165. // Do notihng
  94166. };
  94167. AutoRotationBehavior.prototype.attach = function (camera) {
  94168. var _this = this;
  94169. this._attachedCamera = camera;
  94170. var scene = this._attachedCamera.getScene();
  94171. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94172. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94173. _this._isPointerDown = true;
  94174. return;
  94175. }
  94176. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94177. _this._isPointerDown = false;
  94178. }
  94179. });
  94180. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94181. var now = BABYLON.Tools.Now;
  94182. var dt = 0;
  94183. if (_this._lastFrameTime != null) {
  94184. dt = now - _this._lastFrameTime;
  94185. }
  94186. _this._lastFrameTime = now;
  94187. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94188. _this._applyUserInteraction();
  94189. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94190. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94191. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94192. // Step camera rotation by rotation speed
  94193. if (_this._attachedCamera) {
  94194. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94195. }
  94196. });
  94197. };
  94198. AutoRotationBehavior.prototype.detach = function () {
  94199. if (!this._attachedCamera) {
  94200. return;
  94201. }
  94202. var scene = this._attachedCamera.getScene();
  94203. if (this._onPrePointerObservableObserver) {
  94204. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94205. }
  94206. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94207. this._attachedCamera = null;
  94208. };
  94209. /**
  94210. * Returns true if user is scrolling.
  94211. * @return true if user is scrolling.
  94212. */
  94213. AutoRotationBehavior.prototype._userIsZooming = function () {
  94214. if (!this._attachedCamera) {
  94215. return false;
  94216. }
  94217. return this._attachedCamera.inertialRadiusOffset !== 0;
  94218. };
  94219. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94220. if (!this._attachedCamera) {
  94221. return false;
  94222. }
  94223. var zoomHasHitLimit = false;
  94224. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94225. zoomHasHitLimit = true;
  94226. }
  94227. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94228. this._lastFrameRadius = this._attachedCamera.radius;
  94229. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94230. };
  94231. /**
  94232. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94233. */
  94234. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94235. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94236. this._lastInteractionTime = BABYLON.Tools.Now;
  94237. }
  94238. };
  94239. // Tools
  94240. AutoRotationBehavior.prototype._userIsMoving = function () {
  94241. if (!this._attachedCamera) {
  94242. return false;
  94243. }
  94244. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94245. this._attachedCamera.inertialBetaOffset !== 0 ||
  94246. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94247. this._attachedCamera.inertialPanningX !== 0 ||
  94248. this._attachedCamera.inertialPanningY !== 0 ||
  94249. this._isPointerDown;
  94250. };
  94251. return AutoRotationBehavior;
  94252. }());
  94253. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94254. })(BABYLON || (BABYLON = {}));
  94255. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94256. var BABYLON;
  94257. (function (BABYLON) {
  94258. var NullEngineOptions = /** @class */ (function () {
  94259. function NullEngineOptions() {
  94260. this.renderWidth = 512;
  94261. this.renderHeight = 256;
  94262. this.textureSize = 512;
  94263. this.deterministicLockstep = false;
  94264. this.lockstepMaxSteps = 4;
  94265. }
  94266. return NullEngineOptions;
  94267. }());
  94268. BABYLON.NullEngineOptions = NullEngineOptions;
  94269. /**
  94270. * The null engine class provides support for headless version of babylon.js.
  94271. * This can be used in server side scenario or for testing purposes
  94272. */
  94273. var NullEngine = /** @class */ (function (_super) {
  94274. __extends(NullEngine, _super);
  94275. function NullEngine(options) {
  94276. if (options === void 0) { options = new NullEngineOptions(); }
  94277. var _this = _super.call(this, null) || this;
  94278. if (options.deterministicLockstep === undefined) {
  94279. options.deterministicLockstep = false;
  94280. }
  94281. if (options.lockstepMaxSteps === undefined) {
  94282. options.lockstepMaxSteps = 4;
  94283. }
  94284. _this._options = options;
  94285. // Init caps
  94286. // We consider we are on a webgl1 capable device
  94287. _this._caps = new BABYLON.EngineCapabilities();
  94288. _this._caps.maxTexturesImageUnits = 16;
  94289. _this._caps.maxVertexTextureImageUnits = 16;
  94290. _this._caps.maxTextureSize = 512;
  94291. _this._caps.maxCubemapTextureSize = 512;
  94292. _this._caps.maxRenderTextureSize = 512;
  94293. _this._caps.maxVertexAttribs = 16;
  94294. _this._caps.maxVaryingVectors = 16;
  94295. _this._caps.maxFragmentUniformVectors = 16;
  94296. _this._caps.maxVertexUniformVectors = 16;
  94297. // Extensions
  94298. _this._caps.standardDerivatives = false;
  94299. _this._caps.astc = null;
  94300. _this._caps.s3tc = null;
  94301. _this._caps.pvrtc = null;
  94302. _this._caps.etc1 = null;
  94303. _this._caps.etc2 = null;
  94304. _this._caps.textureAnisotropicFilterExtension = null;
  94305. _this._caps.maxAnisotropy = 0;
  94306. _this._caps.uintIndices = false;
  94307. _this._caps.fragmentDepthSupported = false;
  94308. _this._caps.highPrecisionShaderSupported = true;
  94309. _this._caps.colorBufferFloat = false;
  94310. _this._caps.textureFloat = false;
  94311. _this._caps.textureFloatLinearFiltering = false;
  94312. _this._caps.textureFloatRender = false;
  94313. _this._caps.textureHalfFloat = false;
  94314. _this._caps.textureHalfFloatLinearFiltering = false;
  94315. _this._caps.textureHalfFloatRender = false;
  94316. _this._caps.textureLOD = false;
  94317. _this._caps.drawBuffersExtension = false;
  94318. _this._caps.depthTextureExtension = false;
  94319. _this._caps.vertexArrayObject = false;
  94320. _this._caps.instancedArrays = false;
  94321. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94322. // Wrappers
  94323. if (typeof URL === "undefined") {
  94324. URL = {
  94325. createObjectURL: function () { },
  94326. revokeObjectURL: function () { }
  94327. };
  94328. }
  94329. if (typeof Blob === "undefined") {
  94330. Blob = function () { };
  94331. }
  94332. return _this;
  94333. }
  94334. NullEngine.prototype.isDeterministicLockStep = function () {
  94335. return this._options.deterministicLockstep;
  94336. };
  94337. NullEngine.prototype.getLockstepMaxSteps = function () {
  94338. return this._options.lockstepMaxSteps;
  94339. };
  94340. NullEngine.prototype.getHardwareScalingLevel = function () {
  94341. return 1.0;
  94342. };
  94343. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94344. return {
  94345. capacity: 0,
  94346. references: 1,
  94347. is32Bits: false
  94348. };
  94349. };
  94350. NullEngine.prototype.createIndexBuffer = function (indices) {
  94351. return {
  94352. capacity: 0,
  94353. references: 1,
  94354. is32Bits: false
  94355. };
  94356. };
  94357. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94358. if (stencil === void 0) { stencil = false; }
  94359. };
  94360. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94361. if (useScreen === void 0) { useScreen = false; }
  94362. if (!useScreen && this._currentRenderTarget) {
  94363. return this._currentRenderTarget.width;
  94364. }
  94365. return this._options.renderWidth;
  94366. };
  94367. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94368. if (useScreen === void 0) { useScreen = false; }
  94369. if (!useScreen && this._currentRenderTarget) {
  94370. return this._currentRenderTarget.height;
  94371. }
  94372. return this._options.renderHeight;
  94373. };
  94374. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94375. this._cachedViewport = viewport;
  94376. };
  94377. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94378. return {
  94379. transformFeedback: null,
  94380. __SPECTOR_rebuildProgram: null
  94381. };
  94382. };
  94383. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94384. return [];
  94385. };
  94386. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94387. return [];
  94388. };
  94389. NullEngine.prototype.bindSamplers = function (effect) {
  94390. this._currentEffect = null;
  94391. };
  94392. NullEngine.prototype.enableEffect = function (effect) {
  94393. this._currentEffect = effect;
  94394. if (effect.onBind) {
  94395. effect.onBind(effect);
  94396. }
  94397. effect.onBindObservable.notifyObservers(effect);
  94398. };
  94399. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94400. if (zOffset === void 0) { zOffset = 0; }
  94401. if (reverseSide === void 0) { reverseSide = false; }
  94402. };
  94403. NullEngine.prototype.setIntArray = function (uniform, array) {
  94404. };
  94405. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94406. };
  94407. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94408. };
  94409. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94410. };
  94411. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94412. };
  94413. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94414. };
  94415. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94416. };
  94417. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94418. };
  94419. NullEngine.prototype.setArray = function (uniform, array) {
  94420. };
  94421. NullEngine.prototype.setArray2 = function (uniform, array) {
  94422. };
  94423. NullEngine.prototype.setArray3 = function (uniform, array) {
  94424. };
  94425. NullEngine.prototype.setArray4 = function (uniform, array) {
  94426. };
  94427. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94428. };
  94429. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94430. };
  94431. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94432. };
  94433. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94434. };
  94435. NullEngine.prototype.setFloat = function (uniform, value) {
  94436. };
  94437. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94438. };
  94439. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94440. };
  94441. NullEngine.prototype.setBool = function (uniform, bool) {
  94442. };
  94443. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94444. };
  94445. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94446. };
  94447. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94448. };
  94449. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94450. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94451. if (this._alphaMode === mode) {
  94452. return;
  94453. }
  94454. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94455. if (!noDepthWriteChange) {
  94456. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  94457. }
  94458. this._alphaMode = mode;
  94459. };
  94460. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  94461. };
  94462. NullEngine.prototype.wipeCaches = function (bruteForce) {
  94463. if (this.preventCacheWipeBetweenFrames) {
  94464. return;
  94465. }
  94466. this.resetTextureCache();
  94467. this._currentEffect = null;
  94468. if (bruteForce) {
  94469. this._currentProgram = null;
  94470. this._stencilState.reset();
  94471. this._depthCullingState.reset();
  94472. this._alphaState.reset();
  94473. }
  94474. this._cachedVertexBuffers = null;
  94475. this._cachedIndexBuffer = null;
  94476. this._cachedEffectForVertexBuffers = null;
  94477. };
  94478. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  94479. };
  94480. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  94481. };
  94482. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  94483. };
  94484. NullEngine.prototype._createTexture = function () {
  94485. return {};
  94486. };
  94487. NullEngine.prototype._releaseTexture = function (texture) {
  94488. };
  94489. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  94490. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94491. if (onLoad === void 0) { onLoad = null; }
  94492. if (onError === void 0) { onError = null; }
  94493. if (buffer === void 0) { buffer = null; }
  94494. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  94495. var url = String(urlArg);
  94496. texture.url = url;
  94497. texture.generateMipMaps = !noMipmap;
  94498. texture.samplingMode = samplingMode;
  94499. texture.invertY = invertY;
  94500. texture.baseWidth = this._options.textureSize;
  94501. texture.baseHeight = this._options.textureSize;
  94502. texture.width = this._options.textureSize;
  94503. texture.height = this._options.textureSize;
  94504. if (format) {
  94505. texture.format = format;
  94506. }
  94507. texture.isReady = true;
  94508. if (onLoad) {
  94509. onLoad();
  94510. }
  94511. return texture;
  94512. };
  94513. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  94514. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  94515. if (options !== undefined && typeof options === "object") {
  94516. fullOptions.generateMipMaps = options.generateMipMaps;
  94517. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  94518. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  94519. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  94520. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  94521. }
  94522. else {
  94523. fullOptions.generateMipMaps = options;
  94524. fullOptions.generateDepthBuffer = true;
  94525. fullOptions.generateStencilBuffer = false;
  94526. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  94527. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  94528. }
  94529. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  94530. var width = size.width || size;
  94531. var height = size.height || size;
  94532. texture._depthStencilBuffer = {};
  94533. texture._framebuffer = {};
  94534. texture.baseWidth = width;
  94535. texture.baseHeight = height;
  94536. texture.width = width;
  94537. texture.height = height;
  94538. texture.isReady = true;
  94539. texture.samples = 1;
  94540. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  94541. texture.samplingMode = fullOptions.samplingMode;
  94542. texture.type = fullOptions.type;
  94543. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  94544. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  94545. return texture;
  94546. };
  94547. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  94548. texture.samplingMode = samplingMode;
  94549. };
  94550. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  94551. if (this._currentRenderTarget) {
  94552. this.unBindFramebuffer(this._currentRenderTarget);
  94553. }
  94554. this._currentRenderTarget = texture;
  94555. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  94556. if (this._cachedViewport && !forceFullscreenViewport) {
  94557. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  94558. }
  94559. };
  94560. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  94561. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  94562. this._currentRenderTarget = null;
  94563. if (onBeforeUnbind) {
  94564. if (texture._MSAAFramebuffer) {
  94565. this._currentFramebuffer = texture._framebuffer;
  94566. }
  94567. onBeforeUnbind();
  94568. }
  94569. this._currentFramebuffer = null;
  94570. };
  94571. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  94572. var vbo = {
  94573. capacity: 1,
  94574. references: 1,
  94575. is32Bits: false
  94576. };
  94577. return vbo;
  94578. };
  94579. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  94580. if (offset === void 0) { offset = 0; }
  94581. };
  94582. /**
  94583. * Updates a dynamic vertex buffer.
  94584. * @param vertexBuffer the vertex buffer to update
  94585. * @param data the data used to update the vertex buffer
  94586. * @param byteOffset the byte offset of the data (optional)
  94587. * @param byteLength the byte length of the data (optional)
  94588. */
  94589. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  94590. };
  94591. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  94592. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  94593. this._boundTexturesCache[this._activeChannel] = texture;
  94594. }
  94595. };
  94596. NullEngine.prototype._bindTexture = function (channel, texture) {
  94597. if (channel < 0) {
  94598. return;
  94599. }
  94600. this._bindTextureDirectly(0, texture);
  94601. };
  94602. NullEngine.prototype._releaseBuffer = function (buffer) {
  94603. buffer.references--;
  94604. if (buffer.references === 0) {
  94605. return true;
  94606. }
  94607. return false;
  94608. };
  94609. return NullEngine;
  94610. }(BABYLON.Engine));
  94611. BABYLON.NullEngine = NullEngine;
  94612. })(BABYLON || (BABYLON = {}));
  94613. //# sourceMappingURL=babylon.nullEngine.js.map
  94614. var BABYLON;
  94615. (function (BABYLON) {
  94616. /**
  94617. * This class can be used to get instrumentation data from a Babylon engine
  94618. */
  94619. var EngineInstrumentation = /** @class */ (function () {
  94620. function EngineInstrumentation(engine) {
  94621. this.engine = engine;
  94622. this._captureGPUFrameTime = false;
  94623. this._gpuFrameTime = new BABYLON.PerfCounter();
  94624. this._captureShaderCompilationTime = false;
  94625. this._shaderCompilationTime = new BABYLON.PerfCounter();
  94626. // Observers
  94627. this._onBeginFrameObserver = null;
  94628. this._onEndFrameObserver = null;
  94629. this._onBeforeShaderCompilationObserver = null;
  94630. this._onAfterShaderCompilationObserver = null;
  94631. }
  94632. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  94633. // Properties
  94634. /**
  94635. * Gets the perf counter used for GPU frame time
  94636. */
  94637. get: function () {
  94638. return this._gpuFrameTime;
  94639. },
  94640. enumerable: true,
  94641. configurable: true
  94642. });
  94643. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  94644. /**
  94645. * Gets the GPU frame time capture status
  94646. */
  94647. get: function () {
  94648. return this._captureGPUFrameTime;
  94649. },
  94650. /**
  94651. * Enable or disable the GPU frame time capture
  94652. */
  94653. set: function (value) {
  94654. var _this = this;
  94655. if (value === this._captureGPUFrameTime) {
  94656. return;
  94657. }
  94658. this._captureGPUFrameTime = value;
  94659. if (value) {
  94660. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  94661. if (!_this._gpuFrameTimeToken) {
  94662. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  94663. }
  94664. });
  94665. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  94666. if (!_this._gpuFrameTimeToken) {
  94667. return;
  94668. }
  94669. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  94670. if (time > -1) {
  94671. _this._gpuFrameTimeToken = null;
  94672. _this._gpuFrameTime.fetchNewFrame();
  94673. _this._gpuFrameTime.addCount(time, true);
  94674. }
  94675. });
  94676. }
  94677. else {
  94678. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94679. this._onBeginFrameObserver = null;
  94680. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94681. this._onEndFrameObserver = null;
  94682. }
  94683. },
  94684. enumerable: true,
  94685. configurable: true
  94686. });
  94687. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  94688. /**
  94689. * Gets the perf counter used for shader compilation time
  94690. */
  94691. get: function () {
  94692. return this._shaderCompilationTime;
  94693. },
  94694. enumerable: true,
  94695. configurable: true
  94696. });
  94697. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  94698. /**
  94699. * Gets the shader compilation time capture status
  94700. */
  94701. get: function () {
  94702. return this._captureShaderCompilationTime;
  94703. },
  94704. /**
  94705. * Enable or disable the shader compilation time capture
  94706. */
  94707. set: function (value) {
  94708. var _this = this;
  94709. if (value === this._captureShaderCompilationTime) {
  94710. return;
  94711. }
  94712. this._captureShaderCompilationTime = value;
  94713. if (value) {
  94714. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  94715. _this._shaderCompilationTime.fetchNewFrame();
  94716. _this._shaderCompilationTime.beginMonitoring();
  94717. });
  94718. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  94719. _this._shaderCompilationTime.endMonitoring();
  94720. });
  94721. }
  94722. else {
  94723. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94724. this._onBeforeShaderCompilationObserver = null;
  94725. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94726. this._onAfterShaderCompilationObserver = null;
  94727. }
  94728. },
  94729. enumerable: true,
  94730. configurable: true
  94731. });
  94732. EngineInstrumentation.prototype.dispose = function () {
  94733. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  94734. this._onBeginFrameObserver = null;
  94735. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  94736. this._onEndFrameObserver = null;
  94737. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  94738. this._onBeforeShaderCompilationObserver = null;
  94739. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  94740. this._onAfterShaderCompilationObserver = null;
  94741. this.engine = null;
  94742. };
  94743. return EngineInstrumentation;
  94744. }());
  94745. BABYLON.EngineInstrumentation = EngineInstrumentation;
  94746. })(BABYLON || (BABYLON = {}));
  94747. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  94748. var BABYLON;
  94749. (function (BABYLON) {
  94750. /**
  94751. * This class can be used to get instrumentation data from a Babylon engine
  94752. */
  94753. var SceneInstrumentation = /** @class */ (function () {
  94754. function SceneInstrumentation(scene) {
  94755. var _this = this;
  94756. this.scene = scene;
  94757. this._captureActiveMeshesEvaluationTime = false;
  94758. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  94759. this._captureRenderTargetsRenderTime = false;
  94760. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  94761. this._captureFrameTime = false;
  94762. this._frameTime = new BABYLON.PerfCounter();
  94763. this._captureRenderTime = false;
  94764. this._renderTime = new BABYLON.PerfCounter();
  94765. this._captureInterFrameTime = false;
  94766. this._interFrameTime = new BABYLON.PerfCounter();
  94767. this._captureParticlesRenderTime = false;
  94768. this._particlesRenderTime = new BABYLON.PerfCounter();
  94769. this._captureSpritesRenderTime = false;
  94770. this._spritesRenderTime = new BABYLON.PerfCounter();
  94771. this._capturePhysicsTime = false;
  94772. this._physicsTime = new BABYLON.PerfCounter();
  94773. this._captureAnimationsTime = false;
  94774. this._animationsTime = new BABYLON.PerfCounter();
  94775. // Observers
  94776. this._onBeforeActiveMeshesEvaluationObserver = null;
  94777. this._onAfterActiveMeshesEvaluationObserver = null;
  94778. this._onBeforeRenderTargetsRenderObserver = null;
  94779. this._onAfterRenderTargetsRenderObserver = null;
  94780. this._onAfterRenderObserver = null;
  94781. this._onBeforeDrawPhaseObserver = null;
  94782. this._onAfterDrawPhaseObserver = null;
  94783. this._onBeforeAnimationsObserver = null;
  94784. this._onBeforeParticlesRenderingObserver = null;
  94785. this._onAfterParticlesRenderingObserver = null;
  94786. this._onBeforeSpritesRenderingObserver = null;
  94787. this._onAfterSpritesRenderingObserver = null;
  94788. this._onBeforePhysicsObserver = null;
  94789. this._onAfterPhysicsObserver = null;
  94790. this._onAfterAnimationsObserver = null;
  94791. // Before render
  94792. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  94793. if (_this._captureActiveMeshesEvaluationTime) {
  94794. _this._activeMeshesEvaluationTime.fetchNewFrame();
  94795. }
  94796. if (_this._captureRenderTargetsRenderTime) {
  94797. _this._renderTargetsRenderTime.fetchNewFrame();
  94798. }
  94799. if (_this._captureFrameTime) {
  94800. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  94801. _this._frameTime.beginMonitoring();
  94802. }
  94803. if (_this._captureInterFrameTime) {
  94804. _this._interFrameTime.endMonitoring();
  94805. }
  94806. if (_this._captureParticlesRenderTime) {
  94807. _this._particlesRenderTime.fetchNewFrame();
  94808. }
  94809. if (_this._captureSpritesRenderTime) {
  94810. _this._spritesRenderTime.fetchNewFrame();
  94811. }
  94812. if (_this._captureAnimationsTime) {
  94813. _this._animationsTime.beginMonitoring();
  94814. }
  94815. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  94816. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  94817. });
  94818. // After render
  94819. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  94820. if (_this._captureFrameTime) {
  94821. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  94822. _this._frameTime.endMonitoring();
  94823. }
  94824. if (_this._captureRenderTime) {
  94825. _this._renderTime.endMonitoring(false);
  94826. }
  94827. if (_this._captureInterFrameTime) {
  94828. _this._interFrameTime.beginMonitoring();
  94829. }
  94830. });
  94831. }
  94832. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  94833. // Properties
  94834. /**
  94835. * Gets the perf counter used for active meshes evaluation time
  94836. */
  94837. get: function () {
  94838. return this._activeMeshesEvaluationTime;
  94839. },
  94840. enumerable: true,
  94841. configurable: true
  94842. });
  94843. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  94844. /**
  94845. * Gets the active meshes evaluation time capture status
  94846. */
  94847. get: function () {
  94848. return this._captureActiveMeshesEvaluationTime;
  94849. },
  94850. /**
  94851. * Enable or disable the active meshes evaluation time capture
  94852. */
  94853. set: function (value) {
  94854. var _this = this;
  94855. if (value === this._captureActiveMeshesEvaluationTime) {
  94856. return;
  94857. }
  94858. this._captureActiveMeshesEvaluationTime = value;
  94859. if (value) {
  94860. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  94861. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  94862. _this._activeMeshesEvaluationTime.beginMonitoring();
  94863. });
  94864. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  94865. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  94866. _this._activeMeshesEvaluationTime.endMonitoring();
  94867. });
  94868. }
  94869. else {
  94870. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  94871. this._onBeforeActiveMeshesEvaluationObserver = null;
  94872. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  94873. this._onAfterActiveMeshesEvaluationObserver = null;
  94874. }
  94875. },
  94876. enumerable: true,
  94877. configurable: true
  94878. });
  94879. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  94880. /**
  94881. * Gets the perf counter used for render targets render time
  94882. */
  94883. get: function () {
  94884. return this._renderTargetsRenderTime;
  94885. },
  94886. enumerable: true,
  94887. configurable: true
  94888. });
  94889. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  94890. /**
  94891. * Gets the render targets render time capture status
  94892. */
  94893. get: function () {
  94894. return this._captureRenderTargetsRenderTime;
  94895. },
  94896. /**
  94897. * Enable or disable the render targets render time capture
  94898. */
  94899. set: function (value) {
  94900. var _this = this;
  94901. if (value === this._captureRenderTargetsRenderTime) {
  94902. return;
  94903. }
  94904. this._captureRenderTargetsRenderTime = value;
  94905. if (value) {
  94906. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  94907. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  94908. _this._renderTargetsRenderTime.beginMonitoring();
  94909. });
  94910. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  94911. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  94912. _this._renderTargetsRenderTime.endMonitoring(false);
  94913. });
  94914. }
  94915. else {
  94916. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  94917. this._onBeforeRenderTargetsRenderObserver = null;
  94918. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  94919. this._onAfterRenderTargetsRenderObserver = null;
  94920. }
  94921. },
  94922. enumerable: true,
  94923. configurable: true
  94924. });
  94925. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  94926. /**
  94927. * Gets the perf counter used for particles render time
  94928. */
  94929. get: function () {
  94930. return this._particlesRenderTime;
  94931. },
  94932. enumerable: true,
  94933. configurable: true
  94934. });
  94935. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  94936. /**
  94937. * Gets the particles render time capture status
  94938. */
  94939. get: function () {
  94940. return this._captureParticlesRenderTime;
  94941. },
  94942. /**
  94943. * Enable or disable the particles render time capture
  94944. */
  94945. set: function (value) {
  94946. var _this = this;
  94947. if (value === this._captureParticlesRenderTime) {
  94948. return;
  94949. }
  94950. this._captureParticlesRenderTime = value;
  94951. if (value) {
  94952. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  94953. BABYLON.Tools.StartPerformanceCounter("Particles");
  94954. _this._particlesRenderTime.beginMonitoring();
  94955. });
  94956. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  94957. BABYLON.Tools.EndPerformanceCounter("Particles");
  94958. _this._particlesRenderTime.endMonitoring(false);
  94959. });
  94960. }
  94961. else {
  94962. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  94963. this._onBeforeParticlesRenderingObserver = null;
  94964. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  94965. this._onAfterParticlesRenderingObserver = null;
  94966. }
  94967. },
  94968. enumerable: true,
  94969. configurable: true
  94970. });
  94971. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  94972. /**
  94973. * Gets the perf counter used for sprites render time
  94974. */
  94975. get: function () {
  94976. return this._spritesRenderTime;
  94977. },
  94978. enumerable: true,
  94979. configurable: true
  94980. });
  94981. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  94982. /**
  94983. * Gets the sprites render time capture status
  94984. */
  94985. get: function () {
  94986. return this._captureSpritesRenderTime;
  94987. },
  94988. /**
  94989. * Enable or disable the sprites render time capture
  94990. */
  94991. set: function (value) {
  94992. var _this = this;
  94993. if (value === this._captureSpritesRenderTime) {
  94994. return;
  94995. }
  94996. this._captureSpritesRenderTime = value;
  94997. if (value) {
  94998. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  94999. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95000. _this._spritesRenderTime.beginMonitoring();
  95001. });
  95002. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95003. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95004. _this._spritesRenderTime.endMonitoring(false);
  95005. });
  95006. }
  95007. else {
  95008. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95009. this._onBeforeSpritesRenderingObserver = null;
  95010. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95011. this._onAfterSpritesRenderingObserver = null;
  95012. }
  95013. },
  95014. enumerable: true,
  95015. configurable: true
  95016. });
  95017. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95018. /**
  95019. * Gets the perf counter used for physics time
  95020. */
  95021. get: function () {
  95022. return this._physicsTime;
  95023. },
  95024. enumerable: true,
  95025. configurable: true
  95026. });
  95027. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95028. /**
  95029. * Gets the physics time capture status
  95030. */
  95031. get: function () {
  95032. return this._capturePhysicsTime;
  95033. },
  95034. /**
  95035. * Enable or disable the physics time capture
  95036. */
  95037. set: function (value) {
  95038. var _this = this;
  95039. if (value === this._capturePhysicsTime) {
  95040. return;
  95041. }
  95042. this._capturePhysicsTime = value;
  95043. if (value) {
  95044. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95045. BABYLON.Tools.StartPerformanceCounter("Physics");
  95046. _this._physicsTime.beginMonitoring();
  95047. });
  95048. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95049. BABYLON.Tools.EndPerformanceCounter("Physics");
  95050. _this._physicsTime.endMonitoring();
  95051. });
  95052. }
  95053. else {
  95054. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95055. this._onBeforePhysicsObserver = null;
  95056. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95057. this._onAfterPhysicsObserver = null;
  95058. }
  95059. },
  95060. enumerable: true,
  95061. configurable: true
  95062. });
  95063. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95064. /**
  95065. * Gets the perf counter used for animations time
  95066. */
  95067. get: function () {
  95068. return this._animationsTime;
  95069. },
  95070. enumerable: true,
  95071. configurable: true
  95072. });
  95073. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95074. /**
  95075. * Gets the animations time capture status
  95076. */
  95077. get: function () {
  95078. return this._captureAnimationsTime;
  95079. },
  95080. /**
  95081. * Enable or disable the animations time capture
  95082. */
  95083. set: function (value) {
  95084. var _this = this;
  95085. if (value === this._captureAnimationsTime) {
  95086. return;
  95087. }
  95088. this._captureAnimationsTime = value;
  95089. if (value) {
  95090. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95091. _this._animationsTime.endMonitoring();
  95092. });
  95093. }
  95094. else {
  95095. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95096. this._onAfterAnimationsObserver = null;
  95097. }
  95098. },
  95099. enumerable: true,
  95100. configurable: true
  95101. });
  95102. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95103. /**
  95104. * Gets the perf counter used for frame time capture
  95105. */
  95106. get: function () {
  95107. return this._frameTime;
  95108. },
  95109. enumerable: true,
  95110. configurable: true
  95111. });
  95112. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95113. /**
  95114. * Gets the frame time capture status
  95115. */
  95116. get: function () {
  95117. return this._captureFrameTime;
  95118. },
  95119. /**
  95120. * Enable or disable the frame time capture
  95121. */
  95122. set: function (value) {
  95123. this._captureFrameTime = value;
  95124. },
  95125. enumerable: true,
  95126. configurable: true
  95127. });
  95128. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95129. /**
  95130. * Gets the perf counter used for inter-frames time capture
  95131. */
  95132. get: function () {
  95133. return this._interFrameTime;
  95134. },
  95135. enumerable: true,
  95136. configurable: true
  95137. });
  95138. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95139. /**
  95140. * Gets the inter-frames time capture status
  95141. */
  95142. get: function () {
  95143. return this._captureInterFrameTime;
  95144. },
  95145. /**
  95146. * Enable or disable the inter-frames time capture
  95147. */
  95148. set: function (value) {
  95149. this._captureInterFrameTime = value;
  95150. },
  95151. enumerable: true,
  95152. configurable: true
  95153. });
  95154. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95155. /**
  95156. * Gets the perf counter used for render time capture
  95157. */
  95158. get: function () {
  95159. return this._renderTime;
  95160. },
  95161. enumerable: true,
  95162. configurable: true
  95163. });
  95164. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95165. /**
  95166. * Gets the render time capture status
  95167. */
  95168. get: function () {
  95169. return this._captureRenderTime;
  95170. },
  95171. /**
  95172. * Enable or disable the render time capture
  95173. */
  95174. set: function (value) {
  95175. var _this = this;
  95176. if (value === this._captureRenderTime) {
  95177. return;
  95178. }
  95179. this._captureRenderTime = value;
  95180. if (value) {
  95181. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95182. _this._renderTime.beginMonitoring();
  95183. BABYLON.Tools.StartPerformanceCounter("Main render");
  95184. });
  95185. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95186. _this._renderTime.endMonitoring(false);
  95187. BABYLON.Tools.EndPerformanceCounter("Main render");
  95188. });
  95189. }
  95190. else {
  95191. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95192. this._onBeforeDrawPhaseObserver = null;
  95193. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95194. this._onAfterDrawPhaseObserver = null;
  95195. }
  95196. },
  95197. enumerable: true,
  95198. configurable: true
  95199. });
  95200. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95201. /**
  95202. * Gets the perf counter used for draw calls
  95203. */
  95204. get: function () {
  95205. return this.scene.getEngine()._drawCalls;
  95206. },
  95207. enumerable: true,
  95208. configurable: true
  95209. });
  95210. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95211. /**
  95212. * Gets the perf counter used for texture collisions
  95213. */
  95214. get: function () {
  95215. return this.scene.getEngine()._textureCollisions;
  95216. },
  95217. enumerable: true,
  95218. configurable: true
  95219. });
  95220. SceneInstrumentation.prototype.dispose = function () {
  95221. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95222. this._onAfterRenderObserver = null;
  95223. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95224. this._onBeforeActiveMeshesEvaluationObserver = null;
  95225. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95226. this._onAfterActiveMeshesEvaluationObserver = null;
  95227. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95228. this._onBeforeRenderTargetsRenderObserver = null;
  95229. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95230. this._onAfterRenderTargetsRenderObserver = null;
  95231. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95232. this._onBeforeAnimationsObserver = null;
  95233. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95234. this._onBeforeParticlesRenderingObserver = null;
  95235. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95236. this._onAfterParticlesRenderingObserver = null;
  95237. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95238. this._onBeforeSpritesRenderingObserver = null;
  95239. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95240. this._onAfterSpritesRenderingObserver = null;
  95241. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95242. this._onBeforeDrawPhaseObserver = null;
  95243. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95244. this._onAfterDrawPhaseObserver = null;
  95245. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95246. this._onBeforePhysicsObserver = null;
  95247. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95248. this._onAfterPhysicsObserver = null;
  95249. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95250. this._onAfterAnimationsObserver = null;
  95251. this.scene = null;
  95252. };
  95253. return SceneInstrumentation;
  95254. }());
  95255. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95256. })(BABYLON || (BABYLON = {}));
  95257. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95258. var BABYLON;
  95259. (function (BABYLON) {
  95260. var _TimeToken = /** @class */ (function () {
  95261. function _TimeToken() {
  95262. this._timeElapsedQueryEnded = false;
  95263. }
  95264. return _TimeToken;
  95265. }());
  95266. BABYLON._TimeToken = _TimeToken;
  95267. })(BABYLON || (BABYLON = {}));
  95268. //# sourceMappingURL=babylon.timeToken.js.map
  95269. var BABYLON;
  95270. (function (BABYLON) {
  95271. /**
  95272. * Background material defines definition.
  95273. * @ignore Mainly internal Use
  95274. */
  95275. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95276. __extends(BackgroundMaterialDefines, _super);
  95277. /**
  95278. * Constructor of the defines.
  95279. */
  95280. function BackgroundMaterialDefines() {
  95281. var _this = _super.call(this) || this;
  95282. /**
  95283. * True if the diffuse texture is in use.
  95284. */
  95285. _this.DIFFUSE = false;
  95286. /**
  95287. * The direct UV channel to use.
  95288. */
  95289. _this.DIFFUSEDIRECTUV = 0;
  95290. /**
  95291. * True if the diffuse texture is in gamma space.
  95292. */
  95293. _this.GAMMADIFFUSE = false;
  95294. /**
  95295. * True if the diffuse texture has opacity in the alpha channel.
  95296. */
  95297. _this.DIFFUSEHASALPHA = false;
  95298. /**
  95299. * True if you want the material to fade to transparent at grazing angle.
  95300. */
  95301. _this.OPACITYFRESNEL = false;
  95302. /**
  95303. * True if an extra blur needs to be added in the reflection.
  95304. */
  95305. _this.REFLECTIONBLUR = false;
  95306. /**
  95307. * True if you want the material to fade to reflection at grazing angle.
  95308. */
  95309. _this.REFLECTIONFRESNEL = false;
  95310. /**
  95311. * True if you want the material to falloff as far as you move away from the scene center.
  95312. */
  95313. _this.REFLECTIONFALLOFF = false;
  95314. /**
  95315. * False if the current Webgl implementation does not support the texture lod extension.
  95316. */
  95317. _this.TEXTURELODSUPPORT = false;
  95318. /**
  95319. * True to ensure the data are premultiplied.
  95320. */
  95321. _this.PREMULTIPLYALPHA = false;
  95322. /**
  95323. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95324. */
  95325. _this.USERGBCOLOR = false;
  95326. /**
  95327. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95328. * stays aligned with the desired configuration.
  95329. */
  95330. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95331. /**
  95332. * True to add noise in order to reduce the banding effect.
  95333. */
  95334. _this.NOISE = false;
  95335. /**
  95336. * is the reflection texture in BGR color scheme?
  95337. * Mainly used to solve a bug in ios10 video tag
  95338. */
  95339. _this.REFLECTIONBGR = false;
  95340. _this.IMAGEPROCESSING = false;
  95341. _this.VIGNETTE = false;
  95342. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95343. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95344. _this.TONEMAPPING = false;
  95345. _this.CONTRAST = false;
  95346. _this.COLORCURVES = false;
  95347. _this.COLORGRADING = false;
  95348. _this.COLORGRADING3D = false;
  95349. _this.SAMPLER3DGREENDEPTH = false;
  95350. _this.SAMPLER3DBGRMAP = false;
  95351. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95352. _this.EXPOSURE = false;
  95353. // Reflection.
  95354. _this.REFLECTION = false;
  95355. _this.REFLECTIONMAP_3D = false;
  95356. _this.REFLECTIONMAP_SPHERICAL = false;
  95357. _this.REFLECTIONMAP_PLANAR = false;
  95358. _this.REFLECTIONMAP_CUBIC = false;
  95359. _this.REFLECTIONMAP_PROJECTION = false;
  95360. _this.REFLECTIONMAP_SKYBOX = false;
  95361. _this.REFLECTIONMAP_EXPLICIT = false;
  95362. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95363. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95364. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95365. _this.INVERTCUBICMAP = false;
  95366. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95367. _this.LODINREFLECTIONALPHA = false;
  95368. _this.GAMMAREFLECTION = false;
  95369. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95370. // Default BJS.
  95371. _this.MAINUV1 = false;
  95372. _this.MAINUV2 = false;
  95373. _this.UV1 = false;
  95374. _this.UV2 = false;
  95375. _this.CLIPPLANE = false;
  95376. _this.POINTSIZE = false;
  95377. _this.FOG = false;
  95378. _this.NORMAL = false;
  95379. _this.NUM_BONE_INFLUENCERS = 0;
  95380. _this.BonesPerMesh = 0;
  95381. _this.INSTANCES = false;
  95382. _this.SHADOWFLOAT = false;
  95383. _this.rebuild();
  95384. return _this;
  95385. }
  95386. return BackgroundMaterialDefines;
  95387. }(BABYLON.MaterialDefines));
  95388. /**
  95389. * Background material used to create an efficient environement around your scene.
  95390. */
  95391. var BackgroundMaterial = /** @class */ (function (_super) {
  95392. __extends(BackgroundMaterial, _super);
  95393. /**
  95394. * Instantiates a Background Material in the given scene
  95395. * @param name The friendly name of the material
  95396. * @param scene The scene to add the material to
  95397. */
  95398. function BackgroundMaterial(name, scene) {
  95399. var _this = _super.call(this, name, scene) || this;
  95400. /**
  95401. * Key light Color (multiply against the environement texture)
  95402. */
  95403. _this.primaryColor = BABYLON.Color3.White();
  95404. _this._primaryColorShadowLevel = 0;
  95405. _this._primaryColorHighlightLevel = 0;
  95406. /**
  95407. * Reflection Texture used in the material.
  95408. * Should be author in a specific way for the best result (refer to the documentation).
  95409. */
  95410. _this.reflectionTexture = null;
  95411. /**
  95412. * Reflection Texture level of blur.
  95413. *
  95414. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95415. * texture twice.
  95416. */
  95417. _this.reflectionBlur = 0;
  95418. /**
  95419. * Diffuse Texture used in the material.
  95420. * Should be author in a specific way for the best result (refer to the documentation).
  95421. */
  95422. _this.diffuseTexture = null;
  95423. _this._shadowLights = null;
  95424. /**
  95425. * Specify the list of lights casting shadow on the material.
  95426. * All scene shadow lights will be included if null.
  95427. */
  95428. _this.shadowLights = null;
  95429. /**
  95430. * Helps adjusting the shadow to a softer level if required.
  95431. * 0 means black shadows and 1 means no shadows.
  95432. */
  95433. _this.shadowLevel = 0;
  95434. /**
  95435. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95436. * It is usually zero but might be interesting to modify according to your setup.
  95437. */
  95438. _this.sceneCenter = BABYLON.Vector3.Zero();
  95439. /**
  95440. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95441. * This helps ensuring a nice transition when the camera goes under the ground.
  95442. */
  95443. _this.opacityFresnel = true;
  95444. /**
  95445. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95446. * This helps adding a mirror texture on the ground.
  95447. */
  95448. _this.reflectionFresnel = false;
  95449. /**
  95450. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  95451. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  95452. */
  95453. _this.reflectionFalloffDistance = 0.0;
  95454. /**
  95455. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  95456. */
  95457. _this.reflectionAmount = 1.0;
  95458. /**
  95459. * This specifies the weight of the reflection at grazing angle.
  95460. */
  95461. _this.reflectionReflectance0 = 0.05;
  95462. /**
  95463. * This specifies the weight of the reflection at a perpendicular point of view.
  95464. */
  95465. _this.reflectionReflectance90 = 0.5;
  95466. /**
  95467. * Helps to directly use the maps channels instead of their level.
  95468. */
  95469. _this.useRGBColor = true;
  95470. /**
  95471. * This helps reducing the banding effect that could occur on the background.
  95472. */
  95473. _this.enableNoise = false;
  95474. _this._fovMultiplier = 1.0;
  95475. /**
  95476. * Enable the FOV adjustment feature controlled by fovMultiplier.
  95477. */
  95478. _this.useEquirectangularFOV = false;
  95479. _this._maxSimultaneousLights = 4;
  95480. /**
  95481. * Number of Simultaneous lights allowed on the material.
  95482. */
  95483. _this.maxSimultaneousLights = 4;
  95484. /**
  95485. * Keep track of the image processing observer to allow dispose and replace.
  95486. */
  95487. _this._imageProcessingObserver = null;
  95488. /**
  95489. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  95490. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  95491. */
  95492. _this.switchToBGR = false;
  95493. // Temp values kept as cache in the material.
  95494. _this._renderTargets = new BABYLON.SmartArray(16);
  95495. _this._reflectionControls = BABYLON.Vector4.Zero();
  95496. _this._white = BABYLON.Color3.White();
  95497. _this._primaryShadowColor = BABYLON.Color3.Black();
  95498. _this._primaryHighlightColor = BABYLON.Color3.Black();
  95499. // Setup the default processing configuration to the scene.
  95500. _this._attachImageProcessingConfiguration(null);
  95501. _this.getRenderTargetTextures = function () {
  95502. _this._renderTargets.reset();
  95503. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  95504. _this._renderTargets.push(_this._diffuseTexture);
  95505. }
  95506. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  95507. _this._renderTargets.push(_this._reflectionTexture);
  95508. }
  95509. return _this._renderTargets;
  95510. };
  95511. return _this;
  95512. }
  95513. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  95514. /**
  95515. * Experimental Internal Use Only.
  95516. *
  95517. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  95518. * This acts as a helper to set the primary color to a more "human friendly" value.
  95519. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  95520. * output color as close as possible from the chosen value.
  95521. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  95522. * part of lighting setup.)
  95523. */
  95524. get: function () {
  95525. return this.__perceptualColor;
  95526. },
  95527. set: function (value) {
  95528. this.__perceptualColor = value;
  95529. this._computePrimaryColorFromPerceptualColor();
  95530. this._markAllSubMeshesAsLightsDirty();
  95531. },
  95532. enumerable: true,
  95533. configurable: true
  95534. });
  95535. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  95536. /**
  95537. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  95538. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  95539. */
  95540. get: function () {
  95541. return this._primaryColorShadowLevel;
  95542. },
  95543. set: function (value) {
  95544. this._primaryColorShadowLevel = value;
  95545. this._computePrimaryColors();
  95546. this._markAllSubMeshesAsLightsDirty();
  95547. },
  95548. enumerable: true,
  95549. configurable: true
  95550. });
  95551. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  95552. /**
  95553. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  95554. * The primary color is used at the level chosen to define what the white area would look.
  95555. */
  95556. get: function () {
  95557. return this._primaryColorHighlightLevel;
  95558. },
  95559. set: function (value) {
  95560. this._primaryColorHighlightLevel = value;
  95561. this._computePrimaryColors();
  95562. this._markAllSubMeshesAsLightsDirty();
  95563. },
  95564. enumerable: true,
  95565. configurable: true
  95566. });
  95567. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  95568. /**
  95569. * Sets the reflection reflectance fresnel values according to the default standard
  95570. * empirically know to work well :-)
  95571. */
  95572. set: function (value) {
  95573. var reflectionWeight = value;
  95574. if (reflectionWeight < 0.5) {
  95575. reflectionWeight = reflectionWeight * 2.0;
  95576. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  95577. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  95578. }
  95579. else {
  95580. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  95581. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  95582. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  95583. }
  95584. },
  95585. enumerable: true,
  95586. configurable: true
  95587. });
  95588. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  95589. /**
  95590. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  95591. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  95592. * Recommended to be keep at 1.0 except for special cases.
  95593. */
  95594. get: function () {
  95595. return this._fovMultiplier;
  95596. },
  95597. set: function (value) {
  95598. if (isNaN(value)) {
  95599. value = 1.0;
  95600. }
  95601. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  95602. },
  95603. enumerable: true,
  95604. configurable: true
  95605. });
  95606. /**
  95607. * Attaches a new image processing configuration to the PBR Material.
  95608. * @param configuration (if null the scene configuration will be use)
  95609. */
  95610. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  95611. var _this = this;
  95612. if (configuration === this._imageProcessingConfiguration) {
  95613. return;
  95614. }
  95615. // Detaches observer.
  95616. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  95617. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  95618. }
  95619. // Pick the scene configuration if needed.
  95620. if (!configuration) {
  95621. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  95622. }
  95623. else {
  95624. this._imageProcessingConfiguration = configuration;
  95625. }
  95626. // Attaches observer.
  95627. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  95628. _this._computePrimaryColorFromPerceptualColor();
  95629. _this._markAllSubMeshesAsImageProcessingDirty();
  95630. });
  95631. };
  95632. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  95633. /**
  95634. * Gets the image processing configuration used either in this material.
  95635. */
  95636. get: function () {
  95637. return this._imageProcessingConfiguration;
  95638. },
  95639. /**
  95640. * Sets the Default image processing configuration used either in the this material.
  95641. *
  95642. * If sets to null, the scene one is in use.
  95643. */
  95644. set: function (value) {
  95645. this._attachImageProcessingConfiguration(value);
  95646. // Ensure the effect will be rebuilt.
  95647. this._markAllSubMeshesAsTexturesDirty();
  95648. },
  95649. enumerable: true,
  95650. configurable: true
  95651. });
  95652. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  95653. /**
  95654. * Gets wether the color curves effect is enabled.
  95655. */
  95656. get: function () {
  95657. return this.imageProcessingConfiguration.colorCurvesEnabled;
  95658. },
  95659. /**
  95660. * Sets wether the color curves effect is enabled.
  95661. */
  95662. set: function (value) {
  95663. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  95664. },
  95665. enumerable: true,
  95666. configurable: true
  95667. });
  95668. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  95669. /**
  95670. * Gets wether the color grading effect is enabled.
  95671. */
  95672. get: function () {
  95673. return this.imageProcessingConfiguration.colorGradingEnabled;
  95674. },
  95675. /**
  95676. * Gets wether the color grading effect is enabled.
  95677. */
  95678. set: function (value) {
  95679. this.imageProcessingConfiguration.colorGradingEnabled = value;
  95680. },
  95681. enumerable: true,
  95682. configurable: true
  95683. });
  95684. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  95685. /**
  95686. * Gets wether tonemapping is enabled or not.
  95687. */
  95688. get: function () {
  95689. return this._imageProcessingConfiguration.toneMappingEnabled;
  95690. },
  95691. /**
  95692. * Sets wether tonemapping is enabled or not
  95693. */
  95694. set: function (value) {
  95695. this._imageProcessingConfiguration.toneMappingEnabled = value;
  95696. },
  95697. enumerable: true,
  95698. configurable: true
  95699. });
  95700. ;
  95701. ;
  95702. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  95703. /**
  95704. * The camera exposure used on this material.
  95705. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95706. * This corresponds to a photographic exposure.
  95707. */
  95708. get: function () {
  95709. return this._imageProcessingConfiguration.exposure;
  95710. },
  95711. /**
  95712. * The camera exposure used on this material.
  95713. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  95714. * This corresponds to a photographic exposure.
  95715. */
  95716. set: function (value) {
  95717. this._imageProcessingConfiguration.exposure = value;
  95718. },
  95719. enumerable: true,
  95720. configurable: true
  95721. });
  95722. ;
  95723. ;
  95724. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  95725. /**
  95726. * Gets The camera contrast used on this material.
  95727. */
  95728. get: function () {
  95729. return this._imageProcessingConfiguration.contrast;
  95730. },
  95731. /**
  95732. * Sets The camera contrast used on this material.
  95733. */
  95734. set: function (value) {
  95735. this._imageProcessingConfiguration.contrast = value;
  95736. },
  95737. enumerable: true,
  95738. configurable: true
  95739. });
  95740. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  95741. /**
  95742. * Gets the Color Grading 2D Lookup Texture.
  95743. */
  95744. get: function () {
  95745. return this._imageProcessingConfiguration.colorGradingTexture;
  95746. },
  95747. /**
  95748. * Sets the Color Grading 2D Lookup Texture.
  95749. */
  95750. set: function (value) {
  95751. this.imageProcessingConfiguration.colorGradingTexture = value;
  95752. },
  95753. enumerable: true,
  95754. configurable: true
  95755. });
  95756. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  95757. /**
  95758. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95759. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95760. * 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;
  95761. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95762. */
  95763. get: function () {
  95764. return this.imageProcessingConfiguration.colorCurves;
  95765. },
  95766. /**
  95767. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  95768. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  95769. * 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;
  95770. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  95771. */
  95772. set: function (value) {
  95773. this.imageProcessingConfiguration.colorCurves = value;
  95774. },
  95775. enumerable: true,
  95776. configurable: true
  95777. });
  95778. /**
  95779. * The entire material has been created in order to prevent overdraw.
  95780. * @returns false
  95781. */
  95782. BackgroundMaterial.prototype.needAlphaTesting = function () {
  95783. return true;
  95784. };
  95785. /**
  95786. * The entire material has been created in order to prevent overdraw.
  95787. * @returns true if blending is enable
  95788. */
  95789. BackgroundMaterial.prototype.needAlphaBlending = function () {
  95790. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  95791. };
  95792. /**
  95793. * Checks wether the material is ready to be rendered for a given mesh.
  95794. * @param mesh The mesh to render
  95795. * @param subMesh The submesh to check against
  95796. * @param useInstances Specify wether or not the material is used with instances
  95797. * @returns true if all the dependencies are ready (Textures, Effects...)
  95798. */
  95799. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  95800. var _this = this;
  95801. if (useInstances === void 0) { useInstances = false; }
  95802. if (subMesh.effect && this.isFrozen) {
  95803. if (this._wasPreviouslyReady) {
  95804. return true;
  95805. }
  95806. }
  95807. if (!subMesh._materialDefines) {
  95808. subMesh._materialDefines = new BackgroundMaterialDefines();
  95809. }
  95810. var scene = this.getScene();
  95811. var defines = subMesh._materialDefines;
  95812. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  95813. if (defines._renderId === scene.getRenderId()) {
  95814. return true;
  95815. }
  95816. }
  95817. var engine = scene.getEngine();
  95818. // Lights
  95819. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  95820. defines._needNormals = true;
  95821. // Textures
  95822. if (defines._areTexturesDirty) {
  95823. defines._needUVs = false;
  95824. if (scene.texturesEnabled) {
  95825. if (scene.getEngine().getCaps().textureLOD) {
  95826. defines.TEXTURELODSUPPORT = true;
  95827. }
  95828. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  95829. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  95830. return false;
  95831. }
  95832. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  95833. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  95834. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  95835. defines.OPACITYFRESNEL = this._opacityFresnel;
  95836. }
  95837. else {
  95838. defines.DIFFUSE = false;
  95839. defines.DIFFUSEHASALPHA = false;
  95840. defines.GAMMADIFFUSE = false;
  95841. defines.OPACITYFRESNEL = false;
  95842. }
  95843. var reflectionTexture = this._reflectionTexture;
  95844. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  95845. if (!reflectionTexture.isReadyOrNotBlocking()) {
  95846. return false;
  95847. }
  95848. defines.REFLECTION = true;
  95849. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  95850. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  95851. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  95852. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  95853. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  95854. defines.REFLECTIONBGR = this.switchToBGR;
  95855. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  95856. defines.INVERTCUBICMAP = true;
  95857. }
  95858. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  95859. switch (reflectionTexture.coordinatesMode) {
  95860. case BABYLON.Texture.CUBIC_MODE:
  95861. case BABYLON.Texture.INVCUBIC_MODE:
  95862. defines.REFLECTIONMAP_CUBIC = true;
  95863. break;
  95864. case BABYLON.Texture.EXPLICIT_MODE:
  95865. defines.REFLECTIONMAP_EXPLICIT = true;
  95866. break;
  95867. case BABYLON.Texture.PLANAR_MODE:
  95868. defines.REFLECTIONMAP_PLANAR = true;
  95869. break;
  95870. case BABYLON.Texture.PROJECTION_MODE:
  95871. defines.REFLECTIONMAP_PROJECTION = true;
  95872. break;
  95873. case BABYLON.Texture.SKYBOX_MODE:
  95874. defines.REFLECTIONMAP_SKYBOX = true;
  95875. break;
  95876. case BABYLON.Texture.SPHERICAL_MODE:
  95877. defines.REFLECTIONMAP_SPHERICAL = true;
  95878. break;
  95879. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  95880. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  95881. break;
  95882. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  95883. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  95884. break;
  95885. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  95886. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  95887. break;
  95888. }
  95889. if (this.reflectionFresnel) {
  95890. defines.REFLECTIONFRESNEL = true;
  95891. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  95892. this._reflectionControls.x = this.reflectionAmount;
  95893. this._reflectionControls.y = this.reflectionReflectance0;
  95894. this._reflectionControls.z = this.reflectionReflectance90;
  95895. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  95896. }
  95897. else {
  95898. defines.REFLECTIONFRESNEL = false;
  95899. defines.REFLECTIONFALLOFF = false;
  95900. }
  95901. }
  95902. else {
  95903. defines.REFLECTION = false;
  95904. defines.REFLECTIONFRESNEL = false;
  95905. defines.REFLECTIONFALLOFF = false;
  95906. defines.REFLECTIONBLUR = false;
  95907. defines.REFLECTIONMAP_3D = false;
  95908. defines.REFLECTIONMAP_SPHERICAL = false;
  95909. defines.REFLECTIONMAP_PLANAR = false;
  95910. defines.REFLECTIONMAP_CUBIC = false;
  95911. defines.REFLECTIONMAP_PROJECTION = false;
  95912. defines.REFLECTIONMAP_SKYBOX = false;
  95913. defines.REFLECTIONMAP_EXPLICIT = false;
  95914. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95915. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95916. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95917. defines.INVERTCUBICMAP = false;
  95918. defines.REFLECTIONMAP_OPPOSITEZ = false;
  95919. defines.LODINREFLECTIONALPHA = false;
  95920. defines.GAMMAREFLECTION = false;
  95921. }
  95922. }
  95923. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  95924. defines.USERGBCOLOR = this._useRGBColor;
  95925. defines.NOISE = this._enableNoise;
  95926. }
  95927. if (defines._areLightsDirty) {
  95928. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  95929. }
  95930. if (defines._areImageProcessingDirty) {
  95931. if (!this._imageProcessingConfiguration.isReady()) {
  95932. return false;
  95933. }
  95934. this._imageProcessingConfiguration.prepareDefines(defines);
  95935. }
  95936. // Misc.
  95937. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  95938. // Values that need to be evaluated on every frame
  95939. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  95940. // Attribs
  95941. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  95942. if (mesh) {
  95943. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  95944. mesh.createNormals(true);
  95945. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  95946. }
  95947. }
  95948. }
  95949. // Get correct effect
  95950. if (defines.isDirty) {
  95951. defines.markAsProcessed();
  95952. scene.resetCachedMaterial();
  95953. // Fallbacks
  95954. var fallbacks = new BABYLON.EffectFallbacks();
  95955. if (defines.FOG) {
  95956. fallbacks.addFallback(0, "FOG");
  95957. }
  95958. if (defines.POINTSIZE) {
  95959. fallbacks.addFallback(1, "POINTSIZE");
  95960. }
  95961. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  95962. if (defines.NUM_BONE_INFLUENCERS > 0) {
  95963. fallbacks.addCPUSkinningFallback(0, mesh);
  95964. }
  95965. //Attributes
  95966. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95967. if (defines.NORMAL) {
  95968. attribs.push(BABYLON.VertexBuffer.NormalKind);
  95969. }
  95970. if (defines.UV1) {
  95971. attribs.push(BABYLON.VertexBuffer.UVKind);
  95972. }
  95973. if (defines.UV2) {
  95974. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95975. }
  95976. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  95977. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  95978. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  95979. "vFogInfos", "vFogColor", "pointSize",
  95980. "vClipPlane", "mBones",
  95981. "vPrimaryColor", "vPrimaryColorShadow",
  95982. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  95983. "shadowLevel", "alpha",
  95984. "vBackgroundCenter", "vReflectionControl",
  95985. "vDiffuseInfos", "diffuseMatrix",
  95986. ];
  95987. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  95988. var uniformBuffers = ["Material", "Scene"];
  95989. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  95990. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  95991. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  95992. uniformsNames: uniforms,
  95993. uniformBuffersNames: uniformBuffers,
  95994. samplers: samplers,
  95995. defines: defines,
  95996. maxSimultaneousLights: this._maxSimultaneousLights
  95997. });
  95998. var onCompiled = function (effect) {
  95999. if (_this.onCompiled) {
  96000. _this.onCompiled(effect);
  96001. }
  96002. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96003. };
  96004. var join = defines.toString();
  96005. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96006. attributes: attribs,
  96007. uniformsNames: uniforms,
  96008. uniformBuffersNames: uniformBuffers,
  96009. samplers: samplers,
  96010. defines: join,
  96011. fallbacks: fallbacks,
  96012. onCompiled: onCompiled,
  96013. onError: this.onError,
  96014. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96015. }, engine), defines);
  96016. this.buildUniformLayout();
  96017. }
  96018. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96019. return false;
  96020. }
  96021. defines._renderId = scene.getRenderId();
  96022. this._wasPreviouslyReady = true;
  96023. return true;
  96024. };
  96025. /**
  96026. * Compute the primary color according to the chosen perceptual color.
  96027. */
  96028. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96029. if (!this.__perceptualColor) {
  96030. return;
  96031. }
  96032. this._primaryColor.copyFrom(this.__perceptualColor);
  96033. // Revert gamma space.
  96034. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96035. // Revert image processing configuration.
  96036. if (this._imageProcessingConfiguration) {
  96037. // Revert Exposure.
  96038. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96039. }
  96040. this._computePrimaryColors();
  96041. };
  96042. /**
  96043. * Compute the highlights and shadow colors according to their chosen levels.
  96044. */
  96045. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96046. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96047. return;
  96048. }
  96049. // Find the highlight color based on the configuration.
  96050. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96051. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96052. // Find the shadow color based on the configuration.
  96053. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96054. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96055. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96056. };
  96057. /**
  96058. * Build the uniform buffer used in the material.
  96059. */
  96060. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96061. // Order is important !
  96062. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96063. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96064. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96065. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96066. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96067. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96068. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96069. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96070. this._uniformBuffer.addUniform("pointSize", 1);
  96071. this._uniformBuffer.addUniform("shadowLevel", 1);
  96072. this._uniformBuffer.addUniform("alpha", 1);
  96073. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96074. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96075. this._uniformBuffer.create();
  96076. };
  96077. /**
  96078. * Unbind the material.
  96079. */
  96080. BackgroundMaterial.prototype.unbind = function () {
  96081. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96082. this._uniformBuffer.setTexture("diffuseSampler", null);
  96083. }
  96084. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96085. this._uniformBuffer.setTexture("reflectionSampler", null);
  96086. }
  96087. _super.prototype.unbind.call(this);
  96088. };
  96089. /**
  96090. * Bind only the world matrix to the material.
  96091. * @param world The world matrix to bind.
  96092. */
  96093. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96094. this._activeEffect.setMatrix("world", world);
  96095. };
  96096. /**
  96097. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96098. * @param world The world matrix to bind.
  96099. * @param subMesh The submesh to bind for.
  96100. */
  96101. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96102. var scene = this.getScene();
  96103. var defines = subMesh._materialDefines;
  96104. if (!defines) {
  96105. return;
  96106. }
  96107. var effect = subMesh.effect;
  96108. if (!effect) {
  96109. return;
  96110. }
  96111. this._activeEffect = effect;
  96112. // Matrices
  96113. this.bindOnlyWorldMatrix(world);
  96114. // Bones
  96115. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96116. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96117. if (mustRebind) {
  96118. this._uniformBuffer.bindToEffect(effect, "Material");
  96119. this.bindViewProjection(effect);
  96120. var reflectionTexture = this._reflectionTexture;
  96121. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96122. // Texture uniforms
  96123. if (scene.texturesEnabled) {
  96124. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96125. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96126. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96127. }
  96128. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96129. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96130. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96131. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96132. }
  96133. }
  96134. if (this.shadowLevel > 0) {
  96135. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96136. }
  96137. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96138. // Point size
  96139. if (this.pointsCloud) {
  96140. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96141. }
  96142. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96143. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96144. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96145. }
  96146. else {
  96147. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96148. }
  96149. }
  96150. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96151. // Textures
  96152. if (scene.texturesEnabled) {
  96153. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96154. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96155. }
  96156. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96157. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96158. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96159. }
  96160. else if (!defines.REFLECTIONBLUR) {
  96161. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96162. }
  96163. else {
  96164. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96165. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96166. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96167. }
  96168. if (defines.REFLECTIONFRESNEL) {
  96169. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96170. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96171. }
  96172. }
  96173. }
  96174. // Clip plane
  96175. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96176. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96177. }
  96178. if (mustRebind || !this.isFrozen) {
  96179. if (scene.lightsEnabled) {
  96180. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96181. }
  96182. // View
  96183. this.bindView(effect);
  96184. // Fog
  96185. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96186. // image processing
  96187. this._imageProcessingConfiguration.bind(this._activeEffect);
  96188. }
  96189. this._uniformBuffer.update();
  96190. this._afterBind(mesh);
  96191. };
  96192. /**
  96193. * Dispose the material.
  96194. * @param forceDisposeEffect Force disposal of the associated effect.
  96195. * @param forceDisposeTextures Force disposal of the associated textures.
  96196. */
  96197. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96198. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96199. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96200. if (forceDisposeTextures) {
  96201. if (this.diffuseTexture) {
  96202. this.diffuseTexture.dispose();
  96203. }
  96204. if (this.reflectionTexture) {
  96205. this.reflectionTexture.dispose();
  96206. }
  96207. }
  96208. this._renderTargets.dispose();
  96209. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96210. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96211. }
  96212. _super.prototype.dispose.call(this, forceDisposeEffect);
  96213. };
  96214. /**
  96215. * Clones the material.
  96216. * @param name The cloned name.
  96217. * @returns The cloned material.
  96218. */
  96219. BackgroundMaterial.prototype.clone = function (name) {
  96220. var _this = this;
  96221. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96222. };
  96223. /**
  96224. * Serializes the current material to its JSON representation.
  96225. * @returns The JSON representation.
  96226. */
  96227. BackgroundMaterial.prototype.serialize = function () {
  96228. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96229. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96230. return serializationObject;
  96231. };
  96232. /**
  96233. * Gets the class name of the material
  96234. * @returns "BackgroundMaterial"
  96235. */
  96236. BackgroundMaterial.prototype.getClassName = function () {
  96237. return "BackgroundMaterial";
  96238. };
  96239. /**
  96240. * Parse a JSON input to create back a background material.
  96241. * @param source The JSON data to parse
  96242. * @param scene The scene to create the parsed material in
  96243. * @param rootUrl The root url of the assets the material depends upon
  96244. * @returns the instantiated BackgroundMaterial.
  96245. */
  96246. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96247. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96248. };
  96249. /**
  96250. * Standard reflectance value at parallel view angle.
  96251. */
  96252. BackgroundMaterial.StandardReflectance0 = 0.05;
  96253. /**
  96254. * Standard reflectance value at grazing angle.
  96255. */
  96256. BackgroundMaterial.StandardReflectance90 = 0.5;
  96257. __decorate([
  96258. BABYLON.serializeAsColor3()
  96259. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96260. __decorate([
  96261. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96262. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96263. __decorate([
  96264. BABYLON.serializeAsColor3()
  96265. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96266. __decorate([
  96267. BABYLON.serialize()
  96268. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96269. __decorate([
  96270. BABYLON.serialize()
  96271. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96272. __decorate([
  96273. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96274. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96275. __decorate([
  96276. BABYLON.serializeAsTexture()
  96277. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96278. __decorate([
  96279. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96280. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96281. __decorate([
  96282. BABYLON.serialize()
  96283. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96284. __decorate([
  96285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96286. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96287. __decorate([
  96288. BABYLON.serializeAsTexture()
  96289. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96290. __decorate([
  96291. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96292. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96293. __decorate([
  96294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96295. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96296. __decorate([
  96297. BABYLON.serialize()
  96298. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96299. __decorate([
  96300. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96301. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96302. __decorate([
  96303. BABYLON.serializeAsVector3()
  96304. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96305. __decorate([
  96306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96307. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96308. __decorate([
  96309. BABYLON.serialize()
  96310. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96311. __decorate([
  96312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96313. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96314. __decorate([
  96315. BABYLON.serialize()
  96316. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96317. __decorate([
  96318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96319. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96320. __decorate([
  96321. BABYLON.serialize()
  96322. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96323. __decorate([
  96324. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96325. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96326. __decorate([
  96327. BABYLON.serialize()
  96328. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96329. __decorate([
  96330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96331. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96332. __decorate([
  96333. BABYLON.serialize()
  96334. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96335. __decorate([
  96336. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96337. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96338. __decorate([
  96339. BABYLON.serialize()
  96340. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96341. __decorate([
  96342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96343. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96344. __decorate([
  96345. BABYLON.serialize()
  96346. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96347. __decorate([
  96348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96349. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96350. __decorate([
  96351. BABYLON.serialize()
  96352. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96353. __decorate([
  96354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96355. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96356. __decorate([
  96357. BABYLON.serialize()
  96358. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96359. __decorate([
  96360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96361. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96362. __decorate([
  96363. BABYLON.serializeAsImageProcessingConfiguration()
  96364. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96365. return BackgroundMaterial;
  96366. }(BABYLON.PushMaterial));
  96367. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96368. })(BABYLON || (BABYLON = {}));
  96369. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96370. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96371. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96372. s = arguments[i];
  96373. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96374. t[p] = s[p];
  96375. }
  96376. return t;
  96377. };
  96378. var BABYLON;
  96379. (function (BABYLON) {
  96380. /**
  96381. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96382. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96383. * It also helps with the default setup of your imageProcessing configuration.
  96384. */
  96385. var EnvironmentHelper = /** @class */ (function () {
  96386. /**
  96387. * constructor
  96388. * @param options
  96389. * @param scene The scene to add the material to
  96390. */
  96391. function EnvironmentHelper(options, scene) {
  96392. var _this = this;
  96393. this._errorHandler = function (message, exception) {
  96394. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96395. };
  96396. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96397. this._scene = scene;
  96398. this.onErrorObservable = new BABYLON.Observable();
  96399. this._setupBackground();
  96400. this._setupImageProcessing();
  96401. }
  96402. /**
  96403. * Creates the default options for the helper.
  96404. */
  96405. EnvironmentHelper._getDefaultOptions = function () {
  96406. return {
  96407. createGround: true,
  96408. groundSize: 15,
  96409. groundTexture: this._groundTextureCDNUrl,
  96410. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96411. groundOpacity: 0.9,
  96412. enableGroundShadow: true,
  96413. groundShadowLevel: 0.5,
  96414. enableGroundMirror: false,
  96415. groundMirrorSizeRatio: 0.3,
  96416. groundMirrorBlurKernel: 64,
  96417. groundMirrorAmount: 1,
  96418. groundMirrorFresnelWeight: 1,
  96419. groundMirrorFallOffDistance: 0,
  96420. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96421. groundYBias: 0.00001,
  96422. createSkybox: true,
  96423. skyboxSize: 20,
  96424. skyboxTexture: this._skyboxTextureCDNUrl,
  96425. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96426. backgroundYRotation: 0,
  96427. sizeAuto: true,
  96428. rootPosition: BABYLON.Vector3.Zero(),
  96429. setupImageProcessing: true,
  96430. environmentTexture: this._environmentTextureCDNUrl,
  96431. cameraExposure: 0.8,
  96432. cameraContrast: 1.2,
  96433. toneMappingEnabled: true,
  96434. };
  96435. };
  96436. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96437. /**
  96438. * Gets the root mesh created by the helper.
  96439. */
  96440. get: function () {
  96441. return this._rootMesh;
  96442. },
  96443. enumerable: true,
  96444. configurable: true
  96445. });
  96446. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96447. /**
  96448. * Gets the skybox created by the helper.
  96449. */
  96450. get: function () {
  96451. return this._skybox;
  96452. },
  96453. enumerable: true,
  96454. configurable: true
  96455. });
  96456. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  96457. /**
  96458. * Gets the skybox texture created by the helper.
  96459. */
  96460. get: function () {
  96461. return this._skyboxTexture;
  96462. },
  96463. enumerable: true,
  96464. configurable: true
  96465. });
  96466. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  96467. /**
  96468. * Gets the skybox material created by the helper.
  96469. */
  96470. get: function () {
  96471. return this._skyboxMaterial;
  96472. },
  96473. enumerable: true,
  96474. configurable: true
  96475. });
  96476. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  96477. /**
  96478. * Gets the ground mesh created by the helper.
  96479. */
  96480. get: function () {
  96481. return this._ground;
  96482. },
  96483. enumerable: true,
  96484. configurable: true
  96485. });
  96486. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  96487. /**
  96488. * Gets the ground texture created by the helper.
  96489. */
  96490. get: function () {
  96491. return this._groundTexture;
  96492. },
  96493. enumerable: true,
  96494. configurable: true
  96495. });
  96496. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  96497. /**
  96498. * Gets the ground mirror created by the helper.
  96499. */
  96500. get: function () {
  96501. return this._groundMirror;
  96502. },
  96503. enumerable: true,
  96504. configurable: true
  96505. });
  96506. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  96507. /**
  96508. * Gets the ground mirror render list to helps pushing the meshes
  96509. * you wish in the ground reflection.
  96510. */
  96511. get: function () {
  96512. if (this._groundMirror) {
  96513. return this._groundMirror.renderList;
  96514. }
  96515. return null;
  96516. },
  96517. enumerable: true,
  96518. configurable: true
  96519. });
  96520. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  96521. /**
  96522. * Gets the ground material created by the helper.
  96523. */
  96524. get: function () {
  96525. return this._groundMaterial;
  96526. },
  96527. enumerable: true,
  96528. configurable: true
  96529. });
  96530. /**
  96531. * Updates the background according to the new options
  96532. * @param options
  96533. */
  96534. EnvironmentHelper.prototype.updateOptions = function (options) {
  96535. var newOptions = __assign({}, this._options, options);
  96536. if (this._ground && !newOptions.createGround) {
  96537. this._ground.dispose();
  96538. this._ground = null;
  96539. }
  96540. if (this._groundMaterial && !newOptions.createGround) {
  96541. this._groundMaterial.dispose();
  96542. this._groundMaterial = null;
  96543. }
  96544. if (this._groundTexture) {
  96545. if (this._options.groundTexture != newOptions.groundTexture) {
  96546. this._groundTexture.dispose();
  96547. this._groundTexture = null;
  96548. }
  96549. }
  96550. if (this._skybox && !newOptions.createSkybox) {
  96551. this._skybox.dispose();
  96552. this._skybox = null;
  96553. }
  96554. if (this._skyboxMaterial && !newOptions.createSkybox) {
  96555. this._skyboxMaterial.dispose();
  96556. this._skyboxMaterial = null;
  96557. }
  96558. if (this._skyboxTexture) {
  96559. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  96560. this._skyboxTexture.dispose();
  96561. this._skyboxTexture = null;
  96562. }
  96563. }
  96564. if (this._groundMirror && !newOptions.enableGroundMirror) {
  96565. this._groundMirror.dispose();
  96566. this._groundMirror = null;
  96567. }
  96568. if (this._scene.environmentTexture) {
  96569. if (this._options.environmentTexture != newOptions.environmentTexture) {
  96570. this._scene.environmentTexture.dispose();
  96571. }
  96572. }
  96573. this._options = newOptions;
  96574. this._setupBackground();
  96575. this._setupImageProcessing();
  96576. };
  96577. /**
  96578. * Sets the primary color of all the available elements.
  96579. * @param color the main color to affect to the ground and the background
  96580. */
  96581. EnvironmentHelper.prototype.setMainColor = function (color) {
  96582. if (this.groundMaterial) {
  96583. this.groundMaterial.primaryColor = color;
  96584. }
  96585. if (this.skyboxMaterial) {
  96586. this.skyboxMaterial.primaryColor = color;
  96587. }
  96588. if (this.groundMirror) {
  96589. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  96590. }
  96591. };
  96592. /**
  96593. * Setup the image processing according to the specified options.
  96594. */
  96595. EnvironmentHelper.prototype._setupImageProcessing = function () {
  96596. if (this._options.setupImageProcessing) {
  96597. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  96598. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  96599. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  96600. this._setupEnvironmentTexture();
  96601. }
  96602. };
  96603. /**
  96604. * Setup the environment texture according to the specified options.
  96605. */
  96606. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  96607. if (this._scene.environmentTexture) {
  96608. return;
  96609. }
  96610. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  96611. this._scene.environmentTexture = this._options.environmentTexture;
  96612. return;
  96613. }
  96614. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  96615. this._scene.environmentTexture = environmentTexture;
  96616. };
  96617. /**
  96618. * Setup the background according to the specified options.
  96619. */
  96620. EnvironmentHelper.prototype._setupBackground = function () {
  96621. if (!this._rootMesh) {
  96622. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  96623. }
  96624. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  96625. var sceneSize = this._getSceneSize();
  96626. if (this._options.createGround) {
  96627. this._setupGround(sceneSize);
  96628. this._setupGroundMaterial();
  96629. this._setupGroundDiffuseTexture();
  96630. if (this._options.enableGroundMirror) {
  96631. this._setupGroundMirrorTexture(sceneSize);
  96632. }
  96633. this._setupMirrorInGroundMaterial();
  96634. }
  96635. if (this._options.createSkybox) {
  96636. this._setupSkybox(sceneSize);
  96637. this._setupSkyboxMaterial();
  96638. this._setupSkyboxReflectionTexture();
  96639. }
  96640. this._rootMesh.position.x = sceneSize.rootPosition.x;
  96641. this._rootMesh.position.z = sceneSize.rootPosition.z;
  96642. this._rootMesh.position.y = sceneSize.rootPosition.y;
  96643. };
  96644. /**
  96645. * Get the scene sizes according to the setup.
  96646. */
  96647. EnvironmentHelper.prototype._getSceneSize = function () {
  96648. var _this = this;
  96649. var groundSize = this._options.groundSize;
  96650. var skyboxSize = this._options.skyboxSize;
  96651. var rootPosition = this._options.rootPosition;
  96652. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  96653. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96654. }
  96655. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  96656. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  96657. });
  96658. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  96659. if (this._options.sizeAuto) {
  96660. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  96661. this._scene.activeCamera.upperRadiusLimit) {
  96662. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  96663. skyboxSize = groundSize;
  96664. }
  96665. var sceneDiagonalLenght = sceneDiagonal.length();
  96666. if (sceneDiagonalLenght > groundSize) {
  96667. groundSize = sceneDiagonalLenght * 2;
  96668. skyboxSize = groundSize;
  96669. }
  96670. // 10 % bigger.
  96671. groundSize *= 1.1;
  96672. skyboxSize *= 1.5;
  96673. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  96674. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  96675. }
  96676. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  96677. };
  96678. /**
  96679. * Setup the ground according to the specified options.
  96680. */
  96681. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  96682. var _this = this;
  96683. if (!this._ground) {
  96684. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  96685. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  96686. this._ground.parent = this._rootMesh;
  96687. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  96688. }
  96689. this._ground.receiveShadows = this._options.enableGroundShadow;
  96690. };
  96691. /**
  96692. * Setup the ground material according to the specified options.
  96693. */
  96694. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  96695. if (!this._groundMaterial) {
  96696. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  96697. }
  96698. this._groundMaterial.alpha = this._options.groundOpacity;
  96699. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  96700. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  96701. this._groundMaterial.primaryColor = this._options.groundColor;
  96702. this._groundMaterial.useRGBColor = false;
  96703. this._groundMaterial.enableNoise = true;
  96704. if (this._ground) {
  96705. this._ground.material = this._groundMaterial;
  96706. }
  96707. };
  96708. /**
  96709. * Setup the ground diffuse texture according to the specified options.
  96710. */
  96711. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  96712. if (!this._groundMaterial) {
  96713. return;
  96714. }
  96715. if (this._groundTexture) {
  96716. return;
  96717. }
  96718. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  96719. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  96720. return;
  96721. }
  96722. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96723. diffuseTexture.gammaSpace = false;
  96724. diffuseTexture.hasAlpha = true;
  96725. this._groundMaterial.diffuseTexture = diffuseTexture;
  96726. };
  96727. /**
  96728. * Setup the ground mirror texture according to the specified options.
  96729. */
  96730. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  96731. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96732. if (!this._groundMirror) {
  96733. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  96734. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  96735. this._groundMirror.anisotropicFilteringLevel = 1;
  96736. this._groundMirror.wrapU = wrapping;
  96737. this._groundMirror.wrapV = wrapping;
  96738. this._groundMirror.gammaSpace = false;
  96739. if (this._groundMirror.renderList) {
  96740. for (var i = 0; i < this._scene.meshes.length; i++) {
  96741. var mesh = this._scene.meshes[i];
  96742. if (mesh !== this._ground &&
  96743. mesh !== this._skybox &&
  96744. mesh !== this._rootMesh) {
  96745. this._groundMirror.renderList.push(mesh);
  96746. }
  96747. }
  96748. }
  96749. }
  96750. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  96751. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  96752. };
  96753. /**
  96754. * Setup the ground to receive the mirror texture.
  96755. */
  96756. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  96757. if (this._groundMaterial) {
  96758. this._groundMaterial.reflectionTexture = this._groundMirror;
  96759. this._groundMaterial.reflectionFresnel = true;
  96760. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  96761. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  96762. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  96763. }
  96764. };
  96765. /**
  96766. * Setup the skybox according to the specified options.
  96767. */
  96768. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  96769. var _this = this;
  96770. if (!this._skybox) {
  96771. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  96772. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  96773. }
  96774. this._skybox.parent = this._rootMesh;
  96775. };
  96776. /**
  96777. * Setup the skybox material according to the specified options.
  96778. */
  96779. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  96780. if (!this._skybox) {
  96781. return;
  96782. }
  96783. if (!this._skyboxMaterial) {
  96784. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  96785. }
  96786. this._skyboxMaterial.useRGBColor = false;
  96787. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  96788. this._skyboxMaterial.enableNoise = true;
  96789. this._skybox.material = this._skyboxMaterial;
  96790. };
  96791. /**
  96792. * Setup the skybox reflection texture according to the specified options.
  96793. */
  96794. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  96795. if (!this._skyboxMaterial) {
  96796. return;
  96797. }
  96798. if (this._skyboxTexture) {
  96799. return;
  96800. }
  96801. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  96802. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  96803. return;
  96804. }
  96805. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  96806. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  96807. this._skyboxTexture.gammaSpace = false;
  96808. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  96809. };
  96810. /**
  96811. * Dispose all the elements created by the Helper.
  96812. */
  96813. EnvironmentHelper.prototype.dispose = function () {
  96814. if (this._groundMaterial) {
  96815. this._groundMaterial.dispose(true, true);
  96816. }
  96817. if (this._skyboxMaterial) {
  96818. this._skyboxMaterial.dispose(true, true);
  96819. }
  96820. this._rootMesh.dispose(false);
  96821. };
  96822. /**
  96823. * Default ground texture URL.
  96824. */
  96825. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  96826. /**
  96827. * Default skybox texture URL.
  96828. */
  96829. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  96830. /**
  96831. * Default environment texture URL.
  96832. */
  96833. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  96834. return EnvironmentHelper;
  96835. }());
  96836. BABYLON.EnvironmentHelper = EnvironmentHelper;
  96837. })(BABYLON || (BABYLON = {}));
  96838. //# sourceMappingURL=babylon.environmentHelper.js.map
  96839. var BABYLON;
  96840. (function (BABYLON) {
  96841. /**
  96842. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  96843. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  96844. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  96845. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  96846. */
  96847. var VideoDome = /** @class */ (function (_super) {
  96848. __extends(VideoDome, _super);
  96849. /**
  96850. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  96851. * @param name Element's name, child elements will append suffixes for their own names.
  96852. * @param urlsOrVideo
  96853. * @param options An object containing optional or exposed sub element properties:
  96854. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  96855. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  96856. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  96857. * @param options **loop=true** Automatically loop video on end.
  96858. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  96859. */
  96860. function VideoDome(name, urlsOrVideo, options, scene) {
  96861. var _this = _super.call(this, name, scene) || this;
  96862. // set defaults and manage values
  96863. name = name || "videoDome";
  96864. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  96865. options.clickToPlay = Boolean(options.clickToPlay);
  96866. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  96867. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  96868. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  96869. // create
  96870. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  96871. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  96872. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  96873. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  96874. flat: false,
  96875. radius: options.size,
  96876. subdivisions: options.resolution,
  96877. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  96878. }, scene);
  96879. // configure material
  96880. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  96881. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  96882. material.reflectionTexture = _this._videoTexture;
  96883. material.useEquirectangularFOV = true;
  96884. material.fovMultiplier = 1.0;
  96885. // configure mesh
  96886. _this._mesh.material = material;
  96887. _this._mesh.parent = _this;
  96888. // optional configuration
  96889. if (options.clickToPlay) {
  96890. scene.onPointerUp = function () {
  96891. _this._videoTexture.video.play();
  96892. };
  96893. }
  96894. return _this;
  96895. }
  96896. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  96897. /**
  96898. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96899. * Also see the options.resolution property.
  96900. */
  96901. get: function () {
  96902. return this._material.fovMultiplier;
  96903. },
  96904. set: function (value) {
  96905. this._material.fovMultiplier = value;
  96906. },
  96907. enumerable: true,
  96908. configurable: true
  96909. });
  96910. /**
  96911. * Releases resources associated with this node.
  96912. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  96913. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  96914. */
  96915. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  96916. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  96917. this._videoTexture.dispose();
  96918. this._mesh.dispose();
  96919. this._material.dispose();
  96920. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  96921. };
  96922. return VideoDome;
  96923. }(BABYLON.Node));
  96924. BABYLON.VideoDome = VideoDome;
  96925. })(BABYLON || (BABYLON = {}));
  96926. //# sourceMappingURL=babylon.videoDome.js.map
  96927. 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(GEOMETRYAA)\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#ifdef GEOMETRYAA\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#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef GEOMETRYAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\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\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\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,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"};
  96928. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,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};"};